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;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
/// <summary>
/// A class that reads both primitive values and non-cyclical object graphs from a stream that was constructed using
/// the ObjectWriter class.
/// </summary>
internal sealed class ObjectReader : ObjectReaderWriterBase, IDisposable
{
private readonly BinaryReader _reader;
private readonly ObjectReaderData _dataMap;
private readonly ObjectBinder _binder;
internal ObjectReader(
Stream stream,
ObjectReaderData defaultData = null,
ObjectBinder binder = null)
{
// String serialization assumes both reader and writer to be of the same endianness.
// It can be adjusted for BigEndian if needed.
Debug.Assert(BitConverter.IsLittleEndian);
_reader = new BinaryReader(stream, Encoding.UTF8);
_dataMap = new ObjectReaderData(defaultData);
_binder = binder;
}
public void Dispose()
{
_dataMap.Dispose();
}
/// <summary>
/// Read a Boolean value from the stream. This value must have been written using <see cref="ObjectWriter.WriteBoolean(bool)"/>.
/// </summary>
public bool ReadBoolean()
{
return _reader.ReadBoolean();
}
/// <summary>
/// Read a Byte value from the stream. This value must have been written using <see cref="ObjectWriter.WriteByte(byte)"/>.
/// </summary>
public byte ReadByte()
{
return _reader.ReadByte();
}
/// <summary>
/// Read a Char value from the stream. This value must have been written using <see cref="ObjectWriter.WriteChar(char)"/>.
/// </summary>
public char ReadChar()
{
// char was written as UInt16 because BinaryWriter fails on characters that are unicode surrogates.
return (char)_reader.ReadUInt16();
}
/// <summary>
/// Read a Decimal value from the stream. This value must have been written using <see cref="ObjectWriter.WriteDecimal(decimal)"/>.
/// </summary>
public decimal ReadDecimal()
{
return _reader.ReadDecimal();
}
/// <summary>
/// Read a Double value from the stream. This value must have been written using <see cref="ObjectWriter.WriteDouble(double)"/>.
/// </summary>
public double ReadDouble()
{
return _reader.ReadDouble();
}
/// <summary>
/// Read a Single value from the stream. This value must have been written using <see cref="ObjectWriter.WriteSingle(float)"/>.
/// </summary>
public float ReadSingle()
{
return _reader.ReadSingle();
}
/// <summary>
/// Read a Int32 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteInt32(int)"/>.
/// </summary>
public int ReadInt32()
{
return _reader.ReadInt32();
}
/// <summary>
/// Read a Int64 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteInt64(long)"/>.
/// </summary>
public long ReadInt64()
{
return _reader.ReadInt64();
}
/// <summary>
/// Read a SByte value from the stream. This value must have been written using <see cref="ObjectWriter.WriteSByte(sbyte)"/>.
/// </summary>
public sbyte ReadSByte()
{
return _reader.ReadSByte();
}
/// <summary>
/// Read a Int16 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteInt16(short)"/>.
/// </summary>
public short ReadInt16()
{
return _reader.ReadInt16();
}
/// <summary>
/// Read a UInt32 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteUInt32(uint)"/>.
/// </summary>
public uint ReadUInt32()
{
return _reader.ReadUInt32();
}
/// <summary>
/// Read a UInt64 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteUInt64(ulong)"/>.
/// </summary>
public ulong ReadUInt64()
{
return _reader.ReadUInt64();
}
/// <summary>
/// Read a UInt16 value from the stream. This value must have been written using <see cref="ObjectWriter.WriteUInt16(ushort)"/>.
/// </summary>
public ushort ReadUInt16()
{
return _reader.ReadUInt16();
}
/// <summary>
/// Read a DateTime value from the stream. This value must have been written using the <see cref="ObjectWriter.WriteDateTime(DateTime)"/>.
/// </summary>
public DateTime ReadDateTime()
{
return DateTime.FromBinary(this.ReadInt64());
}
/// <summary>
/// Read a compressed 30-bit integer value from the stream. This value must have been written using <see cref="ObjectWriter.WriteCompressedUInt(uint)"/>.
/// </summary>
public uint ReadCompressedUInt()
{
var info = _reader.ReadByte();
byte marker = (byte)(info & ByteMarkerMask);
byte byte0 = (byte)(info & ~ByteMarkerMask);
if (marker == Byte1Marker)
{
return byte0;
}
if (marker == Byte2Marker)
{
var byte1 = _reader.ReadByte();
return (((uint)byte0) << 8) | byte1;
}
if (marker == Byte4Marker)
{
var byte1 = _reader.ReadByte();
var byte2 = _reader.ReadByte();
var byte3 = _reader.ReadByte();
return (((uint)byte0) << 24) | (((uint)byte1) << 16) | (((uint)byte2) << 8) | byte3;
}
throw ExceptionUtilities.UnexpectedValue(marker);
}
/// <summary>
/// Read a value from the stream. The value must have been written using ObjectWriter.WriteValue.
/// </summary>
public object ReadValue()
{
var kind = (DataKind)_reader.ReadByte();
switch (kind)
{
case DataKind.Null:
return null;
case DataKind.Boolean_T:
return Boxes.BoxedTrue;
case DataKind.Boolean_F:
return Boxes.BoxedFalse;
case DataKind.Int8:
return _reader.ReadSByte();
case DataKind.UInt8:
return _reader.ReadByte();
case DataKind.Int16:
return _reader.ReadInt16();
case DataKind.UInt16:
return _reader.ReadUInt16();
case DataKind.Int32:
return _reader.ReadInt32();
case DataKind.Int32_B:
return (int)_reader.ReadByte();
case DataKind.Int32_S:
return (int)_reader.ReadUInt16();
case DataKind.Int32_Z:
return Boxes.BoxedInt32Zero;
case DataKind.UInt32:
return _reader.ReadUInt32();
case DataKind.Int64:
return _reader.ReadInt64();
case DataKind.UInt64:
return _reader.ReadUInt64();
case DataKind.Float4:
return _reader.ReadSingle();
case DataKind.Float8:
return _reader.ReadDouble();
case DataKind.Decimal:
return _reader.ReadDecimal();
case DataKind.DateTime:
return this.ReadDateTime();
case DataKind.Char:
return this.ReadChar();
case DataKind.StringUtf8:
case DataKind.StringUtf16:
case DataKind.StringRef:
case DataKind.StringRef_B:
case DataKind.StringRef_S:
return ReadString(kind);
case DataKind.Object_W:
case DataKind.ObjectRef:
case DataKind.ObjectRef_B:
case DataKind.ObjectRef_S:
return ReadObject(kind);
case DataKind.Type:
case DataKind.TypeRef:
case DataKind.TypeRef_B:
case DataKind.TypeRef_S:
return ReadType(kind);
case DataKind.Enum:
return ReadEnum();
case DataKind.Array:
case DataKind.Array_0:
case DataKind.Array_1:
case DataKind.Array_2:
case DataKind.Array_3:
return ReadArray(kind);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
/// <summary>
/// Read a String value from the stream. This value must have been written using ObjectWriter.WriteString.
/// </summary>
public string ReadString()
{
var kind = (DataKind)_reader.ReadByte();
return kind == DataKind.Null ? null : ReadString(kind);
}
private string ReadString(DataKind kind)
{
switch (kind)
{
case DataKind.StringRef_B:
return (string)_dataMap.GetValue(_reader.ReadByte());
case DataKind.StringRef_S:
return (string)_dataMap.GetValue(_reader.ReadUInt16());
case DataKind.StringRef:
return (string)_dataMap.GetValue(_reader.ReadInt32());
case DataKind.StringUtf16:
case DataKind.StringUtf8:
return ReadStringLiteral(kind);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private unsafe string ReadStringLiteral(DataKind kind)
{
int id = _dataMap.GetNextId();
string value;
if (kind == DataKind.StringUtf8)
{
value = _reader.ReadString();
}
else
{
// This is rare, just allocate UTF16 bytes for simplicity.
int characterCount = (int)ReadCompressedUInt();
byte[] bytes = _reader.ReadBytes(characterCount * sizeof(char));
fixed (byte* bytesPtr = bytes)
{
value = new string((char*)bytesPtr, 0, characterCount);
}
}
_dataMap.AddValue(id, value);
return value;
}
private Array ReadArray(DataKind kind)
{
int length;
switch (kind)
{
case DataKind.Array_0:
length = 0;
break;
case DataKind.Array_1:
length = 1;
break;
case DataKind.Array_2:
length = 2;
break;
case DataKind.Array_3:
length = 3;
break;
default:
length = (int)this.ReadCompressedUInt();
break;
}
Type elementType = this.ReadType();
// optimizations for supported array type by binary reader
if (elementType == typeof(byte))
{
return _reader.ReadBytes(length);
}
if (elementType == typeof(char))
{
return _reader.ReadChars(length);
}
Array array = Array.CreateInstance(elementType, length);
for (int i = 0; i < length; i++)
{
var value = this.ReadValue();
array.SetValue(value, i);
}
return array;
}
private Type ReadType()
{
var kind = (DataKind)_reader.ReadByte();
return ReadType(kind);
}
private Type ReadType(DataKind kind)
{
// optimization for primitive types
if (kind == DataKind.UInt8)
{
return typeof(byte);
}
if (kind == DataKind.Char)
{
return typeof(char);
}
switch (kind)
{
case DataKind.TypeRef_B:
return (Type)_dataMap.GetValue(_reader.ReadByte());
case DataKind.TypeRef_S:
return (Type)_dataMap.GetValue(_reader.ReadUInt16());
case DataKind.TypeRef:
return (Type)_dataMap.GetValue(_reader.ReadInt32());
case DataKind.Type:
int id = _dataMap.GetNextId();
var assemblyName = this.ReadString();
var typeName = this.ReadString();
if (_binder == null)
{
throw NoBinderException(typeName);
}
var type = _binder.GetType(assemblyName, typeName);
_dataMap.AddValue(id, type);
return type;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private object ReadEnum()
{
var enumType = this.ReadType();
var type = Enum.GetUnderlyingType(enumType);
if (type == typeof(int))
{
return Enum.ToObject(enumType, _reader.ReadInt32());
}
if (type == typeof(short))
{
return Enum.ToObject(enumType, _reader.ReadInt16());
}
if (type == typeof(byte))
{
return Enum.ToObject(enumType, _reader.ReadByte());
}
if (type == typeof(long))
{
return Enum.ToObject(enumType, _reader.ReadInt64());
}
if (type == typeof(sbyte))
{
return Enum.ToObject(enumType, _reader.ReadSByte());
}
if (type == typeof(ushort))
{
return Enum.ToObject(enumType, _reader.ReadUInt16());
}
if (type == typeof(uint))
{
return Enum.ToObject(enumType, _reader.ReadUInt32());
}
if (type == typeof(ulong))
{
return Enum.ToObject(enumType, _reader.ReadUInt64());
}
throw ExceptionUtilities.UnexpectedValue(enumType);
}
private object ReadObject(DataKind kind)
{
switch (kind)
{
case DataKind.ObjectRef_B:
return _dataMap.GetValue(_reader.ReadByte());
case DataKind.ObjectRef_S:
return _dataMap.GetValue(_reader.ReadUInt16());
case DataKind.ObjectRef:
return _dataMap.GetValue(_reader.ReadInt32());
case DataKind.Object_W:
return this.ReadReadableObject();
case DataKind.Array:
return this.ReadArray(kind);
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private object ReadReadableObject()
{
int id = _dataMap.GetNextId();
Type type = this.ReadType();
var instance = CreateInstance(type);
_dataMap.AddValue(id, instance);
return instance;
}
private object CreateInstance(Type type)
{
if (_binder == null)
{
return NoBinderException(type.FullName);
}
var reader = _binder.GetReader(type);
if (reader == null)
{
return NoReaderException(type.FullName);
}
return reader(this);
}
private static Exception NoBinderException(string typeName)
{
#if COMPILERCORE
throw new InvalidOperationException(string.Format(CodeAnalysisResources.NoBinderException, typeName));
#else
throw new InvalidOperationException(string.Format(Microsoft.CodeAnalysis.WorkspacesResources.Cannot_deserialize_type_0_no_binder_supplied, typeName));
#endif
}
private static Exception NoReaderException(string typeName)
{
#if COMPILERCORE
throw new InvalidOperationException(string.Format(CodeAnalysisResources.NoReaderException, typeName));
#else
throw new InvalidOperationException(string.Format(Microsoft.CodeAnalysis.WorkspacesResources.Cannot_deserialize_type_0_it_has_no_deserialization_reader, typeName));
#endif
}
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocol.Entities;
using Thrift.Transport;
namespace Thrift.Protocol
{
//TODO: implementation of TProtocol
// ReSharper disable once InconsistentNaming
public class TCompactProtocol : TProtocol
{
private const byte ProtocolId = 0x82;
private const byte Version = 1;
private const byte VersionMask = 0x1f; // 0001 1111
private const byte TypeMask = 0xE0; // 1110 0000
private const byte TypeBits = 0x07; // 0000 0111
private const int TypeShiftAmount = 5;
private static readonly TStruct AnonymousStruct = new TStruct(string.Empty);
private static readonly TField StopField = new TField(string.Empty, TType.Stop, 0);
private const byte NoTypeOverride = 0xFF;
// ReSharper disable once InconsistentNaming
private static readonly byte[] TTypeToCompactType = new byte[16];
private static readonly TType[] CompactTypeToTType = new TType[13];
/// <summary>
/// Used to keep track of the last field for the current and previous structs, so we can do the delta stuff.
/// </summary>
private readonly Stack<short> _lastField = new Stack<short>(15);
/// <summary>
/// If we encounter a boolean field begin, save the TField here so it can have the value incorporated.
/// </summary>
private TField? _booleanField;
/// <summary>
/// If we Read a field header, and it's a boolean field, save the boolean value here so that ReadBool can use it.
/// </summary>
private bool? _boolValue;
private short _lastFieldId;
// minimize memory allocations by means of an preallocated bytes buffer
// The value of 128 is arbitrarily chosen, the required minimum size must be sizeof(long)
private byte[] PreAllocatedBuffer = new byte[128];
private struct VarInt
{
public byte[] bytes;
public int count;
}
// minimize memory allocations by means of an preallocated VarInt buffer
private VarInt PreAllocatedVarInt = new VarInt()
{
bytes = new byte[10], // see Int64ToVarInt()
count = 0
};
public TCompactProtocol(TTransport trans)
: base(trans)
{
TTypeToCompactType[(int) TType.Stop] = Types.Stop;
TTypeToCompactType[(int) TType.Bool] = Types.BooleanTrue;
TTypeToCompactType[(int) TType.Byte] = Types.Byte;
TTypeToCompactType[(int) TType.I16] = Types.I16;
TTypeToCompactType[(int) TType.I32] = Types.I32;
TTypeToCompactType[(int) TType.I64] = Types.I64;
TTypeToCompactType[(int) TType.Double] = Types.Double;
TTypeToCompactType[(int) TType.String] = Types.Binary;
TTypeToCompactType[(int) TType.List] = Types.List;
TTypeToCompactType[(int) TType.Set] = Types.Set;
TTypeToCompactType[(int) TType.Map] = Types.Map;
TTypeToCompactType[(int) TType.Struct] = Types.Struct;
CompactTypeToTType[Types.Stop] = TType.Stop;
CompactTypeToTType[Types.BooleanTrue] = TType.Bool;
CompactTypeToTType[Types.BooleanFalse] = TType.Bool;
CompactTypeToTType[Types.Byte] = TType.Byte;
CompactTypeToTType[Types.I16] = TType.I16;
CompactTypeToTType[Types.I32] = TType.I32;
CompactTypeToTType[Types.I64] = TType.I64;
CompactTypeToTType[Types.Double] = TType.Double;
CompactTypeToTType[Types.Binary] = TType.String;
CompactTypeToTType[Types.List] = TType.List;
CompactTypeToTType[Types.Set] = TType.Set;
CompactTypeToTType[Types.Map] = TType.Map;
CompactTypeToTType[Types.Struct] = TType.Struct;
}
public void Reset()
{
_lastField.Clear();
_lastFieldId = 0;
}
public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken)
{
PreAllocatedBuffer[0] = ProtocolId;
PreAllocatedBuffer[1] = (byte)((Version & VersionMask) | (((uint)message.Type << TypeShiftAmount) & TypeMask));
await Trans.WriteAsync(PreAllocatedBuffer, 0, 2, cancellationToken);
Int32ToVarInt((uint) message.SeqID, ref PreAllocatedVarInt);
await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken);
await WriteStringAsync(message.Name, cancellationToken);
}
public override async Task WriteMessageEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
/// <summary>
/// Write a struct begin. This doesn't actually put anything on the wire. We
/// use it as an opportunity to put special placeholder markers on the field
/// stack so we can get the field id deltas correct.
/// </summary>
public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
_lastField.Push(_lastFieldId);
_lastFieldId = 0;
}
public override async Task WriteStructEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
_lastFieldId = _lastField.Pop();
}
private async Task WriteFieldBeginInternalAsync(TField field, byte fieldType, CancellationToken cancellationToken)
{
// if there's a exType override passed in, use that. Otherwise ask GetCompactType().
if (fieldType == NoTypeOverride)
fieldType = GetCompactType(field.Type);
// check if we can use delta encoding for the field id
if (field.ID > _lastFieldId)
{
var delta = field.ID - _lastFieldId;
if (delta <= 15)
{
// Write them together
PreAllocatedBuffer[0] = (byte)((delta << 4) | fieldType);
await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
_lastFieldId = field.ID;
return;
}
}
// Write them separate
PreAllocatedBuffer[0] = fieldType;
await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
await WriteI16Async(field.ID, cancellationToken);
_lastFieldId = field.ID;
}
public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken)
{
if (field.Type == TType.Bool)
{
_booleanField = field;
}
else
{
await WriteFieldBeginInternalAsync(field, NoTypeOverride, cancellationToken);
}
}
public override async Task WriteFieldEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteFieldStopAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
PreAllocatedBuffer[0] = Types.Stop;
await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
}
protected async Task WriteCollectionBeginAsync(TType elemType, int size, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
/*
Abstract method for writing the start of lists and sets. List and sets on
the wire differ only by the exType indicator.
*/
if (size <= 14)
{
PreAllocatedBuffer[0] = (byte)((size << 4) | GetCompactType(elemType));
await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
}
else
{
PreAllocatedBuffer[0] = (byte)(0xf0 | GetCompactType(elemType));
await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
Int32ToVarInt((uint) size, ref PreAllocatedVarInt);
await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken);
}
}
public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken)
{
await WriteCollectionBeginAsync(list.ElementType, list.Count, cancellationToken);
}
public override async Task WriteListEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
await WriteCollectionBeginAsync(set.ElementType, set.Count, cancellationToken);
}
public override async Task WriteSetEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
/*
Write a boolean value. Potentially, this could be a boolean field, in
which case the field header info isn't written yet. If so, decide what the
right exType header is for the value and then Write the field header.
Otherwise, Write a single byte.
*/
if (_booleanField != null)
{
// we haven't written the field header yet
var type = b ? Types.BooleanTrue : Types.BooleanFalse;
await WriteFieldBeginInternalAsync(_booleanField.Value, type, cancellationToken);
_booleanField = null;
}
else
{
// we're not part of a field, so just write the value.
PreAllocatedBuffer[0] = b ? Types.BooleanTrue : Types.BooleanFalse;
await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
}
}
public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
PreAllocatedBuffer[0] = (byte)b;
await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
}
public override async Task WriteI16Async(short i16, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
Int32ToVarInt(IntToZigzag(i16), ref PreAllocatedVarInt);
await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken);
}
private static void Int32ToVarInt(uint n, ref VarInt varint)
{
// Write an i32 as a varint. Results in 1 - 5 bytes on the wire.
varint.count = 0;
Debug.Assert(varint.bytes.Length >= 5);
while (true)
{
if ((n & ~0x7F) == 0)
{
varint.bytes[varint.count++] = (byte)n;
break;
}
varint.bytes[varint.count++] = (byte)((n & 0x7F) | 0x80);
n >>= 7;
}
}
public override async Task WriteI32Async(int i32, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
Int32ToVarInt(IntToZigzag(i32), ref PreAllocatedVarInt);
await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken);
}
static private void Int64ToVarInt(ulong n, ref VarInt varint)
{
// Write an i64 as a varint. Results in 1-10 bytes on the wire.
varint.count = 0;
Debug.Assert(varint.bytes.Length >= 10);
while (true)
{
if ((n & ~(ulong)0x7FL) == 0)
{
varint.bytes[varint.count++] = (byte)n;
break;
}
varint.bytes[varint.count++] = (byte)((n & 0x7F) | 0x80);
n >>= 7;
}
}
public override async Task WriteI64Async(long i64, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
Int64ToVarInt(LongToZigzag(i64), ref PreAllocatedVarInt);
await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken);
}
public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
BinaryPrimitives.WriteInt64LittleEndian(PreAllocatedBuffer, BitConverter.DoubleToInt64Bits(d));
await Trans.WriteAsync(PreAllocatedBuffer, 0, 8, cancellationToken);
}
public override async Task WriteStringAsync(string str, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
var bytes = Encoding.UTF8.GetBytes(str);
Int32ToVarInt((uint) bytes.Length, ref PreAllocatedVarInt);
await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken);
await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
}
public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
Int32ToVarInt((uint) bytes.Length, ref PreAllocatedVarInt);
await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken);
await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken);
}
public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
if (map.Count == 0)
{
PreAllocatedBuffer[0] = 0;
await Trans.WriteAsync( PreAllocatedBuffer, 0, 1, cancellationToken);
}
else
{
Int32ToVarInt((uint) map.Count, ref PreAllocatedVarInt);
await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken);
PreAllocatedBuffer[0] = (byte)((GetCompactType(map.KeyType) << 4) | GetCompactType(map.ValueType));
await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
}
}
public override async Task WriteMapEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async ValueTask<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<TMessage>(cancellationToken);
}
var protocolId = (byte) await ReadByteAsync(cancellationToken);
if (protocolId != ProtocolId)
{
throw new TProtocolException($"Expected protocol id {ProtocolId:X} but got {protocolId:X}");
}
var versionAndType = (byte) await ReadByteAsync(cancellationToken);
var version = (byte) (versionAndType & VersionMask);
if (version != Version)
{
throw new TProtocolException($"Expected version {Version} but got {version}");
}
var type = (byte) ((versionAndType >> TypeShiftAmount) & TypeBits);
var seqid = (int) await ReadVarInt32Async(cancellationToken);
var messageName = await ReadStringAsync(cancellationToken);
return new TMessage(messageName, (TMessageType) type, seqid);
}
public override async Task ReadMessageEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async ValueTask<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<TStruct>(cancellationToken);
}
// some magic is here )
_lastField.Push(_lastFieldId);
_lastFieldId = 0;
return AnonymousStruct;
}
public override async Task ReadStructEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
/*
Doesn't actually consume any wire data, just removes the last field for
this struct from the field stack.
*/
// consume the last field we Read off the wire.
_lastFieldId = _lastField.Pop();
}
public override async ValueTask<TField> ReadFieldBeginAsync(CancellationToken cancellationToken)
{
// Read a field header off the wire.
var type = (byte) await ReadByteAsync(cancellationToken);
// if it's a stop, then we can return immediately, as the struct is over.
if (type == Types.Stop)
{
return StopField;
}
// mask off the 4 MSB of the exType header. it could contain a field id delta.
var modifier = (short) ((type & 0xf0) >> 4);
var compactType = (byte)(type & 0x0f);
short fieldId;
if (modifier == 0)
{
fieldId = await ReadI16Async(cancellationToken);
}
else
{
fieldId = (short) (_lastFieldId + modifier);
}
var ttype = GetTType(compactType);
var field = new TField(string.Empty, ttype, fieldId);
// if this happens to be a boolean field, the value is encoded in the exType
if( ttype == TType.Bool)
{
_boolValue = (compactType == Types.BooleanTrue);
}
// push the new field onto the field stack so we can keep the deltas going.
_lastFieldId = field.ID;
return field;
}
public override async Task ReadFieldEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async ValueTask<TMap> ReadMapBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled<TMap>(cancellationToken);
}
/*
Read a map header off the wire. If the size is zero, skip Reading the key
and value exType. This means that 0-length maps will yield TMaps without the
"correct" types.
*/
var size = (int) await ReadVarInt32Async(cancellationToken);
var keyAndValueType = size == 0 ? (byte) 0 : (byte) await ReadByteAsync(cancellationToken);
var map = new TMap(GetTType((byte) (keyAndValueType >> 4)), GetTType((byte) (keyAndValueType & 0xf)), size);
CheckReadBytesAvailable(map);
return map;
}
public override async Task ReadMapEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async ValueTask<TSet> ReadSetBeginAsync(CancellationToken cancellationToken)
{
/*
Read a set header off the wire. If the set size is 0-14, the size will
be packed into the element exType header. If it's a longer set, the 4 MSB
of the element exType header will be 0xF, and a varint will follow with the
true size.
*/
return new TSet(await ReadListBeginAsync(cancellationToken));
}
public override ValueTask<bool> ReadBoolAsync(CancellationToken cancellationToken)
{
/*
Read a boolean off the wire. If this is a boolean field, the value should
already have been Read during ReadFieldBegin, so we'll just consume the
pre-stored value. Otherwise, Read a byte.
*/
if (_boolValue != null)
{
var result = _boolValue.Value;
_boolValue = null;
return new ValueTask<bool>(result);
}
return InternalCall();
async ValueTask<bool> InternalCall()
{
var data = await ReadByteAsync(cancellationToken);
return (data == Types.BooleanTrue);
}
}
public override async ValueTask<sbyte> ReadByteAsync(CancellationToken cancellationToken)
{
// Read a single byte off the wire. Nothing interesting here.
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 1, cancellationToken);
return (sbyte)PreAllocatedBuffer[0];
}
public override async ValueTask<short> ReadI16Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<short>(cancellationToken);
}
return (short) ZigzagToInt(await ReadVarInt32Async(cancellationToken));
}
public override async ValueTask<int> ReadI32Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<int>(cancellationToken);
}
return ZigzagToInt(await ReadVarInt32Async(cancellationToken));
}
public override async ValueTask<long> ReadI64Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<long>(cancellationToken);
}
return ZigzagToLong(await ReadVarInt64Async(cancellationToken));
}
public override async ValueTask<double> ReadDoubleAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<double>(cancellationToken);
}
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 8, cancellationToken);
return BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(PreAllocatedBuffer));
}
public override async ValueTask<string> ReadStringAsync(CancellationToken cancellationToken)
{
// read length
var length = (int) await ReadVarInt32Async(cancellationToken);
if (length == 0)
{
return string.Empty;
}
// read and decode data
if (length < PreAllocatedBuffer.Length)
{
await Trans.ReadAllAsync(PreAllocatedBuffer, 0, length, cancellationToken);
return Encoding.UTF8.GetString(PreAllocatedBuffer, 0, length);
}
Transport.CheckReadBytesAvailable(length);
var buf = new byte[length];
await Trans.ReadAllAsync(buf, 0, length, cancellationToken);
return Encoding.UTF8.GetString(buf, 0, length);
}
public override async ValueTask<byte[]> ReadBinaryAsync(CancellationToken cancellationToken)
{
// read length
var length = (int) await ReadVarInt32Async(cancellationToken);
if (length == 0)
{
return new byte[0];
}
// read data
Transport.CheckReadBytesAvailable(length);
var buf = new byte[length];
await Trans.ReadAllAsync(buf, 0, length, cancellationToken);
return buf;
}
public override async ValueTask<TList> ReadListBeginAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled<TList>(cancellationToken);
}
/*
Read a list header off the wire. If the list size is 0-14, the size will
be packed into the element exType header. If it's a longer list, the 4 MSB
of the element exType header will be 0xF, and a varint will follow with the
true size.
*/
var sizeAndType = (byte) await ReadByteAsync(cancellationToken);
var size = (sizeAndType >> 4) & 0x0f;
if (size == 15)
{
size = (int) await ReadVarInt32Async(cancellationToken);
}
var type = GetTType(sizeAndType);
var list = new TList(type, size);
CheckReadBytesAvailable(list);
return list;
}
public override async Task ReadListEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override async Task ReadSetEndAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
private static byte GetCompactType(TType ttype)
{
// Given a TType value, find the appropriate TCompactProtocol.Types constant.
return TTypeToCompactType[(int) ttype];
}
private async ValueTask<uint> ReadVarInt32Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<uint>(cancellationToken);
}
/*
Read an i32 from the wire as a varint. The MSB of each byte is set
if there is another byte to follow. This can Read up to 5 bytes.
*/
uint result = 0;
var shift = 0;
while (true)
{
var b = (byte) await ReadByteAsync(cancellationToken);
result |= (uint) (b & 0x7f) << shift;
if ((b & 0x80) != 0x80)
{
break;
}
shift += 7;
}
return result;
}
private async ValueTask<ulong> ReadVarInt64Async(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return await Task.FromCanceled<uint>(cancellationToken);
}
/*
Read an i64 from the wire as a proper varint. The MSB of each byte is set
if there is another byte to follow. This can Read up to 10 bytes.
*/
var shift = 0;
ulong result = 0;
while (true)
{
var b = (byte) await ReadByteAsync(cancellationToken);
result |= (ulong) (b & 0x7f) << shift;
if ((b & 0x80) != 0x80)
{
break;
}
shift += 7;
}
return result;
}
private static int ZigzagToInt(uint n)
{
return (int) (n >> 1) ^ -(int) (n & 1);
}
private static long ZigzagToLong(ulong n)
{
return (long) (n >> 1) ^ -(long) (n & 1);
}
private static TType GetTType(byte type)
{
// Given a TCompactProtocol.Types constant, convert it to its corresponding TType value.
return CompactTypeToTType[type & 0x0f];
}
private static ulong LongToZigzag(long n)
{
// Convert l into a zigzag long. This allows negative numbers to be represented compactly as a varint
return (ulong) (n << 1) ^ (ulong) (n >> 63);
}
private static uint IntToZigzag(int n)
{
// Convert n into a zigzag int. This allows negative numbers to be represented compactly as a varint
return (uint) (n << 1) ^ (uint) (n >> 31);
}
// Return the minimum number of bytes a type will consume on the wire
public override int GetMinSerializedSize(TType type)
{
switch (type)
{
case TType.Stop: return 0;
case TType.Void: return 0;
case TType.Bool: return sizeof(byte);
case TType.Double: return 8; // uses fixedLongToBytes() which always writes 8 bytes
case TType.Byte: return sizeof(byte);
case TType.I16: return sizeof(byte); // zigzag
case TType.I32: return sizeof(byte); // zigzag
case TType.I64: return sizeof(byte); // zigzag
case TType.String: return sizeof(byte); // string length
case TType.Struct: return 0; // empty struct
case TType.Map: return sizeof(byte); // element count
case TType.Set: return sizeof(byte); // element count
case TType.List: return sizeof(byte); // element count
default: throw new TTransportException(TTransportException.ExceptionType.Unknown, "unrecognized type code");
}
}
public class Factory : TProtocolFactory
{
public override TProtocol GetProtocol(TTransport trans)
{
return new TCompactProtocol(trans);
}
}
/// <summary>
/// All of the on-wire exType codes.
/// </summary>
private static class Types
{
public const byte Stop = 0x00;
public const byte BooleanTrue = 0x01;
public const byte BooleanFalse = 0x02;
public const byte Byte = 0x03;
public const byte I16 = 0x04;
public const byte I32 = 0x05;
public const byte I64 = 0x06;
public const byte Double = 0x07;
public const byte Binary = 0x08;
public const byte List = 0x09;
public const byte Set = 0x0A;
public const byte Map = 0x0B;
public const byte Struct = 0x0C;
}
}
}
| |
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Collections.Generic;
using NationalInstruments.UI.WindowsForms;
using NationalInstruments.UI;
namespace SympatheticHardwareControl
{
/// <summary>
/// Front panel for the sympathetic hardware controller. Everything is just stuffed in there. No particularly
/// clever structure. This class just hands everything straight off to the controller. It has a few
/// thread safe wrappers so that remote calls can safely manipulate the front panel.
/// </summary>
public class ControlWindow : System.Windows.Forms.Form
{
#region Setup
public Controller controller;
private Dictionary<string, TextBox> AOTextBoxes = new Dictionary<string, TextBox>();
private Dictionary<string, CheckBox> DOCheckBoxes = new Dictionary<string, CheckBox>();
public ControlWindow()
{
InitializeComponent();
AOTextBoxes["aom0amplitude"] = aom0rfAmplitudeTextBox;
AOTextBoxes["aom1amplitude"] = aom1rfAmplitudeTextBox;
AOTextBoxes["aom2amplitude"] = aom2rfAmplitudeTextBox;
AOTextBoxes["aom3amplitude"] = aom3rfAmplitudeTextBox;
AOTextBoxes["aom0frequency"] = aom0rfFrequencyTextBox;
AOTextBoxes["aom1frequency"] = aom1rfFrequencyTextBox;
AOTextBoxes["aom2frequency"] = aom2rfFrequencyTextBox;
AOTextBoxes["aom3frequency"] = aom3rfFrequencyTextBox;
AOTextBoxes["coil0current"] = coil0CurrentTextBox;
AOTextBoxes["coil1current"] = coil1CurrentTextBox;
DOCheckBoxes["aom0enable"] = aom0CheckBox;
DOCheckBoxes["aom1enable"] = aom1CheckBox;
DOCheckBoxes["aom2enable"] = aom2CheckBox;
DOCheckBoxes["aom3enable"] = aom3CheckBox;
DOCheckBoxes["shutterenable"] = shutterCheckBox;
}
private void WindowClosing(object sender, FormClosingEventArgs e)
{
controller.ControllerStopping();
}
private void WindowLoaded(object sender, EventArgs e)
{
controller.ControllerLoaded();
}
#endregion
#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.shcTabs = new System.Windows.Forms.TabControl();
this.tabCamera = new System.Windows.Forms.TabPage();
this.stopStreamButton = new System.Windows.Forms.Button();
this.streamButton = new System.Windows.Forms.Button();
this.snapshotButton = new System.Windows.Forms.Button();
this.tabLasers = new System.Windows.Forms.TabPage();
this.ShutterControlBox = new System.Windows.Forms.GroupBox();
this.shutterCheckBox = new System.Windows.Forms.CheckBox();
this.aom3ControlBox = new System.Windows.Forms.GroupBox();
this.aom3Label3 = new System.Windows.Forms.Label();
this.aom3Label1 = new System.Windows.Forms.Label();
this.aom3CheckBox = new System.Windows.Forms.CheckBox();
this.aom3rfFrequencyTextBox = new System.Windows.Forms.TextBox();
this.aom3rfAmplitudeTextBox = new System.Windows.Forms.TextBox();
this.aom3Label2 = new System.Windows.Forms.Label();
this.aom3Label0 = new System.Windows.Forms.Label();
this.aom2ControlBox = new System.Windows.Forms.GroupBox();
this.aom2Label3 = new System.Windows.Forms.Label();
this.aom2Label1 = new System.Windows.Forms.Label();
this.aom2CheckBox = new System.Windows.Forms.CheckBox();
this.aom2rfFrequencyTextBox = new System.Windows.Forms.TextBox();
this.aom2rfAmplitudeTextBox = new System.Windows.Forms.TextBox();
this.aom2Label2 = new System.Windows.Forms.Label();
this.aom2Label0 = new System.Windows.Forms.Label();
this.aom1ControlBox = new System.Windows.Forms.GroupBox();
this.aom1Label3 = new System.Windows.Forms.Label();
this.aom1Label1 = new System.Windows.Forms.Label();
this.aom1CheckBox = new System.Windows.Forms.CheckBox();
this.aom1rfFrequencyTextBox = new System.Windows.Forms.TextBox();
this.aom1rfAmplitudeTextBox = new System.Windows.Forms.TextBox();
this.aom1Label2 = new System.Windows.Forms.Label();
this.aom1Label0 = new System.Windows.Forms.Label();
this.aom0ControlBox = new System.Windows.Forms.GroupBox();
this.aom0Label3 = new System.Windows.Forms.Label();
this.aom0Label1 = new System.Windows.Forms.Label();
this.aom0CheckBox = new System.Windows.Forms.CheckBox();
this.aom0rfFrequencyTextBox = new System.Windows.Forms.TextBox();
this.aom0rfAmplitudeTextBox = new System.Windows.Forms.TextBox();
this.aom0Label2 = new System.Windows.Forms.Label();
this.aom0Label0 = new System.Windows.Forms.Label();
this.tabCoils = new System.Windows.Forms.TabPage();
this.coil1GroupBox = new System.Windows.Forms.GroupBox();
this.coil1Label1 = new System.Windows.Forms.Label();
this.coil1CurrentTextBox = new System.Windows.Forms.TextBox();
this.coil1Label0 = new System.Windows.Forms.Label();
this.coil0GroupBox = new System.Windows.Forms.GroupBox();
this.coil0Label1 = new System.Windows.Forms.Label();
this.coil0CurrentTextBox = new System.Windows.Forms.TextBox();
this.coil0Label0 = new System.Windows.Forms.Label();
this.tabTranslationStage = new System.Windows.Forms.TabPage();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.AutoTriggerCheckBox = new System.Windows.Forms.CheckBox();
this.RS232GroupBox = new System.Windows.Forms.GroupBox();
this.TSConnectButton = new System.Windows.Forms.Button();
this.disposeButton = new System.Windows.Forms.Button();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.TSListAllButton = new System.Windows.Forms.Button();
this.checkStatusButton = new System.Windows.Forms.Button();
this.read = new System.Windows.Forms.Button();
this.TSClearButton = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.TSHomeButton = new System.Windows.Forms.Button();
this.TSGoButton = new System.Windows.Forms.Button();
this.TSReturnButton = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.TSRestartButton = new System.Windows.Forms.Button();
this.TSOnButton = new System.Windows.Forms.Button();
this.TSOffButton = new System.Windows.Forms.Button();
this.initParamsBox = new System.Windows.Forms.GroupBox();
this.TSInitButton = new System.Windows.Forms.Button();
this.label9 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.TSVelTextBox = new System.Windows.Forms.TextBox();
this.TSStepsTextBox = new System.Windows.Forms.TextBox();
this.TSDecTextBox = new System.Windows.Forms.TextBox();
this.TSAccTextBox = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.loadParametersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveParametersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.saveImageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.windowsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.hardwareMonitorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openImageViewerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.remoteControlLED = new NationalInstruments.UI.WindowsForms.Led();
this.label1 = new System.Windows.Forms.Label();
this.updateHardwareButton = new System.Windows.Forms.Button();
this.consoleRichTextBox = new System.Windows.Forms.RichTextBox();
this.shcTabs.SuspendLayout();
this.tabCamera.SuspendLayout();
this.tabLasers.SuspendLayout();
this.ShutterControlBox.SuspendLayout();
this.aom3ControlBox.SuspendLayout();
this.aom2ControlBox.SuspendLayout();
this.aom1ControlBox.SuspendLayout();
this.aom0ControlBox.SuspendLayout();
this.tabCoils.SuspendLayout();
this.coil1GroupBox.SuspendLayout();
this.coil0GroupBox.SuspendLayout();
this.tabTranslationStage.SuspendLayout();
this.groupBox4.SuspendLayout();
this.RS232GroupBox.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox1.SuspendLayout();
this.initParamsBox.SuspendLayout();
this.menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.remoteControlLED)).BeginInit();
this.SuspendLayout();
//
// shcTabs
//
this.shcTabs.AllowDrop = true;
this.shcTabs.Controls.Add(this.tabCamera);
this.shcTabs.Controls.Add(this.tabLasers);
this.shcTabs.Controls.Add(this.tabCoils);
this.shcTabs.Controls.Add(this.tabTranslationStage);
this.shcTabs.Location = new System.Drawing.Point(3, 27);
this.shcTabs.Name = "shcTabs";
this.shcTabs.SelectedIndex = 0;
this.shcTabs.Size = new System.Drawing.Size(666, 235);
this.shcTabs.TabIndex = 0;
//
// tabCamera
//
this.tabCamera.Controls.Add(this.stopStreamButton);
this.tabCamera.Controls.Add(this.streamButton);
this.tabCamera.Controls.Add(this.snapshotButton);
this.tabCamera.Location = new System.Drawing.Point(4, 22);
this.tabCamera.Name = "tabCamera";
this.tabCamera.Padding = new System.Windows.Forms.Padding(3);
this.tabCamera.Size = new System.Drawing.Size(658, 209);
this.tabCamera.TabIndex = 0;
this.tabCamera.Text = "Camera Control";
this.tabCamera.UseVisualStyleBackColor = true;
//
// stopStreamButton
//
this.stopStreamButton.Location = new System.Drawing.Point(168, 6);
this.stopStreamButton.Name = "stopStreamButton";
this.stopStreamButton.Size = new System.Drawing.Size(75, 23);
this.stopStreamButton.TabIndex = 18;
this.stopStreamButton.Text = "Stop";
this.stopStreamButton.UseVisualStyleBackColor = true;
this.stopStreamButton.Click += new System.EventHandler(this.stopStreamButton_Click);
//
// streamButton
//
this.streamButton.Location = new System.Drawing.Point(87, 6);
this.streamButton.Name = "streamButton";
this.streamButton.Size = new System.Drawing.Size(75, 23);
this.streamButton.TabIndex = 17;
this.streamButton.Text = "Stream";
this.streamButton.UseVisualStyleBackColor = true;
this.streamButton.Click += new System.EventHandler(this.streamButton_Click);
//
// snapshotButton
//
this.snapshotButton.Location = new System.Drawing.Point(6, 6);
this.snapshotButton.Name = "snapshotButton";
this.snapshotButton.Size = new System.Drawing.Size(75, 23);
this.snapshotButton.TabIndex = 15;
this.snapshotButton.Text = "Snapshot";
this.snapshotButton.UseVisualStyleBackColor = true;
this.snapshotButton.Click += new System.EventHandler(this.snapshotButton_Click);
//
// tabLasers
//
this.tabLasers.AutoScroll = true;
this.tabLasers.Controls.Add(this.ShutterControlBox);
this.tabLasers.Controls.Add(this.aom3ControlBox);
this.tabLasers.Controls.Add(this.aom2ControlBox);
this.tabLasers.Controls.Add(this.aom1ControlBox);
this.tabLasers.Controls.Add(this.aom0ControlBox);
this.tabLasers.Location = new System.Drawing.Point(4, 22);
this.tabLasers.Name = "tabLasers";
this.tabLasers.Padding = new System.Windows.Forms.Padding(3);
this.tabLasers.Size = new System.Drawing.Size(658, 209);
this.tabLasers.TabIndex = 1;
this.tabLasers.Text = "Laser Control";
this.tabLasers.UseVisualStyleBackColor = true;
//
// ShutterControlBox
//
this.ShutterControlBox.Controls.Add(this.shutterCheckBox);
this.ShutterControlBox.Location = new System.Drawing.Point(549, 3);
this.ShutterControlBox.Name = "ShutterControlBox";
this.ShutterControlBox.Size = new System.Drawing.Size(104, 45);
this.ShutterControlBox.TabIndex = 22;
this.ShutterControlBox.TabStop = false;
this.ShutterControlBox.Text = "Zeeman repump";
//
// shutterCheckBox
//
this.shutterCheckBox.AutoSize = true;
this.shutterCheckBox.Location = new System.Drawing.Point(46, 21);
this.shutterCheckBox.Name = "shutterCheckBox";
this.shutterCheckBox.Size = new System.Drawing.Size(15, 14);
this.shutterCheckBox.TabIndex = 21;
this.shutterCheckBox.UseVisualStyleBackColor = true;
//
// aom3ControlBox
//
this.aom3ControlBox.Controls.Add(this.aom3Label3);
this.aom3ControlBox.Controls.Add(this.aom3Label1);
this.aom3ControlBox.Controls.Add(this.aom3CheckBox);
this.aom3ControlBox.Controls.Add(this.aom3rfFrequencyTextBox);
this.aom3ControlBox.Controls.Add(this.aom3rfAmplitudeTextBox);
this.aom3ControlBox.Controls.Add(this.aom3Label2);
this.aom3ControlBox.Controls.Add(this.aom3Label0);
this.aom3ControlBox.Location = new System.Drawing.Point(3, 156);
this.aom3ControlBox.Name = "aom3ControlBox";
this.aom3ControlBox.Size = new System.Drawing.Size(541, 45);
this.aom3ControlBox.TabIndex = 19;
this.aom3ControlBox.TabStop = false;
this.aom3ControlBox.Text = "AOM 3 (Absorption)";
//
// aom3Label3
//
this.aom3Label3.AutoSize = true;
this.aom3Label3.Location = new System.Drawing.Point(522, 21);
this.aom3Label3.Name = "aom3Label3";
this.aom3Label3.Size = new System.Drawing.Size(14, 13);
this.aom3Label3.TabIndex = 17;
this.aom3Label3.Text = "V";
//
// aom3Label1
//
this.aom3Label1.AutoSize = true;
this.aom3Label1.Location = new System.Drawing.Point(260, 21);
this.aom3Label1.Name = "aom3Label1";
this.aom3Label1.Size = new System.Drawing.Size(29, 13);
this.aom3Label1.TabIndex = 16;
this.aom3Label1.Text = "MHz";
//
// aom3CheckBox
//
this.aom3CheckBox.AutoSize = true;
this.aom3CheckBox.Location = new System.Drawing.Point(38, 21);
this.aom3CheckBox.Name = "aom3CheckBox";
this.aom3CheckBox.Size = new System.Drawing.Size(15, 14);
this.aom3CheckBox.TabIndex = 10;
this.aom3CheckBox.UseVisualStyleBackColor = true;
//
// aom3rfFrequencyTextBox
//
this.aom3rfFrequencyTextBox.Location = new System.Drawing.Point(155, 17);
this.aom3rfFrequencyTextBox.Name = "aom3rfFrequencyTextBox";
this.aom3rfFrequencyTextBox.Size = new System.Drawing.Size(103, 20);
this.aom3rfFrequencyTextBox.TabIndex = 0;
this.aom3rfFrequencyTextBox.Text = "200";
//
// aom3rfAmplitudeTextBox
//
this.aom3rfAmplitudeTextBox.Location = new System.Drawing.Point(421, 17);
this.aom3rfAmplitudeTextBox.Name = "aom3rfAmplitudeTextBox";
this.aom3rfAmplitudeTextBox.Size = new System.Drawing.Size(100, 20);
this.aom3rfAmplitudeTextBox.TabIndex = 8;
this.aom3rfAmplitudeTextBox.Text = "0";
//
// aom3Label2
//
this.aom3Label2.AutoSize = true;
this.aom3Label2.Location = new System.Drawing.Point(348, 20);
this.aom3Label2.Name = "aom3Label2";
this.aom3Label2.Size = new System.Drawing.Size(70, 13);
this.aom3Label2.TabIndex = 7;
this.aom3Label2.Text = "RF Amplitude";
//
// aom3Label0
//
this.aom3Label0.AutoSize = true;
this.aom3Label0.Location = new System.Drawing.Point(78, 20);
this.aom3Label0.Name = "aom3Label0";
this.aom3Label0.Size = new System.Drawing.Size(74, 13);
this.aom3Label0.TabIndex = 6;
this.aom3Label0.Text = "RF Frequency";
//
// aom2ControlBox
//
this.aom2ControlBox.Controls.Add(this.aom2Label3);
this.aom2ControlBox.Controls.Add(this.aom2Label1);
this.aom2ControlBox.Controls.Add(this.aom2CheckBox);
this.aom2ControlBox.Controls.Add(this.aom2rfFrequencyTextBox);
this.aom2ControlBox.Controls.Add(this.aom2rfAmplitudeTextBox);
this.aom2ControlBox.Controls.Add(this.aom2Label2);
this.aom2ControlBox.Controls.Add(this.aom2Label0);
this.aom2ControlBox.Location = new System.Drawing.Point(3, 105);
this.aom2ControlBox.Name = "aom2ControlBox";
this.aom2ControlBox.Size = new System.Drawing.Size(541, 45);
this.aom2ControlBox.TabIndex = 20;
this.aom2ControlBox.TabStop = false;
this.aom2ControlBox.Text = "AOM 2 (Zeeman)";
//
// aom2Label3
//
this.aom2Label3.AutoSize = true;
this.aom2Label3.Location = new System.Drawing.Point(522, 21);
this.aom2Label3.Name = "aom2Label3";
this.aom2Label3.Size = new System.Drawing.Size(14, 13);
this.aom2Label3.TabIndex = 17;
this.aom2Label3.Text = "V";
//
// aom2Label1
//
this.aom2Label1.AutoSize = true;
this.aom2Label1.Location = new System.Drawing.Point(260, 21);
this.aom2Label1.Name = "aom2Label1";
this.aom2Label1.Size = new System.Drawing.Size(29, 13);
this.aom2Label1.TabIndex = 16;
this.aom2Label1.Text = "MHz";
//
// aom2CheckBox
//
this.aom2CheckBox.AutoSize = true;
this.aom2CheckBox.Location = new System.Drawing.Point(38, 21);
this.aom2CheckBox.Name = "aom2CheckBox";
this.aom2CheckBox.Size = new System.Drawing.Size(15, 14);
this.aom2CheckBox.TabIndex = 10;
this.aom2CheckBox.UseVisualStyleBackColor = true;
//
// aom2rfFrequencyTextBox
//
this.aom2rfFrequencyTextBox.Location = new System.Drawing.Point(155, 17);
this.aom2rfFrequencyTextBox.Name = "aom2rfFrequencyTextBox";
this.aom2rfFrequencyTextBox.Size = new System.Drawing.Size(103, 20);
this.aom2rfFrequencyTextBox.TabIndex = 0;
this.aom2rfFrequencyTextBox.Text = "0";
//
// aom2rfAmplitudeTextBox
//
this.aom2rfAmplitudeTextBox.Location = new System.Drawing.Point(421, 17);
this.aom2rfAmplitudeTextBox.Name = "aom2rfAmplitudeTextBox";
this.aom2rfAmplitudeTextBox.Size = new System.Drawing.Size(100, 20);
this.aom2rfAmplitudeTextBox.TabIndex = 8;
this.aom2rfAmplitudeTextBox.Text = "0";
//
// aom2Label2
//
this.aom2Label2.AutoSize = true;
this.aom2Label2.Location = new System.Drawing.Point(348, 20);
this.aom2Label2.Name = "aom2Label2";
this.aom2Label2.Size = new System.Drawing.Size(70, 13);
this.aom2Label2.TabIndex = 7;
this.aom2Label2.Text = "RF Amplitude";
//
// aom2Label0
//
this.aom2Label0.AutoSize = true;
this.aom2Label0.Location = new System.Drawing.Point(78, 20);
this.aom2Label0.Name = "aom2Label0";
this.aom2Label0.Size = new System.Drawing.Size(74, 13);
this.aom2Label0.TabIndex = 6;
this.aom2Label0.Text = "RF Frequency";
//
// aom1ControlBox
//
this.aom1ControlBox.Controls.Add(this.aom1Label3);
this.aom1ControlBox.Controls.Add(this.aom1Label1);
this.aom1ControlBox.Controls.Add(this.aom1CheckBox);
this.aom1ControlBox.Controls.Add(this.aom1rfFrequencyTextBox);
this.aom1ControlBox.Controls.Add(this.aom1rfAmplitudeTextBox);
this.aom1ControlBox.Controls.Add(this.aom1Label2);
this.aom1ControlBox.Controls.Add(this.aom1Label0);
this.aom1ControlBox.Location = new System.Drawing.Point(3, 54);
this.aom1ControlBox.Name = "aom1ControlBox";
this.aom1ControlBox.Size = new System.Drawing.Size(541, 45);
this.aom1ControlBox.TabIndex = 19;
this.aom1ControlBox.TabStop = false;
this.aom1ControlBox.Text = "AOM 1 (MOT Repump)";
//
// aom1Label3
//
this.aom1Label3.AutoSize = true;
this.aom1Label3.Location = new System.Drawing.Point(522, 21);
this.aom1Label3.Name = "aom1Label3";
this.aom1Label3.Size = new System.Drawing.Size(14, 13);
this.aom1Label3.TabIndex = 17;
this.aom1Label3.Text = "V";
//
// aom1Label1
//
this.aom1Label1.AutoSize = true;
this.aom1Label1.Location = new System.Drawing.Point(260, 21);
this.aom1Label1.Name = "aom1Label1";
this.aom1Label1.Size = new System.Drawing.Size(29, 13);
this.aom1Label1.TabIndex = 16;
this.aom1Label1.Text = "MHz";
//
// aom1CheckBox
//
this.aom1CheckBox.AutoSize = true;
this.aom1CheckBox.Location = new System.Drawing.Point(38, 21);
this.aom1CheckBox.Name = "aom1CheckBox";
this.aom1CheckBox.Size = new System.Drawing.Size(15, 14);
this.aom1CheckBox.TabIndex = 10;
this.aom1CheckBox.UseVisualStyleBackColor = true;
//
// aom1rfFrequencyTextBox
//
this.aom1rfFrequencyTextBox.Location = new System.Drawing.Point(155, 17);
this.aom1rfFrequencyTextBox.Name = "aom1rfFrequencyTextBox";
this.aom1rfFrequencyTextBox.Size = new System.Drawing.Size(103, 20);
this.aom1rfFrequencyTextBox.TabIndex = 0;
this.aom1rfFrequencyTextBox.Text = "0";
//
// aom1rfAmplitudeTextBox
//
this.aom1rfAmplitudeTextBox.Location = new System.Drawing.Point(421, 17);
this.aom1rfAmplitudeTextBox.Name = "aom1rfAmplitudeTextBox";
this.aom1rfAmplitudeTextBox.Size = new System.Drawing.Size(100, 20);
this.aom1rfAmplitudeTextBox.TabIndex = 8;
this.aom1rfAmplitudeTextBox.Text = "0";
//
// aom1Label2
//
this.aom1Label2.AutoSize = true;
this.aom1Label2.Location = new System.Drawing.Point(348, 20);
this.aom1Label2.Name = "aom1Label2";
this.aom1Label2.Size = new System.Drawing.Size(70, 13);
this.aom1Label2.TabIndex = 7;
this.aom1Label2.Text = "RF Amplitude";
//
// aom1Label0
//
this.aom1Label0.AutoSize = true;
this.aom1Label0.Location = new System.Drawing.Point(78, 20);
this.aom1Label0.Name = "aom1Label0";
this.aom1Label0.Size = new System.Drawing.Size(74, 13);
this.aom1Label0.TabIndex = 6;
this.aom1Label0.Text = "RF Frequency";
//
// aom0ControlBox
//
this.aom0ControlBox.Controls.Add(this.aom0Label3);
this.aom0ControlBox.Controls.Add(this.aom0Label1);
this.aom0ControlBox.Controls.Add(this.aom0CheckBox);
this.aom0ControlBox.Controls.Add(this.aom0rfFrequencyTextBox);
this.aom0ControlBox.Controls.Add(this.aom0rfAmplitudeTextBox);
this.aom0ControlBox.Controls.Add(this.aom0Label2);
this.aom0ControlBox.Controls.Add(this.aom0Label0);
this.aom0ControlBox.Location = new System.Drawing.Point(3, 3);
this.aom0ControlBox.Name = "aom0ControlBox";
this.aom0ControlBox.Size = new System.Drawing.Size(541, 45);
this.aom0ControlBox.TabIndex = 12;
this.aom0ControlBox.TabStop = false;
this.aom0ControlBox.Text = "AOM 0 (MOT AOM)";
//
// aom0Label3
//
this.aom0Label3.AutoSize = true;
this.aom0Label3.Location = new System.Drawing.Point(522, 21);
this.aom0Label3.Name = "aom0Label3";
this.aom0Label3.Size = new System.Drawing.Size(14, 13);
this.aom0Label3.TabIndex = 17;
this.aom0Label3.Text = "V";
//
// aom0Label1
//
this.aom0Label1.AutoSize = true;
this.aom0Label1.Location = new System.Drawing.Point(260, 21);
this.aom0Label1.Name = "aom0Label1";
this.aom0Label1.Size = new System.Drawing.Size(29, 13);
this.aom0Label1.TabIndex = 16;
this.aom0Label1.Text = "MHz";
//
// aom0CheckBox
//
this.aom0CheckBox.AutoSize = true;
this.aom0CheckBox.Location = new System.Drawing.Point(38, 21);
this.aom0CheckBox.Name = "aom0CheckBox";
this.aom0CheckBox.Size = new System.Drawing.Size(15, 14);
this.aom0CheckBox.TabIndex = 10;
this.aom0CheckBox.UseVisualStyleBackColor = true;
//
// aom0rfFrequencyTextBox
//
this.aom0rfFrequencyTextBox.Location = new System.Drawing.Point(155, 17);
this.aom0rfFrequencyTextBox.Name = "aom0rfFrequencyTextBox";
this.aom0rfFrequencyTextBox.Size = new System.Drawing.Size(103, 20);
this.aom0rfFrequencyTextBox.TabIndex = 0;
this.aom0rfFrequencyTextBox.Text = "0";
//
// aom0rfAmplitudeTextBox
//
this.aom0rfAmplitudeTextBox.Location = new System.Drawing.Point(421, 17);
this.aom0rfAmplitudeTextBox.Name = "aom0rfAmplitudeTextBox";
this.aom0rfAmplitudeTextBox.Size = new System.Drawing.Size(100, 20);
this.aom0rfAmplitudeTextBox.TabIndex = 8;
this.aom0rfAmplitudeTextBox.Text = "0";
//
// aom0Label2
//
this.aom0Label2.AutoSize = true;
this.aom0Label2.Location = new System.Drawing.Point(348, 20);
this.aom0Label2.Name = "aom0Label2";
this.aom0Label2.Size = new System.Drawing.Size(70, 13);
this.aom0Label2.TabIndex = 7;
this.aom0Label2.Text = "RF Amplitude";
//
// aom0Label0
//
this.aom0Label0.AutoSize = true;
this.aom0Label0.Location = new System.Drawing.Point(78, 20);
this.aom0Label0.Name = "aom0Label0";
this.aom0Label0.Size = new System.Drawing.Size(74, 13);
this.aom0Label0.TabIndex = 6;
this.aom0Label0.Text = "RF Frequency";
//
// tabCoils
//
this.tabCoils.Controls.Add(this.coil1GroupBox);
this.tabCoils.Controls.Add(this.coil0GroupBox);
this.tabCoils.Location = new System.Drawing.Point(4, 22);
this.tabCoils.Name = "tabCoils";
this.tabCoils.Size = new System.Drawing.Size(658, 209);
this.tabCoils.TabIndex = 2;
this.tabCoils.Text = "Magnetic Field Control";
this.tabCoils.UseVisualStyleBackColor = true;
//
// coil1GroupBox
//
this.coil1GroupBox.Controls.Add(this.coil1Label1);
this.coil1GroupBox.Controls.Add(this.coil1CurrentTextBox);
this.coil1GroupBox.Controls.Add(this.coil1Label0);
this.coil1GroupBox.Location = new System.Drawing.Point(3, 54);
this.coil1GroupBox.Name = "coil1GroupBox";
this.coil1GroupBox.Size = new System.Drawing.Size(225, 45);
this.coil1GroupBox.TabIndex = 19;
this.coil1GroupBox.TabStop = false;
this.coil1GroupBox.Text = "Bias field coils";
//
// coil1Label1
//
this.coil1Label1.AutoSize = true;
this.coil1Label1.Location = new System.Drawing.Point(200, 21);
this.coil1Label1.Name = "coil1Label1";
this.coil1Label1.Size = new System.Drawing.Size(14, 13);
this.coil1Label1.TabIndex = 17;
this.coil1Label1.Text = "A";
//
// coil1CurrentTextBox
//
this.coil1CurrentTextBox.Location = new System.Drawing.Point(99, 17);
this.coil1CurrentTextBox.Name = "coil1CurrentTextBox";
this.coil1CurrentTextBox.Size = new System.Drawing.Size(100, 20);
this.coil1CurrentTextBox.TabIndex = 8;
this.coil1CurrentTextBox.Text = "0";
//
// coil1Label0
//
this.coil1Label0.AutoSize = true;
this.coil1Label0.Location = new System.Drawing.Point(40, 20);
this.coil1Label0.Name = "coil1Label0";
this.coil1Label0.Size = new System.Drawing.Size(41, 13);
this.coil1Label0.TabIndex = 7;
this.coil1Label0.Text = "Current";
//
// coil0GroupBox
//
this.coil0GroupBox.Controls.Add(this.coil0Label1);
this.coil0GroupBox.Controls.Add(this.coil0CurrentTextBox);
this.coil0GroupBox.Controls.Add(this.coil0Label0);
this.coil0GroupBox.Location = new System.Drawing.Point(3, 3);
this.coil0GroupBox.Name = "coil0GroupBox";
this.coil0GroupBox.Size = new System.Drawing.Size(225, 45);
this.coil0GroupBox.TabIndex = 13;
this.coil0GroupBox.TabStop = false;
this.coil0GroupBox.Text = "MOT coils";
//
// coil0Label1
//
this.coil0Label1.AutoSize = true;
this.coil0Label1.Location = new System.Drawing.Point(200, 21);
this.coil0Label1.Name = "coil0Label1";
this.coil0Label1.Size = new System.Drawing.Size(14, 13);
this.coil0Label1.TabIndex = 17;
this.coil0Label1.Text = "A";
//
// coil0CurrentTextBox
//
this.coil0CurrentTextBox.Location = new System.Drawing.Point(99, 17);
this.coil0CurrentTextBox.Name = "coil0CurrentTextBox";
this.coil0CurrentTextBox.Size = new System.Drawing.Size(100, 20);
this.coil0CurrentTextBox.TabIndex = 8;
this.coil0CurrentTextBox.Text = "0";
//
// coil0Label0
//
this.coil0Label0.AutoSize = true;
this.coil0Label0.Location = new System.Drawing.Point(40, 20);
this.coil0Label0.Name = "coil0Label0";
this.coil0Label0.Size = new System.Drawing.Size(41, 13);
this.coil0Label0.TabIndex = 7;
this.coil0Label0.Text = "Current";
//
// tabTranslationStage
//
this.tabTranslationStage.Controls.Add(this.groupBox4);
this.tabTranslationStage.Controls.Add(this.RS232GroupBox);
this.tabTranslationStage.Controls.Add(this.groupBox3);
this.tabTranslationStage.Controls.Add(this.groupBox2);
this.tabTranslationStage.Controls.Add(this.groupBox1);
this.tabTranslationStage.Controls.Add(this.initParamsBox);
this.tabTranslationStage.Location = new System.Drawing.Point(4, 22);
this.tabTranslationStage.Name = "tabTranslationStage";
this.tabTranslationStage.Size = new System.Drawing.Size(658, 209);
this.tabTranslationStage.TabIndex = 3;
this.tabTranslationStage.Text = "Translation Stage Control";
this.tabTranslationStage.UseVisualStyleBackColor = true;
//
// groupBox4
//
this.groupBox4.Controls.Add(this.AutoTriggerCheckBox);
this.groupBox4.Location = new System.Drawing.Point(558, 7);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(90, 46);
this.groupBox4.TabIndex = 13;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Triggering";
//
// AutoTriggerCheckBox
//
this.AutoTriggerCheckBox.AutoSize = true;
this.AutoTriggerCheckBox.Checked = true;
this.AutoTriggerCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.AutoTriggerCheckBox.Location = new System.Drawing.Point(6, 22);
this.AutoTriggerCheckBox.Name = "AutoTriggerCheckBox";
this.AutoTriggerCheckBox.Size = new System.Drawing.Size(81, 17);
this.AutoTriggerCheckBox.TabIndex = 12;
this.AutoTriggerCheckBox.Text = "AutoTrigger";
this.AutoTriggerCheckBox.UseVisualStyleBackColor = true;
this.AutoTriggerCheckBox.CheckedChanged += new System.EventHandler(this.AutoTriggerCheckBox_CheckedChanged);
//
// RS232GroupBox
//
this.RS232GroupBox.Controls.Add(this.TSConnectButton);
this.RS232GroupBox.Controls.Add(this.disposeButton);
this.RS232GroupBox.Location = new System.Drawing.Point(5, 3);
this.RS232GroupBox.Name = "RS232GroupBox";
this.RS232GroupBox.Size = new System.Drawing.Size(260, 55);
this.RS232GroupBox.TabIndex = 16;
this.RS232GroupBox.TabStop = false;
this.RS232GroupBox.Text = "RS232";
//
// TSConnectButton
//
this.TSConnectButton.Location = new System.Drawing.Point(9, 22);
this.TSConnectButton.Name = "TSConnectButton";
this.TSConnectButton.Size = new System.Drawing.Size(100, 23);
this.TSConnectButton.TabIndex = 16;
this.TSConnectButton.Text = "Connect";
this.TSConnectButton.UseVisualStyleBackColor = true;
this.TSConnectButton.Click += new System.EventHandler(this.TSConnectButton_Click);
//
// disposeButton
//
this.disposeButton.Location = new System.Drawing.Point(115, 22);
this.disposeButton.Name = "disposeButton";
this.disposeButton.Size = new System.Drawing.Size(100, 23);
this.disposeButton.TabIndex = 4;
this.disposeButton.Text = "Disconnect";
this.disposeButton.UseVisualStyleBackColor = true;
this.disposeButton.Click += new System.EventHandler(this.disposeButton_Click);
//
// groupBox3
//
this.groupBox3.Controls.Add(this.TSListAllButton);
this.groupBox3.Controls.Add(this.checkStatusButton);
this.groupBox3.Controls.Add(this.read);
this.groupBox3.Controls.Add(this.TSClearButton);
this.groupBox3.Location = new System.Drawing.Point(271, 132);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(365, 54);
this.groupBox3.TabIndex = 7;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Console";
//
// TSListAllButton
//
this.TSListAllButton.Location = new System.Drawing.Point(184, 17);
this.TSListAllButton.Name = "TSListAllButton";
this.TSListAllButton.Size = new System.Drawing.Size(83, 23);
this.TSListAllButton.TabIndex = 17;
this.TSListAllButton.Text = "List all";
this.TSListAllButton.UseVisualStyleBackColor = true;
this.TSListAllButton.Click += new System.EventHandler(this.button2_Click);
//
// checkStatusButton
//
this.checkStatusButton.Location = new System.Drawing.Point(95, 17);
this.checkStatusButton.Name = "checkStatusButton";
this.checkStatusButton.Size = new System.Drawing.Size(83, 23);
this.checkStatusButton.TabIndex = 18;
this.checkStatusButton.Text = "Check status";
this.checkStatusButton.UseVisualStyleBackColor = true;
this.checkStatusButton.Click += new System.EventHandler(this.checkStatusButton_Click);
//
// read
//
this.read.Location = new System.Drawing.Point(6, 17);
this.read.Name = "read";
this.read.Size = new System.Drawing.Size(83, 23);
this.read.TabIndex = 5;
this.read.Text = "Read";
this.read.UseVisualStyleBackColor = true;
this.read.Click += new System.EventHandler(this.read_Click);
//
// TSClearButton
//
this.TSClearButton.Location = new System.Drawing.Point(273, 17);
this.TSClearButton.Name = "TSClearButton";
this.TSClearButton.Size = new System.Drawing.Size(83, 23);
this.TSClearButton.TabIndex = 8;
this.TSClearButton.Text = "Clear";
this.TSClearButton.UseVisualStyleBackColor = true;
this.TSClearButton.Click += new System.EventHandler(this.TSClearButton_Click);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.TSHomeButton);
this.groupBox2.Controls.Add(this.TSGoButton);
this.groupBox2.Controls.Add(this.TSReturnButton);
this.groupBox2.Location = new System.Drawing.Point(271, 70);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(278, 54);
this.groupBox2.TabIndex = 11;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Motion";
//
// TSHomeButton
//
this.TSHomeButton.Location = new System.Drawing.Point(183, 19);
this.TSHomeButton.Name = "TSHomeButton";
this.TSHomeButton.Size = new System.Drawing.Size(83, 23);
this.TSHomeButton.TabIndex = 17;
this.TSHomeButton.Text = "Home";
this.TSHomeButton.UseVisualStyleBackColor = true;
this.TSHomeButton.Click += new System.EventHandler(this.TSHomeButton_Click);
//
// TSGoButton
//
this.TSGoButton.Location = new System.Drawing.Point(6, 19);
this.TSGoButton.Name = "TSGoButton";
this.TSGoButton.Size = new System.Drawing.Size(83, 23);
this.TSGoButton.TabIndex = 2;
this.TSGoButton.Text = "Go";
this.TSGoButton.UseVisualStyleBackColor = true;
this.TSGoButton.Click += new System.EventHandler(this.TSGoButton_Click);
//
// TSReturnButton
//
this.TSReturnButton.Location = new System.Drawing.Point(95, 19);
this.TSReturnButton.Name = "TSReturnButton";
this.TSReturnButton.Size = new System.Drawing.Size(83, 23);
this.TSReturnButton.TabIndex = 6;
this.TSReturnButton.Text = "Return";
this.TSReturnButton.UseVisualStyleBackColor = true;
this.TSReturnButton.Click += new System.EventHandler(this.TSReturnButton_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.TSRestartButton);
this.groupBox1.Controls.Add(this.TSOnButton);
this.groupBox1.Controls.Add(this.TSOffButton);
this.groupBox1.Location = new System.Drawing.Point(271, 7);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(277, 56);
this.groupBox1.TabIndex = 10;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Enable";
//
// TSRestartButton
//
this.TSRestartButton.Location = new System.Drawing.Point(183, 19);
this.TSRestartButton.Name = "TSRestartButton";
this.TSRestartButton.Size = new System.Drawing.Size(83, 23);
this.TSRestartButton.TabIndex = 7;
this.TSRestartButton.Text = "Restart";
this.TSRestartButton.UseVisualStyleBackColor = true;
this.TSRestartButton.Click += new System.EventHandler(this.TSRestartButton_Click);
//
// TSOnButton
//
this.TSOnButton.Location = new System.Drawing.Point(6, 19);
this.TSOnButton.Name = "TSOnButton";
this.TSOnButton.Size = new System.Drawing.Size(83, 23);
this.TSOnButton.TabIndex = 1;
this.TSOnButton.Text = "On";
this.TSOnButton.UseVisualStyleBackColor = true;
this.TSOnButton.Click += new System.EventHandler(this.TSOnButton_Click);
//
// TSOffButton
//
this.TSOffButton.Location = new System.Drawing.Point(95, 19);
this.TSOffButton.Name = "TSOffButton";
this.TSOffButton.Size = new System.Drawing.Size(83, 23);
this.TSOffButton.TabIndex = 3;
this.TSOffButton.Text = "Off";
this.TSOffButton.UseVisualStyleBackColor = true;
this.TSOffButton.Click += new System.EventHandler(this.TSOffButton_Click);
//
// initParamsBox
//
this.initParamsBox.Controls.Add(this.TSInitButton);
this.initParamsBox.Controls.Add(this.label9);
this.initParamsBox.Controls.Add(this.label8);
this.initParamsBox.Controls.Add(this.label7);
this.initParamsBox.Controls.Add(this.label6);
this.initParamsBox.Controls.Add(this.label5);
this.initParamsBox.Controls.Add(this.label4);
this.initParamsBox.Controls.Add(this.label3);
this.initParamsBox.Controls.Add(this.label2);
this.initParamsBox.Controls.Add(this.TSVelTextBox);
this.initParamsBox.Controls.Add(this.TSStepsTextBox);
this.initParamsBox.Controls.Add(this.TSDecTextBox);
this.initParamsBox.Controls.Add(this.TSAccTextBox);
this.initParamsBox.Location = new System.Drawing.Point(5, 63);
this.initParamsBox.Name = "initParamsBox";
this.initParamsBox.Size = new System.Drawing.Size(260, 143);
this.initParamsBox.TabIndex = 9;
this.initParamsBox.TabStop = false;
this.initParamsBox.Text = "Initialize parameters";
//
// TSInitButton
//
this.TSInitButton.Location = new System.Drawing.Point(115, 114);
this.TSInitButton.Name = "TSInitButton";
this.TSInitButton.Size = new System.Drawing.Size(100, 23);
this.TSInitButton.TabIndex = 0;
this.TSInitButton.Text = "Initialize";
this.TSInitButton.UseVisualStyleBackColor = true;
this.TSInitButton.Click += new System.EventHandler(this.TSInitButton_Click);
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(218, 98);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(33, 13);
this.label9.TabIndex = 15;
this.label9.Text = "mm/s";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(218, 72);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(23, 13);
this.label8.TabIndex = 14;
this.label8.Text = "mm";
this.label8.Click += new System.EventHandler(this.label8_Click);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(218, 46);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(39, 13);
this.label7.TabIndex = 13;
this.label7.Text = "mm/s2";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(218, 21);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(39, 13);
this.label6.TabIndex = 12;
this.label6.Text = "mm/s2";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(9, 98);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(44, 13);
this.label5.TabIndex = 8;
this.label5.Text = "Velocity";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(8, 72);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(90, 13);
this.label4.TabIndex = 7;
this.label4.Text = "Distance to travel";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(8, 46);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(67, 13);
this.label3.TabIndex = 6;
this.label3.Text = "Deceleration";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(9, 20);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(66, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Acceleration";
//
// TSVelTextBox
//
this.TSVelTextBox.Location = new System.Drawing.Point(115, 92);
this.TSVelTextBox.Name = "TSVelTextBox";
this.TSVelTextBox.Size = new System.Drawing.Size(100, 20);
this.TSVelTextBox.TabIndex = 4;
this.TSVelTextBox.Text = "50";
//
// TSStepsTextBox
//
this.TSStepsTextBox.Location = new System.Drawing.Point(115, 67);
this.TSStepsTextBox.Name = "TSStepsTextBox";
this.TSStepsTextBox.Size = new System.Drawing.Size(100, 20);
this.TSStepsTextBox.TabIndex = 3;
this.TSStepsTextBox.Text = "10000";
//
// TSDecTextBox
//
this.TSDecTextBox.Location = new System.Drawing.Point(115, 41);
this.TSDecTextBox.Name = "TSDecTextBox";
this.TSDecTextBox.Size = new System.Drawing.Size(100, 20);
this.TSDecTextBox.TabIndex = 2;
this.TSDecTextBox.Text = "50";
//
// TSAccTextBox
//
this.TSAccTextBox.Location = new System.Drawing.Point(115, 15);
this.TSAccTextBox.Name = "TSAccTextBox";
this.TSAccTextBox.Size = new System.Drawing.Size(100, 20);
this.TSAccTextBox.TabIndex = 1;
this.TSAccTextBox.Text = "50";
//
// button1
//
this.button1.Location = new System.Drawing.Point(0, 0);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
//
// checkBox1
//
this.checkBox1.Location = new System.Drawing.Point(0, 0);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(104, 24);
this.checkBox1.TabIndex = 0;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(0, 0);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 0;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(0, 0);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(100, 20);
this.textBox2.TabIndex = 0;
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.windowsToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(794, 24);
this.menuStrip.TabIndex = 15;
this.menuStrip.Text = "menuStrip";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.loadParametersToolStripMenuItem,
this.saveParametersToolStripMenuItem,
this.toolStripSeparator1,
this.saveImageToolStripMenuItem,
this.toolStripSeparator2,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// loadParametersToolStripMenuItem
//
this.loadParametersToolStripMenuItem.Name = "loadParametersToolStripMenuItem";
this.loadParametersToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.loadParametersToolStripMenuItem.Text = "Load parameters";
this.loadParametersToolStripMenuItem.Click += new System.EventHandler(this.loadParametersToolStripMenuItem_Click);
//
// saveParametersToolStripMenuItem
//
this.saveParametersToolStripMenuItem.Name = "saveParametersToolStripMenuItem";
this.saveParametersToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.saveParametersToolStripMenuItem.Text = "Save parameters on UI";
this.saveParametersToolStripMenuItem.Click += new System.EventHandler(this.saveParametersToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(188, 6);
//
// saveImageToolStripMenuItem
//
this.saveImageToolStripMenuItem.Name = "saveImageToolStripMenuItem";
this.saveImageToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.saveImageToolStripMenuItem.Text = "Save image";
this.saveImageToolStripMenuItem.Click += new System.EventHandler(this.saveImageToolStripMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(188, 6);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(191, 22);
this.exitToolStripMenuItem.Text = "Exit";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// windowsToolStripMenuItem
//
this.windowsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.hardwareMonitorToolStripMenuItem,
this.openImageViewerToolStripMenuItem});
this.windowsToolStripMenuItem.Name = "windowsToolStripMenuItem";
this.windowsToolStripMenuItem.Size = new System.Drawing.Size(68, 20);
this.windowsToolStripMenuItem.Text = "Windows";
//
// hardwareMonitorToolStripMenuItem
//
this.hardwareMonitorToolStripMenuItem.Name = "hardwareMonitorToolStripMenuItem";
this.hardwareMonitorToolStripMenuItem.Size = new System.Drawing.Size(266, 22);
this.hardwareMonitorToolStripMenuItem.Text = "Open new hardware monitor";
this.hardwareMonitorToolStripMenuItem.Click += new System.EventHandler(this.hardwareMonitorToolStripMenuItem_Click);
//
// openImageViewerToolStripMenuItem
//
this.openImageViewerToolStripMenuItem.Name = "openImageViewerToolStripMenuItem";
this.openImageViewerToolStripMenuItem.Size = new System.Drawing.Size(266, 22);
this.openImageViewerToolStripMenuItem.Text = "Start camera and open image viewer";
this.openImageViewerToolStripMenuItem.Click += new System.EventHandler(this.openImageViewerToolStripMenuItem_Click);
//
// remoteControlLED
//
this.remoteControlLED.LedStyle = NationalInstruments.UI.LedStyle.Round3D;
this.remoteControlLED.Location = new System.Drawing.Point(761, 32);
this.remoteControlLED.Name = "remoteControlLED";
this.remoteControlLED.Size = new System.Drawing.Size(25, 24);
this.remoteControlLED.TabIndex = 16;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(675, 36);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 13);
this.label1.TabIndex = 18;
this.label1.Text = "Remote Control";
//
// updateHardwareButton
//
this.updateHardwareButton.Location = new System.Drawing.Point(678, 62);
this.updateHardwareButton.Name = "updateHardwareButton";
this.updateHardwareButton.Size = new System.Drawing.Size(102, 23);
this.updateHardwareButton.TabIndex = 21;
this.updateHardwareButton.Text = "Update hardware";
this.updateHardwareButton.UseVisualStyleBackColor = true;
this.updateHardwareButton.Click += new System.EventHandler(this.updateHardwareButton_Click);
//
// consoleRichTextBox
//
this.consoleRichTextBox.BackColor = System.Drawing.Color.Black;
this.consoleRichTextBox.ForeColor = System.Drawing.Color.Lime;
this.consoleRichTextBox.Location = new System.Drawing.Point(3, 264);
this.consoleRichTextBox.Name = "consoleRichTextBox";
this.consoleRichTextBox.ReadOnly = true;
this.consoleRichTextBox.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical;
this.consoleRichTextBox.Size = new System.Drawing.Size(791, 154);
this.consoleRichTextBox.TabIndex = 23;
this.consoleRichTextBox.Text = "";
//
// ControlWindow
//
this.ClientSize = new System.Drawing.Size(794, 419);
this.Controls.Add(this.consoleRichTextBox);
this.Controls.Add(this.updateHardwareButton);
this.Controls.Add(this.label1);
this.Controls.Add(this.remoteControlLED);
this.Controls.Add(this.shcTabs);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "ControlWindow";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Sympathetic Hardware Control";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.WindowClosing);
this.Load += new System.EventHandler(this.WindowLoaded);
this.shcTabs.ResumeLayout(false);
this.tabCamera.ResumeLayout(false);
this.tabLasers.ResumeLayout(false);
this.ShutterControlBox.ResumeLayout(false);
this.ShutterControlBox.PerformLayout();
this.aom3ControlBox.ResumeLayout(false);
this.aom3ControlBox.PerformLayout();
this.aom2ControlBox.ResumeLayout(false);
this.aom2ControlBox.PerformLayout();
this.aom1ControlBox.ResumeLayout(false);
this.aom1ControlBox.PerformLayout();
this.aom0ControlBox.ResumeLayout(false);
this.aom0ControlBox.PerformLayout();
this.tabCoils.ResumeLayout(false);
this.coil1GroupBox.ResumeLayout(false);
this.coil1GroupBox.PerformLayout();
this.coil0GroupBox.ResumeLayout(false);
this.coil0GroupBox.PerformLayout();
this.tabTranslationStage.ResumeLayout(false);
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.RS232GroupBox.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.initParamsBox.ResumeLayout(false);
this.initParamsBox.PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.remoteControlLED)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region ThreadSafe wrappers
private void setCheckBox(CheckBox box, bool state)
{
box.Invoke(new setCheckDelegate(setCheckHelper), new object[] { box, state });
}
private delegate void setCheckDelegate(CheckBox box, bool state);
private void setCheckHelper(CheckBox box, bool state)
{
box.Checked = state;
}
private void setTabEnable(TabControl box, bool state)
{
box.Invoke(new setTabEnableDelegate(setTabEnableHelper), new object[] { box, state });
}
private delegate void setTabEnableDelegate(TabControl box, bool state);
private void setTabEnableHelper(TabControl box, bool state)
{
box.Enabled = state;
}
private void setTextBox(TextBox box, string text)
{
box.Invoke(new setTextDelegate(setTextHelper), new object[] { box, text });
}
private delegate void setTextDelegate(TextBox box, string text);
private void setTextHelper(TextBox box, string text)
{
box.Text = text;
}
private void setRichTextBox(RichTextBox box, string text)
{
box.Invoke(new setRichTextDelegate(setRichTextHelper), new object[] { box, text });
}
private delegate void setRichTextDelegate(RichTextBox box, string text);
private void setRichTextHelper(RichTextBox box, string text)
{
box.AppendText(text);
consoleRichTextBox.ScrollToCaret();
}
private void setLED(NationalInstruments.UI.WindowsForms.Led led, bool val)
{
led.Invoke(new SetLedDelegate(SetLedHelper), new object[] { led, val });
}
private delegate void SetLedDelegate(NationalInstruments.UI.WindowsForms.Led led, bool val);
private void SetLedHelper(NationalInstruments.UI.WindowsForms.Led led, bool val)
{
led.Value = val;
}
#endregion
#region Declarations
//Declare stuff here
public TabControl shcTabs;
public TabPage tabCamera;
public TabPage tabLasers;
public TabPage tabCoils;
private GroupBox aom0ControlBox;
public CheckBox aom0CheckBox;
public TextBox aom0rfFrequencyTextBox;
public TextBox aom0rfAmplitudeTextBox;
private Label aom0Label2;
private Label aom0Label0;
private Label aom0Label1;
private Label aom0Label3;
private GroupBox aom3ControlBox;
private Label aom3Label3;
private Label aom3Label1;
public CheckBox aom3CheckBox;
public TextBox aom3rfFrequencyTextBox;
public TextBox aom3rfAmplitudeTextBox;
private Label aom3Label2;
private Label aom3Label0;
private GroupBox aom2ControlBox;
private Label aom2Label3;
private Label aom2Label1;
public CheckBox aom2CheckBox;
public TextBox aom2rfFrequencyTextBox;
public TextBox aom2rfAmplitudeTextBox;
private Label aom2Label2;
private Label aom2Label0;
private GroupBox aom1ControlBox;
private Label aom1Label3;
private Label aom1Label1;
public CheckBox aom1CheckBox;
public TextBox aom1rfFrequencyTextBox;
public TextBox aom1rfAmplitudeTextBox;
private Label aom1Label2;
private Label aom1Label0;
private GroupBox coil1GroupBox;
private Label coil1Label1;
public TextBox coil1CurrentTextBox;
private Label coil1Label0;
private GroupBox coil0GroupBox;
private Label coil0Label1;
public TextBox coil0CurrentTextBox;
private Label coil0Label0;
private Button button1;
public CheckBox checkBox1;
public TextBox textBox1;
public TextBox textBox2;
private MenuStrip menuStrip;
private ToolStripMenuItem fileToolStripMenuItem;
private ToolStripMenuItem loadParametersToolStripMenuItem;
private ToolStripMenuItem saveParametersToolStripMenuItem;
private ToolStripMenuItem saveImageToolStripMenuItem;
private ToolStripMenuItem exitToolStripMenuItem;
private ToolStripSeparator toolStripSeparator1;
private ToolStripSeparator toolStripSeparator2;
private Button snapshotButton;
private Led remoteControlLED;
private Label label1;
private Button updateHardwareButton;
private ToolStripMenuItem windowsToolStripMenuItem;
private ToolStripMenuItem hardwareMonitorToolStripMenuItem;
private RichTextBox consoleRichTextBox;
private ToolStripMenuItem openImageViewerToolStripMenuItem;
private Button streamButton;
private Button stopStreamButton;
private TabPage tabTranslationStage;
private Button TSOnButton;
private Button TSInitButton;
private Button TSOffButton;
private Button TSGoButton;
private Button disposeButton;
private Button read;
private Button TSReturnButton;
private Button TSClearButton;
private Button TSRestartButton;
private Button TSHomeButton;
private Button checkStatusButton;
private Button TSListAllButton;
private GroupBox initParamsBox;
private TextBox TSVelTextBox;
private TextBox TSStepsTextBox;
private TextBox TSDecTextBox;
private TextBox TSAccTextBox;
private GroupBox groupBox3;
private GroupBox groupBox2;
private GroupBox groupBox1;
private Label label5;
private Label label4;
private Label label3;
private Label label2;
private Label label9;
private Label label8;
private Label label7;
private Label label6;
private GroupBox groupBox4;
private CheckBox AutoTriggerCheckBox;
private Button TSConnectButton;
private GroupBox RS232GroupBox;
public CheckBox shutterCheckBox;
#endregion
#region Click Handlers
private void saveParametersToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.SaveParametersWithDialog();
}
private void saveImageToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.SaveImageWithDialog();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void updateHardwareButton_Click(object sender, EventArgs e)
{
controller.UpdateHardware();
}
private void loadParametersToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.LoadParametersWithDialog();
}
private void TSInitButton_Click(object sender, EventArgs e)
{
controller.TSInitialize(double.Parse(TSAccTextBox.Text), double.Parse(TSDecTextBox.Text),
double.Parse(TSStepsTextBox.Text), double.Parse(TSVelTextBox.Text));
}
private void TSOnButton_Click(object sender, EventArgs e)
{
controller.TSOn();
}
private void TSGoButton_Click(object sender, EventArgs e)
{
controller.TSGo();
}
private void TSOffButton_Click(object sender, EventArgs e)
{
controller.TSOff();
}
private void read_Click(object sender, EventArgs e)
{
controller.TSRead();
}
private void TSReturnButton_Click(object sender, EventArgs e)
{
controller.TSReturn();
}
private void TSRestartButton_Click(object sender, EventArgs e)
{
controller.TSRestart();
}
private void TSClearButton_Click(object sender, EventArgs e)
{
controller.TSClear();
}
private void disposeButton_Click(object sender, EventArgs e)
{
controller.TSDisconnect();
}
private void TSConnectButton_Click(object sender, EventArgs e)
{
controller.TSConnect();
}
private void AutoTriggerCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (AutoTriggerCheckBox.Checked)
{
controller.TSAutoTriggerEnable();
}
if (!AutoTriggerCheckBox.Checked)
{
controller.TSAutoTriggerDisable();
}
}
private void TSHomeButton_Click(object sender, EventArgs e)
{
controller.TSHome();
}
private void checkStatusButton_Click(object sender, EventArgs e)
{
controller.TSCheckStatus();
}
private void button2_Click(object sender, EventArgs e)
{
controller.TSListAll();
}
#endregion
#region Public properties for controlling UI.
//This gets/sets the values on the GUI panel
public void WriteToConsole(string text)
{
setRichTextBox(consoleRichTextBox, ">> " + text + "\n");
}
public double ReadAnalog(string channelName)
{
return double.Parse(AOTextBoxes[channelName].Text);
}
public void SetAnalog(string channelName, double value)
{
setTextBox(AOTextBoxes[channelName], Convert.ToString(value));
}
public bool ReadDigital(string channelName)
{
return DOCheckBoxes[channelName].Checked;
}
public void SetDigital(string channelName, bool value)
{
setCheckBox(DOCheckBoxes[channelName], value);
}
#endregion
#region Camera Control
private void snapshotButton_Click(object sender, EventArgs e)
{
controller.CameraSnapshot();
}
private void streamButton_Click(object sender, EventArgs e)
{
controller.CameraStream();
}
private void stopStreamButton_Click(object sender, EventArgs e)
{
controller.StopCameraStream();
}
#endregion
#region UI state
public void UpdateUIState(Controller.SHCUIControlState state)
{
switch (state)
{
case Controller.SHCUIControlState.OFF:
setLED(remoteControlLED, false);
setTabEnable(shcTabs, true);
break;
case Controller.SHCUIControlState.LOCAL:
setLED(remoteControlLED, false);
setTabEnable(shcTabs, true);
break;
case Controller.SHCUIControlState.REMOTE:
setLED(remoteControlLED, true);
setTabEnable(shcTabs, false) ;
break;
}
}
#endregion
#region Other Windows
private void hardwareMonitorToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.OpenNewHardwareMonitorWindow();
}
private void openImageViewerToolStripMenuItem_Click(object sender, EventArgs e)
{
controller.StartCameraControl();
}
#endregion
private void label8_Click(object sender, EventArgs e)
{
}
private GroupBox ShutterControlBox;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering
{
public sealed class VolumeComponentListEditor
{
public VolumeProfile asset { get; private set; }
Editor m_BaseEditor;
SerializedObject m_SerializedObject;
SerializedProperty m_ComponentsProperty;
Dictionary<Type, Type> m_EditorTypes; // Component type => Editor type
List<VolumeComponentEditor> m_Editors;
static VolumeComponent s_ClipboardContent;
public VolumeComponentListEditor(Editor editor)
{
Assert.IsNotNull(editor);
m_BaseEditor = editor;
}
public void Init(VolumeProfile asset, SerializedObject serializedObject)
{
Assert.IsNotNull(asset);
Assert.IsNotNull(serializedObject);
this.asset = asset;
m_SerializedObject = serializedObject;
m_ComponentsProperty = serializedObject.Find((VolumeProfile x) => x.components);
Assert.IsNotNull(m_ComponentsProperty);
m_EditorTypes = new Dictionary<Type, Type>();
m_Editors = new List<VolumeComponentEditor>();
// Gets the list of all available component editors
var editorTypes = CoreUtils.GetAllTypesDerivedFrom<VolumeComponentEditor>()
.Where(
t => t.IsDefined(typeof(VolumeComponentEditorAttribute), false)
&& !t.IsAbstract
);
// Map them to their corresponding component type
foreach (var editorType in editorTypes)
{
var attribute = (VolumeComponentEditorAttribute)editorType.GetCustomAttributes(typeof(VolumeComponentEditorAttribute), false)[0];
m_EditorTypes.Add(attribute.componentType, editorType);
}
// Create editors for existing components
var components = asset.components;
for (int i = 0; i < components.Count; i++)
CreateEditor(components[i], m_ComponentsProperty.GetArrayElementAtIndex(i));
// Keep track of undo/redo to redraw the inspector when that happens
Undo.undoRedoPerformed += OnUndoRedoPerformed;
}
void OnUndoRedoPerformed()
{
asset.isDirty = true;
// Dumb hack to make sure the serialized object is up to date on undo (else there'll be
// a state mismatch when this class is used in a GameObject inspector).
m_SerializedObject.Update();
m_SerializedObject.ApplyModifiedProperties();
// Seems like there's an issue with the inspector not repainting after some undo events
// This will take care of that
m_BaseEditor.Repaint();
}
// index is only used when we need to re-create a component in a specific spot (e.g. reset)
void CreateEditor(VolumeComponent component, SerializedProperty property, int index = -1, bool forceOpen = false)
{
var componentType = component.GetType();
Type editorType;
if (!m_EditorTypes.TryGetValue(componentType, out editorType))
editorType = typeof(VolumeComponentEditor);
var editor = (VolumeComponentEditor)Activator.CreateInstance(editorType);
editor.Init(component, m_BaseEditor);
editor.baseProperty = property.Copy();
if (forceOpen)
editor.baseProperty.isExpanded = true;
if (index < 0)
m_Editors.Add(editor);
else
m_Editors[index] = editor;
}
void RefreshEditors()
{
// Disable all editors first
foreach (var editor in m_Editors)
editor.OnDisable();
// Remove them
m_Editors.Clear();
// Recreate editors for existing settings, if any
var components = asset.components;
for (int i = 0; i < components.Count; i++)
CreateEditor(components[i], m_ComponentsProperty.GetArrayElementAtIndex(i));
}
public void Clear()
{
if (m_Editors == null)
return; // Hasn't been inited yet
foreach (var editor in m_Editors)
editor.OnDisable();
m_Editors.Clear();
m_EditorTypes.Clear();
// ReSharper disable once DelegateSubtraction
Undo.undoRedoPerformed -= OnUndoRedoPerformed;
}
public void OnGUI()
{
if (asset == null)
return;
if (asset.isDirty)
{
RefreshEditors();
asset.isDirty = false;
}
bool isEditable = !VersionControl.Provider.isActive
|| AssetDatabase.IsOpenForEdit(asset, StatusQueryOptions.UseCachedIfPossible);
using (new EditorGUI.DisabledScope(!isEditable))
{
// Component list
for (int i = 0; i < m_Editors.Count; i++)
{
var editor = m_Editors[i];
string title = editor.GetDisplayTitle();
int id = i; // Needed for closure capture below
CoreEditorUtils.DrawSplitter();
bool displayContent = CoreEditorUtils.DrawHeaderToggle(
title,
editor.baseProperty,
editor.activeProperty,
pos => OnContextClick(pos, editor.target, id)
);
if (displayContent)
{
using (new EditorGUI.DisabledScope(!editor.activeProperty.boolValue))
editor.OnInternalInspectorGUI();
}
}
if (m_Editors.Count > 0)
CoreEditorUtils.DrawSplitter();
else
EditorGUILayout.HelpBox("This Volume Profile contains no overrides.", MessageType.Info);
EditorGUILayout.Space();
using (var hscope = new EditorGUILayout.HorizontalScope())
{
if (GUILayout.Button(EditorGUIUtility.TrTextContent("Add Override"), EditorStyles.miniButton))
{
var r = hscope.rect;
var pos = new Vector2(r.x + r.width / 2f, r.yMax + 18f);
FilterWindow.Show(pos, new VolumeComponentProvider(asset, this));
}
}
}
}
void OnContextClick(Vector2 position, VolumeComponent targetComponent, int id)
{
var menu = new GenericMenu();
if (id == 0)
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Move Up"));
else
menu.AddItem(EditorGUIUtility.TrTextContent("Move Up"), false, () => MoveComponent(id, -1));
if (id == m_Editors.Count - 1)
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Move Down"));
else
menu.AddItem(EditorGUIUtility.TrTextContent("Move Down"), false, () => MoveComponent(id, 1));
menu.AddSeparator(string.Empty);
menu.AddItem(EditorGUIUtility.TrTextContent("Reset"), false, () => ResetComponent(targetComponent.GetType(), id));
menu.AddItem(EditorGUIUtility.TrTextContent("Remove"), false, () => RemoveComponent(id));
menu.AddSeparator(string.Empty);
menu.AddItem(EditorGUIUtility.TrTextContent("Copy Settings"), false, () => CopySettings(targetComponent));
if (CanPaste(targetComponent))
menu.AddItem(EditorGUIUtility.TrTextContent("Paste Settings"), false, () => PasteSettings(targetComponent));
else
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Paste Settings"));
menu.AddSeparator(string.Empty);
menu.AddItem(EditorGUIUtility.TrTextContent("Toggle All"), false, () => m_Editors[id].SetAllOverridesTo(true));
menu.AddItem(EditorGUIUtility.TrTextContent("Toggle None"), false, () => m_Editors[id].SetAllOverridesTo(false));
menu.DropDown(new Rect(position, Vector2.zero));
}
VolumeComponent CreateNewComponent(Type type)
{
var effect = (VolumeComponent)ScriptableObject.CreateInstance(type);
effect.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy;
effect.name = type.Name;
return effect;
}
internal void AddComponent(Type type)
{
m_SerializedObject.Update();
var component = CreateNewComponent(type);
Undo.RegisterCreatedObjectUndo(component, "Add Volume Override");
// Store this new effect as a subasset so we can reference it safely afterwards
// Only when we're not dealing with an instantiated asset
if (EditorUtility.IsPersistent(asset))
AssetDatabase.AddObjectToAsset(component, asset);
// Grow the list first, then add - that's how serialized lists work in Unity
m_ComponentsProperty.arraySize++;
var componentProp = m_ComponentsProperty.GetArrayElementAtIndex(m_ComponentsProperty.arraySize - 1);
componentProp.objectReferenceValue = component;
// Force save / refresh
if (EditorUtility.IsPersistent(asset))
{
EditorUtility.SetDirty(asset);
AssetDatabase.SaveAssets();
}
// Create & store the internal editor object for this effect
CreateEditor(component, componentProp, forceOpen: true);
m_SerializedObject.ApplyModifiedProperties();
}
internal void RemoveComponent(int id)
{
// Huh. Hack to keep foldout state on the next element...
bool nextFoldoutState = false;
if (id < m_Editors.Count - 1)
nextFoldoutState = m_Editors[id + 1].baseProperty.isExpanded;
// Remove from the cached editors list
m_Editors[id].OnDisable();
m_Editors.RemoveAt(id);
m_SerializedObject.Update();
var property = m_ComponentsProperty.GetArrayElementAtIndex(id);
var component = property.objectReferenceValue;
// Unassign it (should be null already but serialization does funky things
property.objectReferenceValue = null;
// ...and remove the array index itself from the list
m_ComponentsProperty.DeleteArrayElementAtIndex(id);
// Finally refresh editor reference to the serialized settings list
for (int i = 0; i < m_Editors.Count; i++)
m_Editors[i].baseProperty = m_ComponentsProperty.GetArrayElementAtIndex(i).Copy();
// Set the proper foldout state if needed
if (id < m_Editors.Count)
m_Editors[id].baseProperty.isExpanded = nextFoldoutState;
m_SerializedObject.ApplyModifiedProperties();
// Destroy the setting object after ApplyModifiedProperties(). If we do it before, redo
// actions will be in the wrong order and the reference to the setting object in the
// list will be lost.
Undo.DestroyObjectImmediate(component);
// Force save / refresh
EditorUtility.SetDirty(asset);
AssetDatabase.SaveAssets();
}
// Reset is done by deleting and removing the object from the list and adding a new one in
// the same spot as it was before
internal void ResetComponent(Type type, int id)
{
// Remove from the cached editors list
m_Editors[id].OnDisable();
m_Editors[id] = null;
m_SerializedObject.Update();
var property = m_ComponentsProperty.GetArrayElementAtIndex(id);
var prevComponent = property.objectReferenceValue;
// Unassign it but down remove it from the array to keep the index available
property.objectReferenceValue = null;
// Create a new object
var newComponent = CreateNewComponent(type);
Undo.RegisterCreatedObjectUndo(newComponent, "Reset Volume Overrides");
// Store this new effect as a subasset so we can reference it safely afterwards
AssetDatabase.AddObjectToAsset(newComponent, asset);
// Put it in the reserved space
property.objectReferenceValue = newComponent;
// Create & store the internal editor object for this effect
CreateEditor(newComponent, property, id);
m_SerializedObject.ApplyModifiedProperties();
// Same as RemoveComponent, destroy at the end so it's recreated first on Undo to make
// sure the GUID exists before undoing the list state
Undo.DestroyObjectImmediate(prevComponent);
// Force save / refresh
EditorUtility.SetDirty(asset);
AssetDatabase.SaveAssets();
}
internal void MoveComponent(int id, int offset)
{
// Move components
m_SerializedObject.Update();
m_ComponentsProperty.MoveArrayElement(id, id + offset);
m_SerializedObject.ApplyModifiedProperties();
// Move editors
var prev = m_Editors[id + offset];
m_Editors[id + offset] = m_Editors[id];
m_Editors[id] = prev;
}
// Copy/pasting is simply done by creating an in memory copy of the selected component and
// copying over the serialized data to another; it doesn't use nor affect the OS clipboard
static bool CanPaste(VolumeComponent targetComponent)
{
return s_ClipboardContent != null
&& s_ClipboardContent.GetType() == targetComponent.GetType();
}
static void CopySettings(VolumeComponent targetComponent)
{
if (s_ClipboardContent != null)
{
CoreUtils.Destroy(s_ClipboardContent);
s_ClipboardContent = null;
}
s_ClipboardContent = (VolumeComponent)ScriptableObject.CreateInstance(targetComponent.GetType());
EditorUtility.CopySerializedIfDifferent(targetComponent, s_ClipboardContent);
}
static void PasteSettings(VolumeComponent targetComponent)
{
Assert.IsNotNull(s_ClipboardContent);
Assert.AreEqual(s_ClipboardContent.GetType(), targetComponent.GetType());
Undo.RecordObject(targetComponent, "Paste Settings");
EditorUtility.CopySerializedIfDifferent(s_ClipboardContent, targetComponent);
}
}
}
| |
// 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.PetstoreV2NoSync
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// This is a sample server Petstore server. You can find out more about
/// Swagger at <a
/// href="http://swagger.io">http://swagger.io</a> or on
/// irc.freenode.net, #swagger. For this sample, you can use the api key
/// "special-key" to test the authorization filters
/// </summary>
public partial interface ISwaggerPetstoreV2 : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Pet>> AddPetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(IList<string> status, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use
/// tag1, tag2, tag3 for testing.
/// </remarks>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(IList<string> tags, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(long petId, Stream fileContent, string fileName = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10.
/// Other values will generated exceptions
/// </remarks>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything
/// above 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(IList<User> body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<string,LoginUserHeaders>> LoginUserWithHttpMessagesAsync(string username, string password, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> LogoutUserWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ServicePointManager.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net.Configuration;
using System.Net.Sockets;
using System.Net.Security;
using System.Security;
using System.Security.Permissions;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Win32;
// This turned to be a legacy type name that is simply forwarded to System.Security.Authentication.SslProtocols defined values.
#if !FEATURE_PAL
[Flags]
public enum SecurityProtocolType
{
Ssl3 = System.Security.Authentication.SslProtocols.Ssl3,
Tls = System.Security.Authentication.SslProtocols.Tls,
Tls11 = System.Security.Authentication.SslProtocols.Tls11,
Tls12 = System.Security.Authentication.SslProtocols.Tls12,
}
internal class CertPolicyValidationCallback
{
readonly ICertificatePolicy m_CertificatePolicy;
readonly ExecutionContext m_Context;
internal CertPolicyValidationCallback()
{
m_CertificatePolicy = new DefaultCertPolicy();
m_Context = null;
}
internal CertPolicyValidationCallback(ICertificatePolicy certificatePolicy)
{
m_CertificatePolicy = certificatePolicy;
m_Context = ExecutionContext.Capture();
}
internal ICertificatePolicy CertificatePolicy {
get { return m_CertificatePolicy;}
}
internal bool UsesDefault {
get { return m_Context == null;}
}
internal void Callback(object state)
{
CallbackContext context = (CallbackContext) state;
context.result = context.policyWrapper.CheckErrors(context.hostName,
context.certificate,
context.chain,
context.sslPolicyErrors);
}
internal bool Invoke(string hostName,
ServicePoint servicePoint,
X509Certificate certificate,
WebRequest request,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
PolicyWrapper policyWrapper = new PolicyWrapper(m_CertificatePolicy,
servicePoint,
(WebRequest) request);
if (m_Context == null)
{
return policyWrapper.CheckErrors(hostName,
certificate,
chain,
sslPolicyErrors);
}
else
{
ExecutionContext execContext = m_Context.CreateCopy();
CallbackContext callbackContext = new CallbackContext(policyWrapper,
hostName,
certificate,
chain,
sslPolicyErrors);
ExecutionContext.Run(execContext, Callback, callbackContext);
return callbackContext.result;
}
}
private class CallbackContext
{
internal CallbackContext(PolicyWrapper policyWrapper,
string hostName,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
this.policyWrapper = policyWrapper;
this.hostName = hostName;
this.certificate = certificate;
this.chain = chain;
this.sslPolicyErrors = sslPolicyErrors;
}
internal readonly PolicyWrapper policyWrapper;
internal readonly string hostName;
internal readonly X509Certificate certificate;
internal readonly X509Chain chain;
internal readonly SslPolicyErrors sslPolicyErrors;
internal bool result;
}
}
internal class ServerCertValidationCallback
{
readonly RemoteCertificateValidationCallback m_ValidationCallback;
readonly ExecutionContext m_Context;
internal ServerCertValidationCallback(RemoteCertificateValidationCallback validationCallback)
{
m_ValidationCallback = validationCallback;
m_Context = ExecutionContext.Capture();
}
internal RemoteCertificateValidationCallback ValidationCallback {
get { return m_ValidationCallback;}
}
internal void Callback(object state)
{
CallbackContext context = (CallbackContext) state;
context.result = m_ValidationCallback(context.request,
context.certificate,
context.chain,
context.sslPolicyErrors);
}
internal bool Invoke(object request,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (m_Context == null)
{
return m_ValidationCallback(request, certificate, chain, sslPolicyErrors);
}
else
{
ExecutionContext execContext = m_Context.CreateCopy();
CallbackContext callbackContext = new CallbackContext(request,
certificate,
chain,
sslPolicyErrors);
ExecutionContext.Run(execContext, Callback, callbackContext);
return callbackContext.result;
}
}
private class CallbackContext
{
internal readonly Object request;
internal readonly X509Certificate certificate;
internal readonly X509Chain chain;
internal readonly SslPolicyErrors sslPolicyErrors;
internal bool result;
internal CallbackContext(Object request,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
this.request = request;
this.certificate = certificate;
this.chain = chain;
this.sslPolicyErrors = sslPolicyErrors;
}
}
}
#endif // !FEATURE_PAL
//
// The ServicePointManager class hands out ServicePoints (may exist or be created
// as needed) and makes sure they are garbage collected when they expire.
// The ServicePointManager runs in its own thread so that it never
//
/// <devdoc>
/// <para>Manages the collection of <see cref='System.Net.ServicePoint'/> instances.</para>
/// </devdoc>
///
public class ServicePointManager {
/// <devdoc>
/// <para>
/// The number of non-persistent connections allowed on a <see cref='System.Net.ServicePoint'/>.
/// </para>
/// </devdoc>
public const int DefaultNonPersistentConnectionLimit = 4;
/// <devdoc>
/// <para>
/// The default number of persistent connections allowed on a <see cref='System.Net.ServicePoint'/>.
/// </para>
/// </devdoc>
public const int DefaultPersistentConnectionLimit = 2;
/// <devdoc>
/// <para>
/// The default number of persistent connections when running under ASP+.
/// </para>
/// </devdoc>
private const int DefaultAspPersistentConnectionLimit = 10;
internal static readonly string SpecialConnectGroupName = "/.NET/NetClasses/HttpWebRequest/CONNECT__Group$$/";
internal static readonly TimerThread.Callback s_IdleServicePointTimeoutDelegate = new TimerThread.Callback(IdleServicePointTimeoutCallback);
//
// data - only statics used
//
//
// s_ServicePointTable - Uri of ServicePoint is the hash key
// We provide our own comparer function that knows about Uris
//
//also used as a lock object
private static Hashtable s_ServicePointTable = new Hashtable(10);
// IIS6 has 120 sec for an idle connection timeout, we should have a little bit less.
private static volatile TimerThread.Queue s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(100 * 1000);
private static int s_MaxServicePoints = 0;
#if !FEATURE_PAL
private static volatile CertPolicyValidationCallback s_CertPolicyValidationCallback = new CertPolicyValidationCallback();
private static volatile ServerCertValidationCallback s_ServerCertValidationCallback = null;
private const string strongCryptoValueName = "SchUseStrongCrypto";
private const string secureProtocolAppSetting = "System.Net.ServicePointManager.SecurityProtocol";
private static object disableStrongCryptoLock = new object();
private static volatile bool disableStrongCryptoInitialized = false;
private static bool disableStrongCrypto = false;
private static SecurityProtocolType s_SecurityProtocolType = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
private const string reusePortValueName = "HWRPortReuseOnSocketBind";
private static object reusePortLock = new object();
private static volatile bool reusePortSettingsInitialized = false;
private static bool reusePort = false;
private static bool? reusePortSupported = null;
#endif // !FEATURE_PAL
private static volatile Hashtable s_ConfigTable = null;
private static volatile int s_ConnectionLimit = PersistentConnectionLimit;
internal static volatile bool s_UseTcpKeepAlive = false;
internal static volatile int s_TcpKeepAliveTime;
internal static volatile int s_TcpKeepAliveInterval;
//
// InternalConnectionLimit -
// set/get Connection Limit on demand, checking config beforehand
//
private static volatile bool s_UserChangedLimit;
private static int InternalConnectionLimit {
get {
if (s_ConfigTable == null) {
// init config
s_ConfigTable = ConfigTable;
}
return s_ConnectionLimit;
}
set {
if (s_ConfigTable == null) {
// init config
s_ConfigTable = ConfigTable;
}
s_UserChangedLimit = true;
s_ConnectionLimit = value;
}
}
//
// PersistentConnectionLimit -
// Determines the correct connection limit based on whether with running with ASP+
// The following order is followed generally for figuring what ConnectionLimit size to use
// 1. If ServicePoint.ConnectionLimit is set, then take that value
// 2. If ServicePoint has a specific config setting, then take that value
// 3. If ServicePoint.DefaultConnectionLimit is set, then take that value
// 4. If ServicePoint is localhost, then set to infinite (TO Should we change this value?)
// 5. If ServicePointManager has a default config connection limit setting, then take that value
// 6. If ServicePoint is running under ASP+, then set value to 10, else set it to 2
//
private static int PersistentConnectionLimit {
get {
#if !FEATURE_PAL
if (ComNetOS.IsAspNetServer) {
return DefaultAspPersistentConnectionLimit;
} else
#endif
{
return DefaultPersistentConnectionLimit;
}
}
}
/* Consider Removing
//
// InternalServicePointCount -
// Gets the active number of ServicePoints being used
//
internal static int InternalServicePointCount {
get {
return s_ServicePointTable.Count;
}
}
*/
[System.Diagnostics.Conditional("DEBUG")]
internal static void DebugMembers(int requestHash) {
try {
foreach (WeakReference servicePointReference in s_ServicePointTable) {
ServicePoint servicePoint;
if (servicePointReference != null && servicePointReference.IsAlive) {
servicePoint = (ServicePoint)servicePointReference.Target;
}
else {
servicePoint = null;
}
if (servicePoint!=null) {
servicePoint.DebugMembers(requestHash);
}
}
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
}
}
//
// ConfigTable -
// read ConfigTable from Config, or create
// a default on failure
//
private static Hashtable ConfigTable {
get {
if (s_ConfigTable == null) {
lock(s_ServicePointTable) {
if (s_ConfigTable == null) {
ConnectionManagementSectionInternal configSection
= ConnectionManagementSectionInternal.GetSection();
Hashtable configTable = null;
if (configSection != null)
{
configTable = configSection.ConnectionManagement;
}
if (configTable == null) {
configTable = new Hashtable();
}
// we piggy back loading the ConnectionLimit here
if (configTable.ContainsKey("*") ) {
int connectionLimit = (int) configTable["*"];
if ( connectionLimit < 1 ) {
connectionLimit = PersistentConnectionLimit;
}
s_ConnectionLimit = connectionLimit;
}
s_ConfigTable = configTable;
}
}
}
return s_ConfigTable;
}
}
internal static TimerThread.Callback IdleServicePointTimeoutDelegate
{
get
{
return s_IdleServicePointTimeoutDelegate;
}
}
private static void IdleServicePointTimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context)
{
ServicePoint servicePoint = (ServicePoint) context;
if (Logging.On) Logging.PrintInfo(Logging.Web, SR.GetString(SR.net_log_closed_idle,
"ServicePoint", servicePoint.GetHashCode()));
lock (s_ServicePointTable)
{
s_ServicePointTable.Remove(servicePoint.LookupString);
}
servicePoint.ReleaseAllConnectionGroups();
}
//
// constructors
//
private ServicePointManager() {
}
#if !FEATURE_PAL
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
public static SecurityProtocolType SecurityProtocol {
get {
EnsureStrongCryptoSettingsInitialized();
return s_SecurityProtocolType;
}
set {
EnsureStrongCryptoSettingsInitialized();
ValidateSecurityProtocol(value);
s_SecurityProtocolType = value;
}
}
private static void ValidateSecurityProtocol(SecurityProtocolType value)
{
// Do not allow Ssl2 (and others) as explicit SSL version request
SecurityProtocolType allowed = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls
| SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
if ((value & ~allowed) != 0)
{
throw new NotSupportedException(SR.GetString(SR.net_securityprotocolnotsupported));
}
}
#endif // !FEATURE_PAL
//
// accessors
//
/// <devdoc>
/// <para>Gets or sets the maximum number of <see cref='System.Net.ServicePoint'/> instances that should be maintained at any
/// time.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
public static int MaxServicePoints {
get {
return s_MaxServicePoints;
}
set {
ExceptionHelper.WebPermissionUnrestricted.Demand();
if (!ValidationHelper.ValidateRange(value, 0, Int32.MaxValue)) {
throw new ArgumentOutOfRangeException("value");
}
s_MaxServicePoints = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static int DefaultConnectionLimit {
get {
return InternalConnectionLimit;
}
set {
ExceptionHelper.WebPermissionUnrestricted.Demand();
if (value > 0) {
InternalConnectionLimit = value;
}
else {
throw new ArgumentOutOfRangeException("value", SR.GetString(SR.net_toosmall));
}
}
}
/// <devdoc>
/// <para>Gets or sets the maximum idle time in seconds of a <see cref='System.Net.ServicePoint'/>.</para>
/// </devdoc>
public static int MaxServicePointIdleTime {
get {
return s_ServicePointIdlingQueue.Duration;
}
set {
ExceptionHelper.WebPermissionUnrestricted.Demand();
if ( !ValidationHelper.ValidateRange(value, Timeout.Infinite, Int32.MaxValue)) {
throw new ArgumentOutOfRangeException("value");
}
if (s_ServicePointIdlingQueue.Duration != value)
{
s_ServicePointIdlingQueue = TimerThread.GetOrCreateQueue(value);
}
}
}
/// <devdoc>
/// <para>
/// Gets or sets indication whether use of the Nagling algorithm is desired.
/// Changing this value does not affect existing <see cref='System.Net.ServicePoint'/> instances but only to new ones that are created from that moment on.
/// </para>
/// </devdoc>
public static bool UseNagleAlgorithm {
get {
return SettingsSectionInternal.Section.UseNagleAlgorithm;
}
set {
SettingsSectionInternal.Section.UseNagleAlgorithm = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets indication whether 100-continue behaviour is desired.
/// Changing this value does not affect existing <see cref='System.Net.ServicePoint'/> instances but only to new ones that are created from that moment on.
/// </para>
/// </devdoc>
public static bool Expect100Continue {
get {
return SettingsSectionInternal.Section.Expect100Continue;
}
set {
SettingsSectionInternal.Section.Expect100Continue = value;
}
}
/// <devdoc>
/// <para>
/// Enables the use of DNS round robin access, meaning a different IP
/// address may be used on each connection, when more than one IP is availble
/// </para>
/// </devdoc>
public static bool EnableDnsRoundRobin {
get {
return SettingsSectionInternal.Section.EnableDnsRoundRobin;
}
set {
SettingsSectionInternal.Section.EnableDnsRoundRobin = value;
}
}
/// <devdoc>
/// <para>
/// Causes us to go back and reresolve addresses through DNS, even when
/// there were no recorded failures. -1 is infinite. Time should be in ms
/// </para>
/// </devdoc>
public static int DnsRefreshTimeout {
get {
return SettingsSectionInternal.Section.DnsRefreshTimeout;
}
set {
if(value < -1){
SettingsSectionInternal.Section.DnsRefreshTimeout = -1;
}
else{
SettingsSectionInternal.Section.DnsRefreshTimeout = value;
}
}
}
#if !FEATURE_PAL
/// <devdoc>
/// <para>
/// Defines the s_Policy for how to deal with server certificates.
/// </para>
/// </devdoc>
[Obsolete("CertificatePolicy is obsoleted for this type, please use ServerCertificateValidationCallback instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static ICertificatePolicy CertificatePolicy {
get {
return GetLegacyCertificatePolicy();
}
set {
//Prevent for an applet to override default Certificate Policy
ExceptionHelper.UnmanagedPermission.Demand();
s_CertPolicyValidationCallback = new CertPolicyValidationCallback(value);
}
}
internal static ICertificatePolicy GetLegacyCertificatePolicy(){
if (s_CertPolicyValidationCallback == null)
return null;
else
return s_CertPolicyValidationCallback.CertificatePolicy;
}
internal static CertPolicyValidationCallback CertPolicyValidationCallback {
get {
return s_CertPolicyValidationCallback;
}
}
public static RemoteCertificateValidationCallback ServerCertificateValidationCallback {
get {
if (s_ServerCertValidationCallback == null)
return null;
else
return s_ServerCertValidationCallback.ValidationCallback;
}
set {
// Prevent an applet from overriding the default Certificate Policy
ExceptionHelper.InfrastructurePermission.Demand();
if (value == null)
{
s_ServerCertValidationCallback = null;
}
else
{
s_ServerCertValidationCallback = new ServerCertValidationCallback(value);
}
}
}
internal static ServerCertValidationCallback ServerCertValidationCallback {
get {
return s_ServerCertValidationCallback;
}
}
internal static bool DisableStrongCrypto {
get {
EnsureStrongCryptoSettingsInitialized();
return (bool)disableStrongCrypto;
}
}
private static void EnsureStrongCryptoSettingsInitialized() {
if (disableStrongCryptoInitialized) {
return;
}
lock (disableStrongCryptoLock) {
if (disableStrongCryptoInitialized) {
return;
}
try {
bool disableStrongCryptoInternal = false;
int schUseStrongCryptoKeyValue = 0;
if (LocalAppContextSwitches.DontEnableSchUseStrongCrypto)
{
//.Net 4.5.2 and below will default to false unless the registry key is specifically set to 1.
schUseStrongCryptoKeyValue =
RegistryConfiguration.GlobalConfigReadInt(strongCryptoValueName, 0);
disableStrongCryptoInternal = schUseStrongCryptoKeyValue != 1;
}
else
{
// .Net 4.6 and above will default to true unless the registry key is specifically set to 0.
schUseStrongCryptoKeyValue =
RegistryConfiguration.GlobalConfigReadInt(strongCryptoValueName, 1);
disableStrongCryptoInternal = schUseStrongCryptoKeyValue == 0;
}
if (disableStrongCryptoInternal) {
// Revert the SecurityProtocol selection to the legacy combination.
s_SecurityProtocolType = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
}
else {
s_SecurityProtocolType =
SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
string appSetting = RegistryConfiguration.AppConfigReadString(secureProtocolAppSetting, null);
SecurityProtocolType value;
try {
value = (SecurityProtocolType)Enum.Parse(typeof(SecurityProtocolType), appSetting);
ValidateSecurityProtocol(value);
s_SecurityProtocolType = value;
}
// Ignore all potential exceptions caused by Enum.Parse.
catch (ArgumentNullException) { }
catch (ArgumentException) { }
catch (NotSupportedException) { }
catch (OverflowException) { }
}
disableStrongCrypto = disableStrongCryptoInternal;
disableStrongCryptoInitialized = true;
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
}
}
}
public static bool ReusePort {
get {
EnsureReusePortSettingsInitialized();
return reusePort;
}
set {
EnsureReusePortSettingsInitialized();
reusePort = value;
}
}
internal static bool? ReusePortSupported {
get {
return reusePortSupported;
}
set {
reusePortSupported = value;
}
}
private static void EnsureReusePortSettingsInitialized() {
if (reusePortSettingsInitialized) {
return;
}
lock (reusePortLock) {
if (reusePortSettingsInitialized) {
return;
}
int reusePortKeyValue = 0;
try {
reusePortKeyValue = RegistryConfiguration.GlobalConfigReadInt(reusePortValueName, 0);
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
}
bool reusePortInternal = false;
if (reusePortKeyValue == 1) {
if (Logging.On) {
Logging.PrintInfo(Logging.Web, typeof(ServicePointManager), SR.GetString(SR.net_log_set_socketoption_reuseport_default_on));
}
reusePortInternal = true;
}
reusePort = reusePortInternal;
reusePortSettingsInitialized = true;
}
}
#endif // !FEATURE_PAL
public static bool CheckCertificateRevocationList {
get {
return SettingsSectionInternal.Section.CheckCertificateRevocationList;
}
set {
//Prevent an applet to override default certificate checking
ExceptionHelper.UnmanagedPermission.Demand();
SettingsSectionInternal.Section.CheckCertificateRevocationList = value;
}
}
public static EncryptionPolicy EncryptionPolicy {
get {
return SettingsSectionInternal.Section.EncryptionPolicy;
}
}
internal static bool CheckCertificateName {
get {
return SettingsSectionInternal.Section.CheckCertificateName;
}
}
//
// class methods
//
//
// MakeQueryString - Just a short macro to handle creating the query
// string that we search for host ports in the host list
//
internal static string MakeQueryString(Uri address) {
if (address.IsDefaultPort)
return address.Scheme + "://" + address.DnsSafeHost;
else
return address.Scheme + "://" + address.DnsSafeHost + ":" + address.Port.ToString();
}
internal static string MakeQueryString(Uri address1, bool isProxy) {
if (isProxy) {
return MakeQueryString(address1) + "://proxy";
}
else {
return MakeQueryString(address1);
}
}
//
// FindServicePoint - Query using an Uri string for a given ServerPoint Object
//
/// <devdoc>
/// <para>Finds an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the
/// specified Uniform Resource Identifier.</para>
/// </devdoc>
public static ServicePoint FindServicePoint(Uri address) {
return FindServicePoint(address, null);
}
/// <devdoc>
/// <para>Finds an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the
/// specified Uniform Resource Identifier.</para>
/// </devdoc>
public static ServicePoint FindServicePoint(string uriString, IWebProxy proxy) {
Uri uri = new Uri(uriString);
return FindServicePoint(uri, proxy);
}
//
// FindServicePoint - Query using an Uri for a given server point
//
/// <devdoc>
/// <para>Findes an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the specified <see cref='System.Uri'/>
/// instance.</para>
/// </devdoc>
public static ServicePoint FindServicePoint(Uri address, IWebProxy proxy) {
ProxyChain chain;
HttpAbortDelegate abortDelegate = null;
int abortState = 0;
return FindServicePoint(address, proxy, out chain, ref abortDelegate, ref abortState);
}
// If abortState becomes non-zero, the attempt to find a service point has been aborted.
internal static ServicePoint FindServicePoint(Uri address, IWebProxy proxy, out ProxyChain chain, ref HttpAbortDelegate abortDelegate, ref int abortState)
{
if (address==null) {
throw new ArgumentNullException("address");
}
GlobalLog.Enter("ServicePointManager::FindServicePoint() address:" + address.ToString());
bool isProxyServicePoint = false;
chain = null;
//
// find proxy info, and then switch on proxy
//
Uri proxyAddress = null;
if (proxy!=null && !address.IsLoopback) {
IAutoWebProxy autoProxy = proxy as IAutoWebProxy;
if (autoProxy != null)
{
chain = autoProxy.GetProxies(address);
// Set up our ability to abort this MoveNext call. Note that the current implementations of ProxyChain will only
// take time on the first call, so this is the only place we do this. If a new ProxyChain takes time in later
// calls, this logic should be copied to other places MoveNext is called.
GlobalLog.Assert(abortDelegate == null, "ServicePointManager::FindServicePoint()|AbortDelegate already set.");
abortDelegate = chain.HttpAbortDelegate;
try
{
Thread.MemoryBarrier();
if (abortState != 0)
{
Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
GlobalLog.LeaveException("ServicePointManager::FindServicePoint() Request aborted before proxy lookup.", exception);
throw exception;
}
if (!chain.Enumerator.MoveNext())
{
GlobalLog.Assert("ServicePointManager::FindServicePoint()|GetProxies() returned zero proxies.");
/*
Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestProhibitedByProxy), WebExceptionStatus.RequestProhibitedByProxy);
GlobalLog.LeaveException("ServicePointManager::FindServicePoint() Proxy prevented request.", exception);
throw exception;
*/
}
proxyAddress = chain.Enumerator.Current;
}
finally
{
abortDelegate = null;
}
}
else if (!proxy.IsBypassed(address))
{
// use proxy support
// rework address
proxyAddress = proxy.GetProxy(address);
}
// null means DIRECT
if (proxyAddress!=null) {
address = proxyAddress;
isProxyServicePoint = true;
}
}
ServicePoint servicePoint = FindServicePointHelper(address, isProxyServicePoint);
GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint));
return servicePoint;
}
// Returns null if we get to the end of the chain.
internal static ServicePoint FindServicePoint(ProxyChain chain)
{
GlobalLog.Print("ServicePointManager::FindServicePoint() Calling chained version.");
if (!chain.Enumerator.MoveNext())
{
return null;
}
Uri proxyAddress = chain.Enumerator.Current;
return FindServicePointHelper(proxyAddress == null ? chain.Destination : proxyAddress, proxyAddress != null);
}
private static ServicePoint FindServicePointHelper(Uri address, bool isProxyServicePoint)
{
GlobalLog.Enter("ServicePointManager::FindServicePointHelper() address:" + address.ToString());
if (isProxyServicePoint)
{
if (address.Scheme != Uri.UriSchemeHttp)
{
// <
Exception exception = new NotSupportedException(SR.GetString(SR.net_proxyschemenotsupported, address.Scheme));
GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() proxy has unsupported scheme:" + address.Scheme.ToString(), exception);
throw exception;
}
}
//
// Search for the correct proxy host,
// then match its acutal host by using ConnectionGroups
// which are located on the actual ServicePoint.
//
string tempEntry = MakeQueryString(address, isProxyServicePoint);
// lookup service point in the table
ServicePoint servicePoint = null;
GlobalLog.Print("ServicePointManager::FindServicePointHelper() locking and looking up tempEntry:[" + tempEntry.ToString() + "]");
lock (s_ServicePointTable) {
// once we grab the lock, check if it wasn't already added
WeakReference servicePointReference = s_ServicePointTable[tempEntry] as WeakReference;
GlobalLog.Print("ServicePointManager::FindServicePointHelper() lookup returned WeakReference#" + ValidationHelper.HashString(servicePointReference));
if ( servicePointReference != null ) {
servicePoint = (ServicePoint)servicePointReference.Target;
GlobalLog.Print("ServicePointManager::FindServicePointHelper() successful lookup returned ServicePoint#" + ValidationHelper.HashString(servicePoint));
}
if (servicePoint==null) {
// lookup failure or timeout, we need to create a new ServicePoint
if (s_MaxServicePoints<=0 || s_ServicePointTable.Count<s_MaxServicePoints) {
// Determine Connection Limit
int connectionLimit = InternalConnectionLimit;
string schemeHostPort = MakeQueryString(address);
bool userDefined = s_UserChangedLimit;
if (ConfigTable.ContainsKey(schemeHostPort) ) {
connectionLimit = (int) ConfigTable[schemeHostPort];
userDefined = true;
}
servicePoint = new ServicePoint(address, s_ServicePointIdlingQueue, connectionLimit, tempEntry, userDefined, isProxyServicePoint);
GlobalLog.Print("ServicePointManager::FindServicePointHelper() created ServicePoint#" + ValidationHelper.HashString(servicePoint));
servicePointReference = new WeakReference(servicePoint);
s_ServicePointTable[tempEntry] = servicePointReference;
GlobalLog.Print("ServicePointManager::FindServicePointHelper() adding entry WeakReference#" + ValidationHelper.HashString(servicePointReference) + " key:[" + tempEntry + "]");
}
else {
Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints));
GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception);
throw exception;
}
}
}
GlobalLog.Leave("ServicePointManager::FindServicePointHelper() servicePoint#" + ValidationHelper.HashString(servicePoint));
return servicePoint;
}
//
// FindServicePoint - Query using an Uri for a given server point
//
/// <devdoc>
/// <para>Findes an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the specified <see cref='System.Uri'/>
/// instance.</para>
/// </devdoc>
internal static ServicePoint FindServicePoint(string host, int port) {
if (host==null) {
throw new ArgumentNullException("address");
}
GlobalLog.Enter("ServicePointManager::FindServicePoint() host:" + host.ToString());
string tempEntry = null;
bool isProxyServicePoint = false;
//
// Search for the correct proxy host,
// then match its acutal host by using ConnectionGroups
// which are located on the actual ServicePoint.
//
tempEntry = "ByHost:"+host+":"+port.ToString(CultureInfo.InvariantCulture);
// lookup service point in the table
ServicePoint servicePoint = null;
GlobalLog.Print("ServicePointManager::FindServicePoint() locking and looking up tempEntry:[" + tempEntry.ToString() + "]");
lock (s_ServicePointTable) {
// once we grab the lock, check if it wasn't already added
WeakReference servicePointReference = s_ServicePointTable[tempEntry] as WeakReference;
GlobalLog.Print("ServicePointManager::FindServicePoint() lookup returned WeakReference#" + ValidationHelper.HashString(servicePointReference));
if ( servicePointReference != null ) {
servicePoint = (ServicePoint)servicePointReference.Target;
GlobalLog.Print("ServicePointManager::FindServicePoint() successfull lookup returned ServicePoint#" + ValidationHelper.HashString(servicePoint));
}
if (servicePoint==null) {
// lookup failure or timeout, we need to create a new ServicePoint
if (s_MaxServicePoints<=0 || s_ServicePointTable.Count<s_MaxServicePoints) {
// Determine Connection Limit
int connectionLimit = InternalConnectionLimit;
bool userDefined = s_UserChangedLimit;
string schemeHostPort =host+":"+port.ToString(CultureInfo.InvariantCulture);
if (ConfigTable.ContainsKey(schemeHostPort) ) {
connectionLimit = (int) ConfigTable[schemeHostPort];
userDefined = true;
}
servicePoint = new ServicePoint(host, port, s_ServicePointIdlingQueue, connectionLimit, tempEntry, userDefined, isProxyServicePoint);
GlobalLog.Print("ServicePointManager::FindServicePoint() created ServicePoint#" + ValidationHelper.HashString(servicePoint));
servicePointReference = new WeakReference(servicePoint);
s_ServicePointTable[tempEntry] = servicePointReference;
GlobalLog.Print("ServicePointManager::FindServicePoint() adding entry WeakReference#" + ValidationHelper.HashString(servicePointReference) + " key:[" + tempEntry + "]");
}
else {
Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints));
GlobalLog.LeaveException("ServicePointManager::FindServicePoint() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception);
throw exception;
}
}
}
GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint));
return servicePoint;
}
[FriendAccessAllowed]
internal static void CloseConnectionGroups(string connectionGroupName) {
// This method iterates through all service points and closes connection groups with the provided name.
ServicePoint servicePoint = null;
lock (s_ServicePointTable) {
foreach (DictionaryEntry item in s_ServicePointTable) {
WeakReference servicePointReference = item.Value as WeakReference;
if (servicePointReference != null) {
servicePoint = (ServicePoint)servicePointReference.Target;
if (servicePoint != null) {
// We found a service point. Ask the service point to close all internal connection groups
// with name 'connectionGroupName'.
servicePoint.CloseConnectionGroupInternal(connectionGroupName);
}
}
}
}
}
//
// SetTcpKeepAlive
//
// Enable/Disable the use of TCP keepalive option on ServicePoint
// connections. This method does not affect existing ServicePoints.
// When a ServicePoint is constructed it will inherit the current
// settings.
//
// Parameters:
//
// enabled - if true enables the use of the TCP keepalive option
// for ServicePoint connections.
//
// keepAliveTime - specifies the timeout, in milliseconds, with no
// activity until the first keep-alive packet is sent. Ignored if
// enabled parameter is false.
//
// keepAliveInterval - specifies the interval, in milliseconds, between
// when successive keep-alive packets are sent if no acknowledgement is
// received. Ignored if enabled parameter is false.
//
public static void SetTcpKeepAlive(
bool enabled,
int keepAliveTime,
int keepAliveInterval) {
GlobalLog.Enter(
"ServicePointManager::SetTcpKeepAlive()" +
" enabled: " + enabled.ToString() +
" keepAliveTime: " + keepAliveTime.ToString() +
" keepAliveInterval: " + keepAliveInterval.ToString()
);
if (enabled) {
s_UseTcpKeepAlive = true;
if (keepAliveTime <= 0) {
throw new ArgumentOutOfRangeException("keepAliveTime");
}
if (keepAliveInterval <= 0) {
throw new ArgumentOutOfRangeException("keepAliveInterval");
}
s_TcpKeepAliveTime = keepAliveTime;
s_TcpKeepAliveInterval = keepAliveInterval;
} else {
s_UseTcpKeepAlive = false;
s_TcpKeepAliveTime = 0;
s_TcpKeepAliveInterval =0;
}
GlobalLog.Leave("ServicePointManager::SetTcpKeepAlive()");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Client
{
using System;
using System.Collections.Generic;
#if !WINDOWS_UWP && !PCL
using System.Security.Permissions;
#endif
using System.Threading;
// A simple synchronized pool would simply lock a stack and push/pop on return/take.
//
// This implementation tries to reduce locking by exploiting the case where an item
// is taken and returned by the same thread, which turns out to be common in our
// scenarios.
//
// Initially, all the quota is allocated to a global (non-thread-specific) pool,
// which takes locks. As different threads take and return values, we record their IDs,
// and if we detect that a thread is taking and returning "enough" on the same thread,
// then we decide to "promote" the thread. When a thread is promoted, we decrease the
// quota of the global pool by one, and allocate a thread-specific entry for the thread
// to store it's value. Once this entry is allocated, the thread can take and return
// it's value from that entry without taking any locks. Not only does this avoid
// locks, but it affinitizes pooled items to a particular thread.
//
// There are a couple of additional things worth noting:
//
// It is possible for a thread that we have reserved an entry for to exit. This means
// we will still have a entry allocated for it, but the pooled item stored there
// will never be used. After a while, we could end up with a number of these, and
// as a result we would begin to exhaust the quota of the overall pool. To mitigate this
// case, we throw away the entire per-thread pool, and return all the quota back to
// the global pool if we are unable to promote a thread (due to lack of space). Then
// the set of active threads will be re-promoted as they take and return items.
//
// You may notice that the code does not immediately promote a thread, and does not
// immediately throw away the entire per-thread pool when it is unable to promote a
// thread. Instead, it uses counters (based on the number of calls to the pool)
// and a threshold to figure out when to do these operations. In the case where the
// pool to misconfigured to have too few items for the workload, this avoids constant
// promoting and rebuilding of the per thread entries.
//
// You may also notice that we do not use interlocked methods when adjusting statistics.
// Since the statistics are a heuristic as to how often something is happening, they
// do not need to be perfect.
//
[Fx.Tag.SynchronizationObject(Blocking = false)]
class SynchronizedPool<T> where T : class
{
const int maxPendingEntries = 128;
const int maxPromotionFailures = 64;
const int maxReturnsBeforePromotion = 64;
const int maxThreadItemsPerProcessor = 16;
Entry[] entries;
GlobalPool globalPool;
int maxCount;
PendingEntry[] pending;
int promotionFailures;
public SynchronizedPool(int maxCount)
{
int threadCount = maxCount;
int maxThreadCount = maxThreadItemsPerProcessor + SynchronizedPoolHelper.ProcessorCount;
if (threadCount > maxThreadCount)
{
threadCount = maxThreadCount;
}
this.maxCount = maxCount;
this.entries = new Entry[threadCount];
this.pending = new PendingEntry[4];
this.globalPool = new GlobalPool(maxCount);
}
object ThisLock
{
get
{
return this;
}
}
public void Clear()
{
Entry[] entriesReference = this.entries;
for (int i = 0; i < entriesReference.Length; i++)
{
entriesReference[i].value = null;
}
globalPool.Clear();
}
void HandlePromotionFailure(int thisThreadID)
{
int newPromotionFailures = this.promotionFailures + 1;
if (newPromotionFailures >= maxPromotionFailures)
{
lock (ThisLock)
{
this.entries = new Entry[this.entries.Length];
globalPool.MaxCount = maxCount;
}
PromoteThread(thisThreadID);
}
else
{
this.promotionFailures = newPromotionFailures;
}
}
bool PromoteThread(int thisThreadID)
{
lock (ThisLock)
{
for (int i = 0; i < this.entries.Length; i++)
{
int threadID = this.entries[i].threadID;
if (threadID == thisThreadID)
{
return true;
}
else if (threadID == 0)
{
globalPool.DecrementMaxCount();
this.entries[i].threadID = thisThreadID;
return true;
}
}
}
return false;
}
void RecordReturnToGlobalPool(int thisThreadID)
{
PendingEntry[] localPending = this.pending;
for (int i = 0; i < localPending.Length; i++)
{
int threadID = localPending[i].threadID;
if (threadID == thisThreadID)
{
int newReturnCount = localPending[i].returnCount + 1;
if (newReturnCount >= maxReturnsBeforePromotion)
{
localPending[i].returnCount = 0;
if (!PromoteThread(thisThreadID))
{
HandlePromotionFailure(thisThreadID);
}
}
else
{
localPending[i].returnCount = newReturnCount;
}
break;
}
else if (threadID == 0)
{
break;
}
}
}
void RecordTakeFromGlobalPool(int thisThreadID)
{
PendingEntry[] localPending = this.pending;
for (int i = 0; i < localPending.Length; i++)
{
int threadID = localPending[i].threadID;
if (threadID == thisThreadID)
{
return;
}
else if (threadID == 0)
{
lock (localPending)
{
if (localPending[i].threadID == 0)
{
localPending[i].threadID = thisThreadID;
return;
}
}
}
}
if (localPending.Length >= maxPendingEntries)
{
this.pending = new PendingEntry[localPending.Length];
}
else
{
PendingEntry[] newPending = new PendingEntry[localPending.Length * 2];
Array.Copy(localPending, newPending, localPending.Length);
this.pending = newPending;
}
}
public bool Return(T value)
{
#if WINDOWS_UWP || PCL
throw new NotImplementedException();
#else
int thisThreadID = Thread.CurrentThread.ManagedThreadId;
if (thisThreadID == 0)
{
return false;
}
if (ReturnToPerThreadPool(thisThreadID, value))
{
return true;
}
return ReturnToGlobalPool(thisThreadID, value);
#endif
}
bool ReturnToPerThreadPool(int thisThreadID, T value)
{
Entry[] entriesReference = this.entries;
for (int i = 0; i < entriesReference.Length; i++)
{
int threadID = entriesReference[i].threadID;
if (threadID == thisThreadID)
{
if (entriesReference[i].value == null)
{
entriesReference[i].value = value;
return true;
}
else
{
return false;
}
}
else if (threadID == 0)
{
break;
}
}
return false;
}
bool ReturnToGlobalPool(int thisThreadID, T value)
{
RecordReturnToGlobalPool(thisThreadID);
return globalPool.Return(value);
}
public T Take()
{
#if WINDOWS_UWP || PCL
throw new NotImplementedException();
#else
int thisThreadID = Thread.CurrentThread.ManagedThreadId;
if (thisThreadID == 0)
{
return null;
}
T value = TakeFromPerThreadPool(thisThreadID);
if (value != null)
{
return value;
}
return TakeFromGlobalPool(thisThreadID);
#endif
}
T TakeFromPerThreadPool(int thisThreadID)
{
Entry[] entriesReference = this.entries;
for (int i = 0; i < entriesReference.Length; i++)
{
int threadID = entriesReference[i].threadID;
if (threadID == thisThreadID)
{
T value = entriesReference[i].value;
if (value != null)
{
entriesReference[i].value = null;
return value;
}
else
{
return null;
}
}
else if (threadID == 0)
{
break;
}
}
return null;
}
T TakeFromGlobalPool(int thisThreadID)
{
RecordTakeFromGlobalPool(thisThreadID);
return globalPool.Take();
}
struct Entry
{
public int threadID;
public T value;
}
struct PendingEntry
{
public int returnCount;
public int threadID;
}
static class SynchronizedPoolHelper
{
public static readonly int ProcessorCount = GetProcessorCount();
[Fx.Tag.SecurityNote(Critical = "Asserts in order to get the processor count from the environment", Safe = "This data isn't actually protected so it's ok to leak")]
#if !WINDOWS_UWP && !PCL
[EnvironmentPermission(SecurityAction.Assert, Read = "NUMBER_OF_PROCESSORS")]
#endif
static int GetProcessorCount()
{
return Environment.ProcessorCount;
}
}
[Fx.Tag.SynchronizationObject(Blocking = false)]
class GlobalPool
{
Stack<T> items;
int maxCount;
public GlobalPool(int maxCount)
{
this.items = new Stack<T>();
this.maxCount = maxCount;
}
public int MaxCount
{
get
{
return maxCount;
}
set
{
lock (ThisLock)
{
while (items.Count > value)
{
items.Pop();
}
maxCount = value;
}
}
}
object ThisLock
{
get
{
return this;
}
}
public void DecrementMaxCount()
{
lock (ThisLock)
{
if (items.Count == maxCount)
{
items.Pop();
}
maxCount--;
}
}
public T Take()
{
if (this.items.Count > 0)
{
lock (ThisLock)
{
if (this.items.Count > 0)
{
return this.items.Pop();
}
}
}
return null;
}
public bool Return(T value)
{
if (this.items.Count < this.MaxCount)
{
lock (ThisLock)
{
if (this.items.Count < this.MaxCount)
{
this.items.Push(value);
return true;
}
}
}
return false;
}
public void Clear()
{
lock (ThisLock)
{
this.items.Clear();
}
}
}
}
}
| |
using System;
namespace OpenRiaServices.DomainServices.Hosting.OData
{
#region Namespaces
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Xml;
#endregion
/// <summary>
/// Error handler for domain data service exceptions. Uses the data service format
/// for serializing exceptions. Currently only uses the application/xml mime format.
/// </summary>
internal class DomainDataServiceErrorHandler : IErrorHandler
{
/// <summary>
/// Enables error-related processing and returns a value that indicates whether the dispatcher
/// aborts the session and the instance context in certain cases.
/// </summary>
/// <param name="error">The exception thrown during processing.</param>
/// <returns>true if Windows Communication Foundation (WCF) should not abort the session (if there is one) and instance context
/// if the instance context is not Single; otherwise, false. The default is false.</returns>
public bool HandleError(Exception error)
{
return error is DomainDataServiceException;
}
/// <summary>
/// Enables the creation of a custom FaultException that is returned from an exception in the course of a service method.
/// </summary>
/// <param name="error">The Exception object thrown in the course of the service operation.</param>
/// <param name="version">The SOAP version of the message.</param>
/// <param name="fault">The Message object that is returned to the client, or service, in the duplex case.</param>
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
Debug.Assert(error != null, "error != null");
Debug.Assert(version != null, "version != null");
HttpStatusCode statusCode;
Action<Stream> exceptionWriter = DomainDataServiceErrorHandler.HandleException(error, out statusCode);
Message message = null;
try
{
message = Message.CreateMessage(MessageVersion.None, string.Empty, new DelegateBodyWriter(exceptionWriter));
message.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Raw));
HttpResponseMessageProperty response = new HttpResponseMessageProperty();
response.Headers[HttpResponseHeader.ContentType] = ServiceUtils.MimeApplicationXml;
response.Headers[ServiceUtils.HttpDataServiceVersion] = ServiceUtils.DataServiceVersion1Dot0 + ";";
response.StatusCode = statusCode;
if (statusCode == HttpStatusCode.MethodNotAllowed)
{
DomainDataServiceException e = (error as DomainDataServiceException);
if (e != null)
{
response.Headers[HttpResponseHeader.Allow] = e.ResponseAllowHeader;
}
}
message.Properties.Add(HttpResponseMessageProperty.Name, response);
fault = message;
message = null;
}
finally
{
if (message != null)
{
((IDisposable)message).Dispose();
}
}
}
/// <summary>
/// Creates a delegate used for serializing the exception to outgoing stream.
/// </summary>
/// <param name="exception">Exception to serialize.</param>
/// <param name="statusCode">Http status code from <paramref name="exception"/>.</param>
/// <returns>Delegate that serializes the <paramref name="exception"/>.</returns>
private static Action<Stream> HandleException(Exception exception, out HttpStatusCode statusCode)
{
Debug.Assert(TypeUtils.IsCatchableExceptionType(exception), "WebUtil.IsCatchableExceptionType(exception)");
Debug.Assert(exception != null, "exception != null");
DomainDataServiceException e = exception as DomainDataServiceException;
statusCode = e != null ? (HttpStatusCode)e.StatusCode : HttpStatusCode.InternalServerError;
return new ErrorSerializer(exception).SerializeXmlErrorToStream;
}
/// <summary>Use this class to handle writing body contents using a callback.</summary>
private class DelegateBodyWriter : BodyWriter
{
#region Fields.
/// <summary>Writer action callback.</summary>
private readonly Action<Stream> writerAction;
#endregion Fields.
/// <summary>Initializes a new <see cref="DelegateBodyWriter"/> instance.</summary>
/// <param name="writer">Callback for writing.</param>
internal DelegateBodyWriter(Action<Stream> writer)
: base(false)
{
Debug.Assert(writer != null, "writer != null");
this.writerAction = writer;
}
/// <summary>Called when the message body is written to an XML file.</summary>
/// <param name="writer">
/// An <see cref="XmlDictionaryWriter"/> that is used to write this
/// message body to an XML file.
/// </param>
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
Debug.Assert(writer != null, "writer != null");
try
{
writer.WriteStartElement(ServiceUtils.WcfBinaryElementName);
using (XmlWriterStream stream = new XmlWriterStream(writer))
{
this.writerAction(stream);
}
writer.WriteEndElement();
}
finally
{
// We will always abort the channel in case a domain service exception occurs.
var ctx = System.ServiceModel.OperationContext.Current;
if (ctx != null)
{
ctx.Channel.Abort();
}
}
}
/// <summary>Use this class to write to an <see cref="XmlDictionaryWriter"/>.</summary>
private class XmlWriterStream : Stream
{
/// <summary>Target writer.</summary>
private XmlDictionaryWriter innerWriter;
/// <summary>Initializes a new <see cref="XmlWriterStream"/> instance.</summary>
/// <param name="xmlWriter">Target writer.</param>
internal XmlWriterStream(XmlDictionaryWriter xmlWriter)
{
Debug.Assert(xmlWriter != null, "xmlWriter != null");
this.innerWriter = xmlWriter;
}
/// <summary>Gets a value indicating whether the current stream supports reading.</summary>
public override bool CanRead
{
get { return false; }
}
/// <summary>Gets a value indicating whether the current stream supports seeking.</summary>
public override bool CanSeek
{
get { return false; }
}
/// <summary>Gets a value indicating whether the current stream supports writing.</summary>
public override bool CanWrite
{
get { return true; }
}
/// <summary>Gets the length in bytes of the stream.</summary>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>Gets or sets the position within the current stream.</summary>
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered
/// data to be written to the underlying device.
/// </summary>
public override void Flush()
{
this.innerWriter.Flush();
}
/// <summary>
/// Reads a sequence of bytes from the current stream and
/// advances the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains
/// the specified byte array with the values between <paramref name="offset"/>
/// and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced
/// by the bytes read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in <paramref name="buffer"/> at which to
/// begin storing the data read from the current stream.
/// </param>
/// <param name="count">
/// The maximum number of bytes to be read from the current stream.
/// </param>
/// <returns>The total number of bytes read into the buffer.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
/// <summary>Sets the position within the current stream.</summary>
/// <param name="offset">
/// A byte offset relative to the <paramref name="origin"/> parameter.
/// </param>
/// <param name="origin">
/// A value of type <see cref="SeekOrigin"/> indicating the reference
/// point used to obtain the new position.
/// </param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>Sets the length of the current stream.</summary>
/// <param name="value">New value for length.</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Writes a sequence of bytes to the current stream and advances
/// the current position within this stream by the number of
/// bytes written.
/// </summary>
/// <param name="buffer">
/// An array of bytes. This method copies <paramref name="count"/>
/// bytes from <paramref name="buffer"/> to the current stream.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in buffer at which to begin copying
/// bytes to the current stream.
/// </param>
/// <param name="count">
/// The number of bytes to be written to the current stream.
/// </param>
public override void Write(byte[] buffer, int offset, int count)
{
this.innerWriter.WriteBase64(buffer, offset, count);
}
}
}
/// <summary>
/// Performs the actual task of exception serialization.
/// </summary>
private class ErrorSerializer
{
#region Private Fields.
/// <summary>Default error response encoding.</summary>
private static Encoding defaultEncoding = new UTF8Encoding(false, true);
/// <summary>Exception to serialize.</summary>
private Exception _exception;
#endregion
#region Constructors.
/// <summary>Initializes a new <see cref="ErrorSerializer"/> instance.</summary>
/// <param name="e">Exception to handle.</param>
internal ErrorSerializer(Exception e)
{
Debug.Assert(e != null, "exception != null");
this._exception = e;
}
#endregion Constructors.
/// <summary>Serializes the current exception description to the specified <paramref name="stream"/>.</summary>
/// <param name="stream">Stream to write to.</param>
internal void SerializeXmlErrorToStream(Stream stream)
{
Debug.Assert(stream != null, "stream != null");
using (XmlWriter writer = ServiceUtils.CreateXmlWriterAndWriteProcessingInstruction(stream, ErrorSerializer.defaultEncoding))
{
Debug.Assert(writer != null, "writer != null");
writer.WriteStartElement(ServiceUtils.XmlErrorElementName, ServiceUtils.DataWebMetadataNamespace);
string errorCode, message, messageLang;
DomainDataServiceException dataException = ExtractErrorValues(this._exception, out errorCode, out message, out messageLang);
writer.WriteStartElement(ServiceUtils.XmlErrorCodeElementName, ServiceUtils.DataWebMetadataNamespace);
writer.WriteString(errorCode);
writer.WriteEndElement(); // </code>
writer.WriteStartElement(ServiceUtils.XmlErrorMessageElementName, ServiceUtils.DataWebMetadataNamespace);
writer.WriteAttributeString(
ServiceUtils.XmlNamespacePrefix, // prefix
ServiceUtils.XmlLangAttributeName, // localName
null, // ns
messageLang); // value
writer.WriteString(message);
writer.WriteEndElement(); // </message>
// Always assuming verbose errors.
Exception exception = (dataException == null) ? this._exception : dataException.InnerException;
SerializeXmlException(writer, exception);
writer.WriteEndElement(); // </error>
writer.Flush();
}
}
/// <summary>Serializes an exception in XML format.</summary>
/// <param name='writer'>Writer to which error should be serialized.</param>
/// <param name='exception'>Exception to serialize.</param>
private static void SerializeXmlException(XmlWriter writer, Exception exception)
{
string elementName = ServiceUtils.XmlErrorInnerElementName;
int nestingDepth = 0;
while (exception != null)
{
// Inner Error Tag namespace changed to DataWebMetadataNamespace
// Maybe DataWebNamespace should be used on all error tags? Up to debate...
// NOTE: this is a breaking change from V1
writer.WriteStartElement(elementName, ServiceUtils.DataWebMetadataNamespace);
nestingDepth++;
string exceptionMessage = exception.Message ?? String.Empty;
writer.WriteStartElement(ServiceUtils.XmlErrorMessageElementName, ServiceUtils.DataWebMetadataNamespace);
writer.WriteString(exceptionMessage);
writer.WriteEndElement(); // </message>
string exceptionType = exception.GetType().FullName;
writer.WriteStartElement(ServiceUtils.XmlErrorTypeElementName, ServiceUtils.DataWebMetadataNamespace);
writer.WriteString(exceptionType);
writer.WriteEndElement(); // </type>
string exceptionStackTrace = exception.StackTrace ?? String.Empty;
writer.WriteStartElement(ServiceUtils.XmlErrorStackTraceElementName, ServiceUtils.DataWebMetadataNamespace);
writer.WriteString(exceptionStackTrace);
writer.WriteEndElement(); // </stacktrace>
exception = exception.InnerException;
elementName = ServiceUtils.XmlErrorInternalExceptionElementName;
}
while (nestingDepth > 0)
{
writer.WriteEndElement(); // </innererror>
nestingDepth--;
}
}
/// <summary>
/// Gets values describing the <paramref name='exception' /> if it's a DomainDataServiceException;
/// defaults otherwise.
/// </summary>
/// <param name='exception'>Exception to extract value from.</param>
/// <param name='errorCode'>Error code from the <paramref name='exception' />; blank if not available.</param>
/// <param name='message'>Message from the <paramref name='exception' />; blank if not available.</param>
/// <param name='messageLang'>Message language from the <paramref name='exception' />; current default if not available.</param>
/// <returns>The cast DataServiceException; possibly null.</returns>
private static DomainDataServiceException ExtractErrorValues(Exception exception, out string errorCode, out string message, out string messageLang)
{
DomainDataServiceException dataException = exception as DomainDataServiceException;
if (dataException != null)
{
errorCode = dataException.ErrorCode ?? string.Empty;
message = dataException.Message ?? string.Empty;
messageLang = dataException.MessageLanguage ?? CultureInfo.CurrentCulture.Name;
return dataException;
}
else
{
errorCode = string.Empty;
message = Resource.DomainDataService_General_Error;
messageLang = CultureInfo.CurrentCulture.Name;
return null;
}
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Bson;
using System.Globalization;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="Regex"/> to and from JSON and BSON.
/// </summary>
public class RegexConverter : JsonConverter
{
private const string PatternName = "Pattern";
private const string OptionsName = "Options";
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Regex regex = (Regex) value;
BsonWriter bsonWriter = writer as BsonWriter;
if (bsonWriter != null)
WriteBson(bsonWriter, regex);
else
WriteJson(writer, regex, serializer);
}
private bool HasFlag(RegexOptions options, RegexOptions flag)
{
return ((options & flag) == flag);
}
private void WriteBson(BsonWriter writer, Regex regex)
{
// Regular expression - The first cstring is the regex pattern, the second
// is the regex options string. Options are identified by characters, which
// must be stored in alphabetical order. Valid options are 'i' for case
// insensitive matching, 'm' for multiline matching, 'x' for verbose mode,
// 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode
// ('.' matches everything), and 'u' to make \w, \W, etc. match unicode.
string options = null;
if (HasFlag(regex.Options, RegexOptions.IgnoreCase))
options += "i";
if (HasFlag(regex.Options, RegexOptions.Multiline))
options += "m";
if (HasFlag(regex.Options, RegexOptions.Singleline))
options += "s";
options += "u";
if (HasFlag(regex.Options, RegexOptions.ExplicitCapture))
options += "x";
writer.WriteRegex(regex.ToString(), options);
}
private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer)
{
DefaultContractResolver resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(PatternName) : PatternName);
writer.WriteValue(regex.ToString());
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(OptionsName) : OptionsName);
serializer.Serialize(writer, regex.Options);
writer.WriteEndObject();
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject)
return ReadRegexObject(reader, serializer);
if (reader.TokenType == JsonToken.String)
return ReadRegexString(reader);
throw JsonSerializationException.Create(reader, "Unexpected token when reading Regex.");
}
private object ReadRegexString(JsonReader reader)
{
string regexText = (string)reader.Value;
int patternOptionDelimiterIndex = regexText.LastIndexOf('/');
string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1);
string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1);
RegexOptions options = RegexOptions.None;
foreach (char c in optionsText)
{
switch (c)
{
case 'i':
options |= RegexOptions.IgnoreCase;
break;
case 'm':
options |= RegexOptions.Multiline;
break;
case 's':
options |= RegexOptions.Singleline;
break;
case 'x':
options |= RegexOptions.ExplicitCapture;
break;
}
}
return new Regex(patternText, options);
}
private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer)
{
string pattern = null;
RegexOptions? options = null;
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propertyName = reader.Value.ToString();
if (!reader.Read())
throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex.");
if (string.Equals(propertyName, PatternName, StringComparison.OrdinalIgnoreCase))
pattern = (string)reader.Value;
else if (string.Equals(propertyName, OptionsName, StringComparison.OrdinalIgnoreCase))
options = serializer.Deserialize<RegexOptions>(reader);
else
reader.Skip();
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
if (pattern == null)
throw JsonSerializationException.Create(reader, "Error deserializing Regex. No pattern found.");
return new Regex(pattern, options ?? RegexOptions.None);
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex.");
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return (objectType == typeof (Regex));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class OfTypeTests
{
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_AllValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (int i in query.Select(x => (object)x).OfType<int>())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_AllValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_Unordered_AllValid(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_AllValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
foreach (int i in query.Select(x => (object)x).OfType<int>())
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(Sources))]
public static void OfType_AllValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_AllValid(labeled, count);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_AllValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(query.Select(x => (object)x).OfType<int>().ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_AllValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_Unordered_AllValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_AllValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.Select(x => (object)x).OfType<int>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(Sources))]
public static void OfType_AllValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_AllValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Empty(query.OfType<long>());
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_NoneValid(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Empty(query.OfType<long>().ToList());
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_NoneValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_SomeValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(count / 2, (count + 1) / 2);
foreach (int i in query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_SomeValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_Unordered_SomeValid(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
foreach (int i in query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>())
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(Sources))]
public static void OfType_SomeValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValid(labeled, count);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_SomeValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(count / 2, (count + 1) / 2);
Assert.All(query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>().ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(UnorderedSources))]
public static void OfType_Unordered_SomeValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_Unordered_SomeValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(Sources))]
public static void OfType_SomeValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeInvalidNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)x : null).OfType<int>(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(Sources))]
public static void OfType_SomeInvalidNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeInvalidNull(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeValidNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int nullCount = 0;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)(x.ToString()) : (object)(string)null).OfType<string>(),
x =>
{
if (string.IsNullOrEmpty(x)) nullCount++;
else Assert.Equal(seen++, int.Parse(x));
});
Assert.Equal(count, seen);
Assert.Equal(0, nullCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(Sources))]
public static void OfType_SomeValidNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValidNull(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int nullCount = 0;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)(int?)x : (int?)null).OfType<int?>(),
x =>
{
if (!x.HasValue) nullCount++;
else Assert.Equal(seen++, x.Value);
});
Assert.Equal(count, seen);
Assert.Equal(0, nullCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 256 }, MemberType = typeof(Sources))]
public static void OfType_SomeNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeNull(labeled, count);
}
[Fact]
public static void OfType_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<object>)null).OfType<int>());
}
}
}
| |
using System;
using System.Text;
using System.Web.Mvc;
using System.Xml;
using XmlRpcMvc.Extensions;
namespace XmlRpcMvc
{
public class XmlRpcResult : ActionResult
{
private readonly Type[] _services;
public XmlRpcResult(params Type[] services)
{
_services = services;
}
private bool _generateServiceOverview = true;
public bool GenerateServiceOverview
{
get { return _generateServiceOverview; }
set { _generateServiceOverview = value; }
}
public override void ExecuteResult(ControllerContext context)
{
var request = context.HttpContext.Request;
if (GenerateServiceOverview &&
request.HttpMethod.Equals(
HttpVerbs.Get.ToString(),
StringComparison.OrdinalIgnoreCase))
{
new XmlRpcOverviewResult(GenerateServiceOverview, _services)
.ExecuteResult(context);
return;
}
if (!request.HttpMethod.Equals(
HttpVerbs.Post.ToString(),
StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException();
}
var requestInfo =
XmlRpcRequestParser.GetRequestInformation(
request.InputStream);
if (string.IsNullOrWhiteSpace(requestInfo.MethodName))
{
throw new InvalidOperationException(
"XmlRpc call does not contain a method.");
}
var methodInfo =
XmlRpcRequestParser.GetRequestedMethod(requestInfo, _services);
if (methodInfo == null)
{
throw new InvalidOperationException(
string.Concat(
"There was no implementation of IXmlRpcService ",
"found, that containins a method decorated with ",
" the XmlRpcMethodAttribute value'",
requestInfo.MethodName,
"'."));
}
var result =
XmlRpcRequestParser.ExecuteRequestedMethod(
requestInfo, methodInfo, context.Controller);
var response = context.RequestContext.HttpContext.Response;
response.ContentType = "text/xml";
var settings =
new XmlWriterSettings
{
OmitXmlDeclaration = false,
Encoding = new UTF8Encoding(false), // Get rid of BOM
Indent = true,
};
using (var writer =
XmlWriter.Create(response.OutputStream, settings))
{
if (methodInfo.ResponseType == XmlRpcResponseType.Wrapped)
{
WriteWrappedResponse(writer, result);
return;
}
WriteRawResponse(writer, result);
}
}
private static void WriteRawResponse(
XmlWriter output,
dynamic result)
{
output.WriteStartDocument();
{
output.WriteStartElement("response");
{
WriteObject(output, result);
}
output.WriteEndElement();
}
output.WriteEndDocument();
}
private static void WriteWrappedResponse(
XmlWriter output,
dynamic result)
{
output.WriteStartDocument();
{
output.WriteStartElement("methodResponse");
{
output.WriteStartElement("params");
{
output.WriteStartElement("param");
{
output.WriteStartElement("value");
{
WriteObject(output, result);
}
output.WriteEndElement();
}
output.WriteEndElement();
}
output.WriteEndElement();
}
output.WriteEndElement();
}
output.WriteEndDocument();
}
private static void WriteObject(
XmlWriter xmlWriter,
dynamic result)
{
Type type = result.GetType();
if (type.IsPrimitive())
{
xmlWriter.WrapOutgoingType((object)result);
}
else if (type.IsArray)
{
WriteArray(xmlWriter, result);
}
else if (!type.IsPrimitive && type.IsClass)
{
WriteClass(xmlWriter, type, result);
}
}
private static void WriteClass(
XmlWriter xmlWriter,
Type type,
object obj)
{
xmlWriter.WriteStartElement("struct");
foreach (var property in type.GetProperties())
{
var value = property.GetValue(obj, null);
if (value == null)
continue;
xmlWriter.WriteStartElement("member");
{
xmlWriter.WriteStartElement("name");
{
xmlWriter.WriteString(property.GetSerializationName());
}
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("value");
{
WriteObject(xmlWriter, value);
}
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
// struct
xmlWriter.WriteEndElement();
}
private static void WriteArray(XmlWriter xmlWriter, dynamic obj)
{
xmlWriter.WriteStartElement("array");
{
xmlWriter.WriteStartElement("data");
{
foreach (var resultEntry in obj)
{
xmlWriter.WriteStartElement("value");
{
WriteObject(xmlWriter, resultEntry);
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
xmlWriter.WriteEndElement();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Application.Navigation;
using Abp.Authorization;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Localization;
using Abp.Runtime.Session;
using Abp.Timing;
using Abp.Timing.Timezone;
using Abp.Web.Models.AbpUserConfiguration;
using Abp.Web.Security.AntiForgery;
using System.Linq;
using Abp.Dependency;
using Abp.Extensions;
using System.Globalization;
namespace Abp.Web.Configuration
{
public class AbpUserConfigurationBuilder : ITransientDependency
{
private readonly IMultiTenancyConfig _multiTenancyConfig;
private readonly ILanguageManager _languageManager;
private readonly ILocalizationManager _localizationManager;
private readonly IFeatureManager _featureManager;
private readonly IFeatureChecker _featureChecker;
private readonly IPermissionManager _permissionManager;
private readonly IUserNavigationManager _userNavigationManager;
private readonly ISettingDefinitionManager _settingDefinitionManager;
private readonly ISettingManager _settingManager;
private readonly IAbpAntiForgeryConfiguration _abpAntiForgeryConfiguration;
private readonly IAbpSession _abpSession;
private readonly IPermissionChecker _permissionChecker;
public AbpUserConfigurationBuilder(
IMultiTenancyConfig multiTenancyConfig,
ILanguageManager languageManager,
ILocalizationManager localizationManager,
IFeatureManager featureManager,
IFeatureChecker featureChecker,
IPermissionManager permissionManager,
IUserNavigationManager userNavigationManager,
ISettingDefinitionManager settingDefinitionManager,
ISettingManager settingManager,
IAbpAntiForgeryConfiguration abpAntiForgeryConfiguration,
IAbpSession abpSession,
IPermissionChecker permissionChecker)
{
_multiTenancyConfig = multiTenancyConfig;
_languageManager = languageManager;
_localizationManager = localizationManager;
_featureManager = featureManager;
_featureChecker = featureChecker;
_permissionManager = permissionManager;
_userNavigationManager = userNavigationManager;
_settingDefinitionManager = settingDefinitionManager;
_settingManager = settingManager;
_abpAntiForgeryConfiguration = abpAntiForgeryConfiguration;
_abpSession = abpSession;
_permissionChecker = permissionChecker;
}
public async Task<AbpUserConfigurationDto> GetAll()
{
return new AbpUserConfigurationDto
{
MultiTenancy = GetUserMultiTenancyConfig(),
Session = GetUserSessionConfig(),
Localization = GetUserLocalizationConfig(),
Features = await GetUserFeaturesConfig(),
Auth = await GetUserAuthConfig(),
Nav = await GetUserNavConfig(),
Setting = await GetUserSettingConfig(),
Clock = GetUserClockConfig(),
Timing = await GetUserTimingConfig(),
Security = GetUserSecurityConfig()
};
}
private AbpMultiTenancyConfigDto GetUserMultiTenancyConfig()
{
return new AbpMultiTenancyConfigDto
{
IsEnabled = _multiTenancyConfig.IsEnabled
};
}
private AbpUserSessionConfigDto GetUserSessionConfig()
{
return new AbpUserSessionConfigDto
{
UserId = _abpSession.UserId,
TenantId = _abpSession.TenantId,
ImpersonatorUserId = _abpSession.ImpersonatorUserId,
ImpersonatorTenantId = _abpSession.ImpersonatorTenantId,
MultiTenancySide = _abpSession.MultiTenancySide
};
}
private AbpUserLocalizationConfigDto GetUserLocalizationConfig()
{
var currentCulture = CultureInfo.CurrentUICulture;
var languages = _languageManager.GetLanguages();
var config = new AbpUserLocalizationConfigDto
{
CurrentCulture = new AbpUserCurrentCultureConfigDto
{
Name = currentCulture.Name,
DisplayName = currentCulture.DisplayName
},
Languages = languages.ToList()
};
if (languages.Count > 0)
{
config.CurrentLanguage = _languageManager.CurrentLanguage;
}
var sources = _localizationManager.GetAllSources().OrderBy(s => s.Name).ToArray();
config.Sources = sources.Select(s => new AbpLocalizationSourceDto
{
Name = s.Name,
Type = s.GetType().Name
}).ToList();
config.Values = new Dictionary<string, Dictionary<string, string>>();
foreach (var source in sources)
{
var stringValues = source.GetAllStrings(currentCulture).OrderBy(s => s.Name).ToList();
var stringDictionary = stringValues
.ToDictionary(_ => _.Name, _ => _.Value);
config.Values.Add(source.Name, stringDictionary);
}
return config;
}
private async Task<AbpUserFeatureConfigDto> GetUserFeaturesConfig()
{
var config = new AbpUserFeatureConfigDto()
{
AllFeatures = new Dictionary<string, AbpStringValueDto>()
};
var allFeatures = _featureManager.GetAll().ToList();
if (_abpSession.TenantId.HasValue)
{
var currentTenantId = _abpSession.GetTenantId();
foreach (var feature in allFeatures)
{
var value = await _featureChecker.GetValueAsync(currentTenantId, feature.Name);
config.AllFeatures.Add(feature.Name, new AbpStringValueDto
{
Value = value
});
}
}
else
{
foreach (var feature in allFeatures)
{
config.AllFeatures.Add(feature.Name, new AbpStringValueDto
{
Value = feature.DefaultValue
});
}
}
return config;
}
private async Task<AbpUserAuthConfigDto> GetUserAuthConfig()
{
var config = new AbpUserAuthConfigDto();
var allPermissionNames = _permissionManager.GetAllPermissions(false).Select(p => p.Name).ToList();
var grantedPermissionNames = new List<string>();
if (_abpSession.UserId.HasValue)
{
foreach (var permissionName in allPermissionNames)
{
if (await _permissionChecker.IsGrantedAsync(permissionName))
{
grantedPermissionNames.Add(permissionName);
}
}
}
config.AllPermissions = allPermissionNames.ToDictionary(permissionName => permissionName, permissionName => "true");
config.GrantedPermissions = grantedPermissionNames.ToDictionary(permissionName => permissionName, permissionName => "true");
return config;
}
private async Task<AbpUserNavConfigDto> GetUserNavConfig()
{
var userMenus = await _userNavigationManager.GetMenusAsync(_abpSession.ToUserIdentifier());
return new AbpUserNavConfigDto
{
Menus = userMenus.ToDictionary(userMenu => userMenu.Name, userMenu => userMenu)
};
}
private async Task<AbpUserSettingConfigDto> GetUserSettingConfig()
{
var config = new AbpUserSettingConfigDto
{
Values = new Dictionary<string, string>()
};
var settingDefinitions = _settingDefinitionManager
.GetAllSettingDefinitions()
.Where(sd => sd.IsVisibleToClients);
foreach (var settingDefinition in settingDefinitions)
{
var settingValue = await _settingManager.GetSettingValueAsync(settingDefinition.Name);
config.Values.Add(settingDefinition.Name, settingValue);
}
return config;
}
private AbpUserClockConfigDto GetUserClockConfig()
{
return new AbpUserClockConfigDto
{
Provider = Clock.Provider.GetType().Name.ToCamelCase()
};
}
private async Task<AbpUserTimingConfigDto> GetUserTimingConfig()
{
var timezoneId = await _settingManager.GetSettingValueAsync(TimingSettingNames.TimeZone);
var timezone = TimeZoneInfo.FindSystemTimeZoneById(timezoneId);
return new AbpUserTimingConfigDto
{
TimeZoneInfo = new AbpUserTimeZoneConfigDto
{
Windows = new AbpUserWindowsTimeZoneConfigDto
{
TimeZoneId = timezoneId,
BaseUtcOffsetInMilliseconds = timezone.BaseUtcOffset.TotalMilliseconds,
CurrentUtcOffsetInMilliseconds = timezone.GetUtcOffset(Clock.Now).TotalMilliseconds,
IsDaylightSavingTimeNow = timezone.IsDaylightSavingTime(Clock.Now)
},
Iana = new AbpUserIanaTimeZoneConfigDto
{
TimeZoneId = TimezoneHelper.WindowsToIana(timezoneId)
}
}
};
}
private AbpUserSecurityConfigDto GetUserSecurityConfig()
{
return new AbpUserSecurityConfigDto()
{
AntiForgery = new AbpUserAntiForgeryConfigDto
{
TokenCookieName = _abpAntiForgeryConfiguration.TokenCookieName,
TokenHeaderName = _abpAntiForgeryConfiguration.TokenHeaderName
}
};
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
namespace Frapid.Config.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing App Dependencies.
/// </summary>
[RoutePrefix("api/v1.0/config/app-dependency")]
public class AppDependencyController : FrapidApiController
{
/// <summary>
/// The AppDependency repository.
/// </summary>
private readonly IAppDependencyRepository AppDependencyRepository;
public AppDependencyController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>();
this._UserId = AppUsers.GetCurrent().View.UserId.To<int>();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>();
this._Catalog = AppUsers.GetCatalog();
this.AppDependencyRepository = new Frapid.Config.DataAccess.AppDependency
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public AppDependencyController(IAppDependencyRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.To<long>();
this._UserId = view.UserId.To<int>();
this._OfficeId = view.OfficeId.To<int>();
this._Catalog = catalog;
this.AppDependencyRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Creates meta information of "app dependency" entity.
/// </summary>
/// <returns>Returns the "app dependency" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/config/app-dependency/meta")]
[Authorize]
public EntityView GetEntityView()
{
if (this._LoginId == 0)
{
return new EntityView();
}
return new EntityView
{
PrimaryKey = "app_dependency_id",
Columns = new List<EntityColumn>()
{
new EntityColumn { ColumnName = "app_dependency_id", PropertyName = "AppDependencyId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "app_name", PropertyName = "AppName", DataType = "string", DbDataType = "varchar", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 },
new EntityColumn { ColumnName = "depends_on", PropertyName = "DependsOn", DataType = "string", DbDataType = "varchar", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 }
}
};
}
/// <summary>
/// Counts the number of app dependencies.
/// </summary>
/// <returns>Returns the count of the app dependencies.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/config/app-dependency/count")]
[Authorize]
public long Count()
{
try
{
return this.AppDependencyRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of app dependency.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/config/app-dependency/all")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.AppDependency> GetAll()
{
try
{
return this.AppDependencyRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of app dependency for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/config/app-dependency/export")]
[Authorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.AppDependencyRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of app dependency.
/// </summary>
/// <param name="appDependencyId">Enter AppDependencyId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{appDependencyId}")]
[Route("~/api/config/app-dependency/{appDependencyId}")]
[Authorize]
public Frapid.Config.Entities.AppDependency Get(int appDependencyId)
{
try
{
return this.AppDependencyRepository.Get(appDependencyId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/config/app-dependency/get")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.AppDependency> Get([FromUri] int[] appDependencyIds)
{
try
{
return this.AppDependencyRepository.Get(appDependencyIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of app dependency.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/config/app-dependency/first")]
[Authorize]
public Frapid.Config.Entities.AppDependency GetFirst()
{
try
{
return this.AppDependencyRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of app dependency.
/// </summary>
/// <param name="appDependencyId">Enter AppDependencyId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{appDependencyId}")]
[Route("~/api/config/app-dependency/previous/{appDependencyId}")]
[Authorize]
public Frapid.Config.Entities.AppDependency GetPrevious(int appDependencyId)
{
try
{
return this.AppDependencyRepository.GetPrevious(appDependencyId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of app dependency.
/// </summary>
/// <param name="appDependencyId">Enter AppDependencyId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{appDependencyId}")]
[Route("~/api/config/app-dependency/next/{appDependencyId}")]
[Authorize]
public Frapid.Config.Entities.AppDependency GetNext(int appDependencyId)
{
try
{
return this.AppDependencyRepository.GetNext(appDependencyId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of app dependency.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/config/app-dependency/last")]
[Authorize]
public Frapid.Config.Entities.AppDependency GetLast()
{
try
{
return this.AppDependencyRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 app dependencies on each page, sorted by the property AppDependencyId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/config/app-dependency")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.AppDependency> GetPaginatedResult()
{
try
{
return this.AppDependencyRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 app dependencies on each page, sorted by the property AppDependencyId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/config/app-dependency/page/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.AppDependency> GetPaginatedResult(long pageNumber)
{
try
{
return this.AppDependencyRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of app dependencies using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered app dependencies.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/config/app-dependency/count-where")]
[Authorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.AppDependencyRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 app dependencies on each page, sorted by the property AppDependencyId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/config/app-dependency/get-where/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.AppDependency> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.AppDependencyRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of app dependencies using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered app dependencies.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/config/app-dependency/count-filtered/{filterName}")]
[Authorize]
public long CountFiltered(string filterName)
{
try
{
return this.AppDependencyRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 app dependencies on each page, sorted by the property AppDependencyId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/config/app-dependency/get-filtered/{pageNumber}/{filterName}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.AppDependency> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.AppDependencyRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of app dependencies.
/// </summary>
/// <returns>Returns an enumerable key/value collection of app dependencies.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/config/app-dependency/display-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.AppDependencyRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for app dependencies.
/// </summary>
/// <returns>Returns an enumerable custom field collection of app dependencies.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/config/app-dependency/custom-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.AppDependencyRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for app dependencies.
/// </summary>
/// <returns>Returns an enumerable custom field collection of app dependencies.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/config/app-dependency/custom-fields/{resourceId}")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.AppDependencyRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of AppDependency class.
/// </summary>
/// <param name="appDependency">Your instance of app dependencies class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/config/app-dependency/add-or-edit")]
[Authorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic appDependency = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (appDependency == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.AppDependencyRepository.AddOrEdit(appDependency, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of AppDependency class.
/// </summary>
/// <param name="appDependency">Your instance of app dependencies class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{appDependency}")]
[Route("~/api/config/app-dependency/add/{appDependency}")]
[Authorize]
public void Add(Frapid.Config.Entities.AppDependency appDependency)
{
if (appDependency == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.AppDependencyRepository.Add(appDependency);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of AppDependency class.
/// </summary>
/// <param name="appDependency">Your instance of AppDependency class to edit.</param>
/// <param name="appDependencyId">Enter the value for AppDependencyId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{appDependencyId}")]
[Route("~/api/config/app-dependency/edit/{appDependencyId}")]
[Authorize]
public void Edit(int appDependencyId, [FromBody] Frapid.Config.Entities.AppDependency appDependency)
{
if (appDependency == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.AppDependencyRepository.Update(appDependency, appDependencyId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of AppDependency class.
/// </summary>
/// <param name="collection">Your collection of AppDependency class to bulk import.</param>
/// <returns>Returns list of imported appDependencyIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any AppDependency class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/config/app-dependency/bulk-import")]
[Authorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> appDependencyCollection = this.ParseCollection(collection);
if (appDependencyCollection == null || appDependencyCollection.Count.Equals(0))
{
return null;
}
try
{
return this.AppDependencyRepository.BulkImport(appDependencyCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of AppDependency class via AppDependencyId.
/// </summary>
/// <param name="appDependencyId">Enter the value for AppDependencyId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{appDependencyId}")]
[Route("~/api/config/app-dependency/delete/{appDependencyId}")]
[Authorize]
public void Delete(int appDependencyId)
{
try
{
this.AppDependencyRepository.Delete(appDependencyId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
namespace System
{
public partial class String
{
//
//Native Static Methods
//
private unsafe static int CompareOrdinalIgnoreCaseHelper(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
int charA = 0, charB = 0;
while (length != 0)
{
charA = *a;
charB = *b;
Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
// uppercase both chars - notice that we need just one compare per char
if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
//Return the (case-insensitive) difference between them.
if (charA != charB)
return charA - charB;
// Next char
a++; b++;
length--;
}
return strA.Length - strB.Length;
}
}
// native call to COMString::CompareOrdinalEx
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int CompareOrdinalHelper(String strA, int indexA, int countA, String strB, int indexB, int countB);
//This will not work in case-insensitive mode for any character greater than 0x80.
//We'll throw an ArgumentException.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern int nativeCompareOrdinalIgnoreCaseWC(String strA, sbyte* strBBytes);
//
//
// NATIVE INSTANCE METHODS
//
//
//
// Search/Query methods
//
private unsafe static bool EqualsHelper(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(strA.Length == strB.Length);
int length = strA.Length;
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
#if BIT64
// Single int read aligns pointers for the following long reads
// PERF: No length check needed as there is always an int32 worth of string allocated
// This read can also include the null terminator which both strings will have
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
// for AMD64 bit platform we unroll by 12 and
// check 3 qword at a time. This is less code
// than the 32 bit case and is a shorter path length.
while (length >= 12)
{
if (*(long*)a != *(long*)b) return false;
if (*(long*)(a + 4) != *(long*)(b + 4)) return false;
if (*(long*)(a + 8) != *(long*)(b + 8)) return false;
length -= 12; a += 12; b += 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) return false;
if (*(int*)(a + 2) != *(int*)(b + 2)) return false;
if (*(int*)(a + 4) != *(int*)(b + 4)) return false;
if (*(int*)(a + 6) != *(int*)(b + 6)) return false;
if (*(int*)(a + 8) != *(int*)(b + 8)) return false;
length -= 10; a += 10; b += 10;
}
#endif
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) return false;
length -= 2; a += 2; b += 2;
}
return true;
}
}
private unsafe static bool EqualsIgnoreCaseAsciiHelper(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
Debug.Assert(strA.Length == strB.Length);
int length = strA.Length;
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
while (length != 0)
{
int charA = *a;
int charB = *b;
Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
// Ordinal equals or lowercase equals if the result ends up in the a-z range
if (charA == charB ||
((charA | 0x20) == (charB | 0x20) &&
(uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a')))
{
a++;
b++;
length--;
}
else
{
return false;
}
}
return true;
}
}
private unsafe static bool StartsWithOrdinalHelper(String str, String startsWith)
{
Debug.Assert(str != null);
Debug.Assert(startsWith != null);
Debug.Assert(str.Length >= startsWith.Length);
int length = startsWith.Length;
fixed (char* ap = &str._firstChar)
fixed (char* bp = &startsWith._firstChar)
{
char* a = ap;
char* b = bp;
#if BIT64
// Single int read aligns pointers for the following long reads
// No length check needed as this method is called when length >= 2
Debug.Assert(length >= 2);
if (*(int*)a != *(int*)b)
return false;
length -= 2;
a += 2;
b += 2;
while (length >= 12)
{
if (*(long*)a != *(long*)b)
return false;
if (*(long*)(a + 4) != *(long*)(b + 4))
return false;
if (*(long*)(a + 8) != *(long*)(b + 8))
return false;
length -= 12;
a += 12;
b += 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) return false;
if (*(int*)(a+2) != *(int*)(b+2)) return false;
if (*(int*)(a+4) != *(int*)(b+4)) return false;
if (*(int*)(a+6) != *(int*)(b+6)) return false;
if (*(int*)(a+8) != *(int*)(b+8)) return false;
length -= 10; a += 10; b += 10;
}
#endif
while (length >= 2)
{
if (*(int*)a != *(int*)b)
return false;
length -= 2;
a += 2;
b += 2;
}
// PERF: This depends on the fact that the String objects are always zero terminated
// and that the terminating zero is not included in the length. For even string sizes
// this compare can include the zero terminator. Bitwise OR avoids a branch.
return length == 0 | *a == *b;
}
}
private static unsafe int CompareOrdinalHelper(String strA, String strB)
{
Debug.Assert(strA != null);
Debug.Assert(strB != null);
// NOTE: This may be subject to change if eliminating the check
// in the callers makes them small enough to be inlined
Debug.Assert(strA._firstChar == strB._firstChar,
"For performance reasons, callers of this method should " +
"check/short-circuit beforehand if the first char is the same.");
int length = Math.Min(strA.Length, strB.Length);
fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar)
{
char* a = ap;
char* b = bp;
// Check if the second chars are different here
// The reason we check if _firstChar is different is because
// it's the most common case and allows us to avoid a method call
// to here.
// The reason we check if the second char is different is because
// if the first two chars the same we can increment by 4 bytes,
// leaving us word-aligned on both 32-bit (12 bytes into the string)
// and 64-bit (16 bytes) platforms.
// For empty strings, the second char will be null due to padding.
// The start of the string (not including sync block pointer)
// is the method table pointer + string length, which takes up
// 8 bytes on 32-bit, 12 on x64. For empty strings the null
// terminator immediately follows, leaving us with an object
// 10/14 bytes in size. Since everything needs to be a multiple
// of 4/8, this will get padded and zeroed out.
// For one-char strings the second char will be the null terminator.
// NOTE: If in the future there is a way to read the second char
// without pinning the string (e.g. System.Runtime.CompilerServices.Unsafe
// is exposed to mscorlib, or a future version of C# allows inline IL),
// then do that and short-circuit before the fixed.
if (*(a + 1) != *(b + 1)) goto DiffOffset1;
// Since we know that the first two chars are the same,
// we can increment by 2 here and skip 4 bytes.
// This leaves us 8-byte aligned, which results
// on better perf for 64-bit platforms.
length -= 2; a += 2; b += 2;
// unroll the loop
#if BIT64
while (length >= 12)
{
if (*(long*)a != *(long*)b) goto DiffOffset0;
if (*(long*)(a + 4) != *(long*)(b + 4)) goto DiffOffset4;
if (*(long*)(a + 8) != *(long*)(b + 8)) goto DiffOffset8;
length -= 12; a += 12; b += 12;
}
#else // BIT64
while (length >= 10)
{
if (*(int*)a != *(int*)b) goto DiffOffset0;
if (*(int*)(a + 2) != *(int*)(b + 2)) goto DiffOffset2;
if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4;
if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6;
if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8;
length -= 10; a += 10; b += 10;
}
#endif // BIT64
// Fallback loop:
// go back to slower code path and do comparison on 4 bytes at a time.
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) goto DiffNextInt;
length -= 2;
a += 2;
b += 2;
}
// At this point, we have compared all the characters in at least one string.
// The longer string will be larger.
return strA.Length - strB.Length;
#if BIT64
DiffOffset8: a += 4; b += 4;
DiffOffset4: a += 4; b += 4;
#else // BIT64
// Use jumps instead of falling through, since
// otherwise going to DiffOffset8 will involve
// 8 add instructions before getting to DiffNextInt
DiffOffset8: a += 8; b += 8; goto DiffOffset0;
DiffOffset6: a += 6; b += 6; goto DiffOffset0;
DiffOffset4: a += 2; b += 2;
DiffOffset2: a += 2; b += 2;
#endif // BIT64
DiffOffset0:
// If we reached here, we already see a difference in the unrolled loop above
#if BIT64
if (*(int*)a == *(int*)b)
{
a += 2; b += 2;
}
#endif // BIT64
DiffNextInt:
if (*a != *b) return *a - *b;
DiffOffset1:
Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!");
return *(a + 1) - *(b + 1);
}
}
// Provides a culture-correct string comparison. StrA is compared to StrB
// to determine whether it is lexicographically less, equal, or greater, and then returns
// either a negative integer, 0, or a positive integer; respectively.
//
public static int Compare(String strA, String strB)
{
return Compare(strA, strB, StringComparison.CurrentCulture);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase
//
public static int Compare(String strA, String strB, bool ignoreCase)
{
var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
return Compare(strA, strB, comparisonType);
}
// Provides a more flexible function for string comparision. See StringComparison
// for meaning of different comparisonType.
public static int Compare(String strA, String strB, StringComparison comparisonType)
{
if (object.ReferenceEquals(strA, strB))
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return -1;
}
if (strB == null)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return 1;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CompareInfo.Invariant.Compare(strA, strB, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.Compare(strA, strB, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
// Most common case: first character is different.
// Returns false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
case StringComparison.OrdinalIgnoreCase:
// If both strings are ASCII strings, we can take the fast path.
if (strA.IsAscii() && strB.IsAscii())
{
return (CompareOrdinalIgnoreCaseHelper(strA, strB));
}
return CompareInfo.CompareOrdinalIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
//
public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
return culture.CompareInfo.Compare(strA, strB, options);
}
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
// The case-sensitive option is set by ignoreCase, and the culture is set
// by culture
//
public static int Compare(String strA, String strB, bool ignoreCase, CultureInfo culture)
{
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, strB, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length count is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length)
{
// NOTE: It's important we call the boolean overload, and not the StringComparison
// one. The two have some subtly different behavior (see notes in the former).
return Compare(strA, indexA, strB, indexB, length, ignoreCase: false);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length count is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase)
{
// Ideally we would just forward to the string.Compare overload that takes
// a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase.
// That function will return early if an optimization can be applied, e.g. if
// (object)strA == strB && indexA == indexB then it will return 0 straightaway.
// There are a couple of subtle behavior differences that prevent us from doing so
// however:
// - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works
// since that method also returns early for nulls before validation. It shouldn't
// for this overload.
// - Since we originally forwarded to CompareInfo.Compare for all of the argument
// validation logic, the ArgumentOutOfRangeExceptions thrown will contain different
// parameter names.
// Therefore, we have to duplicate some of the logic here.
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean,
// and the culture is set by culture.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, CultureInfo culture)
{
var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
return Compare(strA, indexA, strB, indexB, length, culture, options);
}
// Determines whether two string regions match. The substring of strA beginning
// at indexA of length length is compared with the substring of strB
// beginning at indexB of the same length.
//
public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
int lengthA = length;
int lengthB = length;
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
}
if (strB != null)
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
return culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
{
string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CompareInfo.Invariant.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.OrdinalIgnoreCase:
return (CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB));
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Compares strA and strB using an ordinal (code-point) comparison.
//
public static int CompareOrdinal(String strA, String strB)
{
if (object.ReferenceEquals(strA, strB))
{
return 0;
}
// They can't both be null at this point.
if (strA == null)
{
return -1;
}
if (strB == null)
{
return 1;
}
// Most common case, first character is different.
// This will return false for empty strings.
if (strA._firstChar != strB._firstChar)
{
return strA._firstChar - strB._firstChar;
}
return CompareOrdinalHelper(strA, strB);
}
// TODO https://github.com/dotnet/corefx/issues/21395: Expose this publicly?
internal static int CompareOrdinal(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
{
// TODO: This needs to be optimized / unrolled. It can't just use CompareOrdinalHelper(str, str)
// (changed to accept spans) because its implementation is based on a string layout,
// in a way that doesn't work when there isn't guaranteed to be a null terminator.
int minLength = Math.Min(strA.Length, strB.Length);
for (int i = 0; i < minLength; i++)
{
if (strA[i] != strB[i])
{
return strA[i] - strB[i];
}
}
return strA.Length - strB.Length;
}
// Compares strA and strB using an ordinal (code-point) comparison.
//
public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length)
{
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
{
// They're both null
return 0;
}
return strA == null ? -1 : 1;
}
// COMPAT: Checking for nulls should become before the arguments are validated,
// but other optimizations which allow us to return early should come after.
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeCount);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
if (lengthA < 0 || lengthB < 0)
{
string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
{
return 0;
}
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
}
// Compares this String to another String (cast as object), returning an integer that
// indicates the relationship. This method returns a value less than 0 if this is less than value, 0
// if this is equal to value, or a value greater than 0 if this is greater than value.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
string other = value as string;
if (other == null)
{
throw new ArgumentException(SR.Arg_MustBeString);
}
return CompareTo(other); // will call the string-based overload
}
// Determines the sorting relation of StrB to the current instance.
//
public int CompareTo(String strB)
{
return string.Compare(this, strB, StringComparison.CurrentCulture);
}
// Determines whether a specified string is a suffix of the current instance.
//
// The case-sensitive and culture-sensitive option is set by options,
// and the default culture is used.
//
public Boolean EndsWith(String value)
{
return EndsWith(value, StringComparison.CurrentCulture);
}
public Boolean EndsWith(String value, StringComparison comparisonType)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if ((Object)this == (Object)value)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return true;
}
if (value.Length == 0)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CompareInfo.Invariant.IsSuffix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IsSuffix(this, value, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return this.Length < value.Length ? false : (CompareOrdinalHelper(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
case StringComparison.OrdinalIgnoreCase:
return this.Length < value.Length ? false : (CompareInfo.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture;
return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public bool EndsWith(char value)
{
int thisLen = Length;
return thisLen != 0 && this[thisLen - 1] == value;
}
// Determines whether two strings match.
public override bool Equals(Object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
string str = obj as string;
if (str == null)
return false;
if (this.Length != str.Length)
return false;
return EqualsHelper(this, str);
}
// Determines whether two strings match.
public bool Equals(String value)
{
if (object.ReferenceEquals(this, value))
return true;
// NOTE: No need to worry about casting to object here.
// If either side of an == comparison between strings
// is null, Roslyn generates a simple ceq instruction
// instead of calling string.op_Equality.
if (value == null)
return false;
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
}
public bool Equals(String value, StringComparison comparisonType)
{
if ((Object)this == (Object)value)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return true;
}
if ((Object)value == null)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0);
case StringComparison.InvariantCulture:
return (CompareInfo.Invariant.Compare(this, value, CompareOptions.None) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CompareInfo.Invariant.Compare(this, value, CompareOptions.IgnoreCase) == 0);
case StringComparison.Ordinal:
if (this.Length != value.Length)
return false;
return EqualsHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length != value.Length)
return false;
// If both strings are ASCII strings, we can take the fast path.
if (this.IsAscii() && value.IsAscii())
{
return EqualsIgnoreCaseAsciiHelper(this, value);
}
return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Determines whether two Strings match.
public static bool Equals(String a, String b)
{
if ((Object)a == (Object)b)
{
return true;
}
if ((Object)a == null || (Object)b == null || a.Length != b.Length)
{
return false;
}
return EqualsHelper(a, b);
}
public static bool Equals(String a, String b, StringComparison comparisonType)
{
if ((Object)a == (Object)b)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return true;
}
if ((Object)a == null || (Object)b == null)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return false;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);
case StringComparison.CurrentCultureIgnoreCase:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0);
case StringComparison.InvariantCulture:
return (CompareInfo.Invariant.Compare(a, b, CompareOptions.None) == 0);
case StringComparison.InvariantCultureIgnoreCase:
return (CompareInfo.Invariant.Compare(a, b, CompareOptions.IgnoreCase) == 0);
case StringComparison.Ordinal:
if (a.Length != b.Length)
return false;
return EqualsHelper(a, b);
case StringComparison.OrdinalIgnoreCase:
if (a.Length != b.Length)
return false;
else
{
// If both strings are ASCII strings, we can take the fast path.
if (a.IsAscii() && b.IsAscii())
{
return EqualsIgnoreCaseAsciiHelper(a, b);
}
// Take the slow path.
return (CompareInfo.CompareOrdinalIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0);
}
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public static bool operator ==(String a, String b)
{
return String.Equals(a, b);
}
public static bool operator !=(String a, String b)
{
return !String.Equals(a, b);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int InternalMarvin32HashString(string s);
// Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
// they will return the same hash code.
public override int GetHashCode()
{
return InternalMarvin32HashString(this);
}
// Gets a hash code for this string and this comparison. If strings A and B and comparition C are such
// that String.Equals(A, B, C), then they will return the same hash code with this comparison C.
public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this);
// Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile
// hash table).
internal int GetLegacyNonRandomizedHashCode()
{
unsafe
{
fixed (char* src = &_firstChar)
{
Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary");
#if BIT64
int hash1 = 5381;
#else // !BIT64 (32)
int hash1 = (5381<<16) + 5381;
#endif
int hash2 = hash1;
#if BIT64
int c;
char* s = src;
while ((c = s[0]) != 0)
{
hash1 = ((hash1 << 5) + hash1) ^ c;
c = s[1];
if (c == 0)
break;
hash2 = ((hash2 << 5) + hash2) ^ c;
s += 2;
}
#else // !BIT64 (32)
// 32 bit machines.
int* pint = (int *)src;
int len = this.Length;
while (len > 2)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1];
pint += 2;
len -= 4;
}
if (len > 0)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
}
#endif
#if DEBUG
// We want to ensure we can change our hash function daily.
// This is perfectly fine as long as you don't persist the
// value from GetHashCode to disk or count on String A
// hashing before string B. Those are bugs in your code.
hash1 ^= ThisAssembly.DailyBuildNumber;
#endif
return hash1 + (hash2 * 1566083941);
}
}
}
// Determines whether a specified string is a prefix of the current instance
//
public Boolean StartsWith(String value)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
return StartsWith(value, StringComparison.CurrentCulture);
}
public Boolean StartsWith(String value, StringComparison comparisonType)
{
if ((Object)value == null)
{
throw new ArgumentNullException(nameof(value));
}
if ((Object)this == (Object)value)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return true;
}
if (value.Length == 0)
{
StringSpanHelpers.CheckStringComparison(comparisonType);
return true;
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CompareInfo.Invariant.IsPrefix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IsPrefix(this, value, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
if (this.Length < value.Length || _firstChar != value._firstChar)
{
return false;
}
return (value.Length == 1) ?
true : // First char is the same and thats all there is to compare
StartsWithOrdinalHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
if (this.Length < value.Length)
{
return false;
}
return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, value.Length, value, 0, value.Length) == 0);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture)
{
if (null == value)
{
throw new ArgumentNullException(nameof(value));
}
if ((object)this == (object)value)
{
return true;
}
CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture;
return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
public bool StartsWith(char value) => Length != 0 && _firstChar == value;
}
}
| |
using System;
using System.IO;
using IdSharp.Common.Utils;
namespace IdSharp.Tagging.ID3v2
{
internal sealed class FrameHeader : IFrameHeader
{
private int _frameSize;
private int _frameSizeExcludingAdditions;
private bool _isTagAlterPreservation;
private bool _isFileAlterPreservation;
private bool _isReadOnly;
private bool _isCompressed;
private byte? _encryptionMethod;
private byte? _groupingIdentity;
private int _decompressedSize;
private ID3v2TagVersion _tagVersion;
public ID3v2TagVersion TagVersion
{
get { return _tagVersion; }
}
#region IFrameHeader Members
public int FrameSize
{
get { return _frameSize; }
}
public int FrameSizeTotal
{
get { return _frameSize + (_tagVersion == ID3v2TagVersion.ID3v22 ? 6 : 10); }
}
public int FrameSizeExcludingAdditions
{
get { return _frameSizeExcludingAdditions; }
}
public bool IsTagAlterPreservation
{
get
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
return _isTagAlterPreservation;
}
else
{
return false;
}
}
set
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
_isTagAlterPreservation = value;
}
else
{
_isTagAlterPreservation = false;
}
}
}
public bool IsFileAlterPreservation
{
get
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
return _isFileAlterPreservation;
}
else
{
return false;
}
}
set
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
_isFileAlterPreservation = value;
}
else
{
_isFileAlterPreservation = false;
}
}
}
public bool IsReadOnly
{
get
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
return _isReadOnly;
}
else
{
return false;
}
}
set
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
_isReadOnly = value;
}
else
{
_isReadOnly = false;
}
}
}
public bool IsCompressed
{
get
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
return _isCompressed;
}
else
{
return false;
}
}
set
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
_isCompressed = value;
}
else
{
_isCompressed = false;
}
}
}
public byte? EncryptionMethod
{
get
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
return _encryptionMethod;
}
else
{
return null;
}
}
set
{
// TODO
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
_encryptionMethod = value;
}
else
{
_encryptionMethod = null;
}
}
}
public byte? GroupingIdentity
{
get
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
return _groupingIdentity;
}
else
{
return null;
}
}
set
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
_groupingIdentity = value;
}
else
{
_groupingIdentity = null;
}
}
}
public int DecompressedSize
{
get
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
return _decompressedSize;
}
else
{
return 0;
}
}
set
{
if (_tagVersion != ID3v2TagVersion.ID3v22)
{
_decompressedSize = value;
}
else
{
_decompressedSize = 0;
}
}
}
public bool UsesUnsynchronization
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
public void Read(TagReadingInfo tagReadingInfo, ref Stream stream)
{
// TODO: Some tags have the length INCLUDE the extra ten bytes of the tag header.
// Handle this (don't corrupt MP3 on rewrite)
_tagVersion = tagReadingInfo.TagVersion;
bool usesUnsynchronization = ((tagReadingInfo.TagVersionOptions & TagVersionOptions.Unsynchronized) == TagVersionOptions.Unsynchronized);
if (tagReadingInfo.TagVersion == ID3v2TagVersion.ID3v23)
{
if (!usesUnsynchronization)
_frameSize = stream.ReadInt32();
else
_frameSize = ID3v2Utils.ReadInt32Unsynchronized(stream);
_frameSizeExcludingAdditions = _frameSize;
byte byte0 = stream.Read1();
byte byte1 = stream.Read1();
// First byte
IsTagAlterPreservation = ((byte0 & 0x80) == 0x80);
IsFileAlterPreservation = ((byte0 & 0x40) == 0x40);
IsReadOnly = ((byte0 & 0x20) == 0x20);
// Second byte
IsCompressed = ((byte1 & 0x80) == 0x80);
bool tmpIsEncrypted = ((byte1 & 0x40) == 0x40);
bool tmpIsGroupingIdentity = ((byte1 & 0x20) == 0x20);
// Additional bytes
// Compression
if (IsCompressed)
{
DecompressedSize = stream.ReadInt32();
_frameSizeExcludingAdditions -= 4;
}
else
{
DecompressedSize = 0;
}
// Encryption
if (tmpIsEncrypted)
{
EncryptionMethod = stream.Read1();
_frameSizeExcludingAdditions -= 1;
}
else
{
EncryptionMethod = null;
}
// Grouping Identity
if (tmpIsGroupingIdentity)
{
GroupingIdentity = stream.Read1();
_frameSizeExcludingAdditions -= 1;
}
else
{
GroupingIdentity = null;
}
if (usesUnsynchronization)
{
stream = ID3v2Utils.ReadUnsynchronizedStream(stream, _frameSize);
}
}
else if (tagReadingInfo.TagVersion == ID3v2TagVersion.ID3v22)
{
if (!usesUnsynchronization)
_frameSize = stream.ReadInt24();
else
_frameSize = ID3v2Utils.ReadInt24Unsynchronized(stream);
if ((tagReadingInfo.TagVersionOptions & TagVersionOptions.AddOneByteToSize) == TagVersionOptions.AddOneByteToSize)
{
_frameSize++;
}
_frameSizeExcludingAdditions = _frameSize;
// These fields are not supported in ID3v2.2
IsTagAlterPreservation = false;
IsFileAlterPreservation = false;
IsReadOnly = false;
IsCompressed = false;
DecompressedSize = 0;
EncryptionMethod = null;
GroupingIdentity = null;
if (usesUnsynchronization)
{
stream = ID3v2Utils.ReadUnsynchronizedStream(stream, _frameSize);
}
}
else if (tagReadingInfo.TagVersion == ID3v2TagVersion.ID3v24)
{
if ((tagReadingInfo.TagVersionOptions & TagVersionOptions.UseNonSyncSafeFrameSizeID3v24) == TagVersionOptions.UseNonSyncSafeFrameSizeID3v24)
_frameSize = stream.ReadInt32();
else
_frameSize = ID3v2Utils.ReadInt32SyncSafe(stream);
_frameSizeExcludingAdditions = _frameSize;
byte byte0 = stream.Read1();
byte byte1 = stream.Read1();
bool hasDataLengthIndicator = ((byte1 & 0x01) == 0x01);
usesUnsynchronization = ((byte1 & 0x03) == 0x03);
if (hasDataLengthIndicator)
{
_frameSizeExcludingAdditions -= 4;
stream.Seek(4, SeekOrigin.Current); // skip data length indicator
}
if (usesUnsynchronization)
{
stream = ID3v2Utils.ReadUnsynchronizedStream(stream, _frameSize);
}
// TODO - finish parsing
}
if (IsCompressed)
{
stream = ID3v2Utils.DecompressFrame(stream, FrameSizeExcludingAdditions);
IsCompressed = false;
DecompressedSize = 0;
_frameSizeExcludingAdditions = (int)stream.Length;
}
}
public byte[] GetBytes(MemoryStream frameData, ID3v2TagVersion tagVersion, string frameID)
{
_frameSizeExcludingAdditions = (int)frameData.Length;
if (frameID == null)
return new byte[0];
byte[] frameIDBytes = ByteUtils.ISO88591GetBytes(frameID);
byte[] tmpRawData;
if (tagVersion == ID3v2TagVersion.ID3v22)
{
if (frameIDBytes.Length != 3)
throw new ArgumentException(String.Format("FrameID must be 3 bytes from ID3v2.2 ({0} bytes passed)", frameIDBytes.Length));
tmpRawData = new byte[6];
tmpRawData[0] = frameIDBytes[0];
tmpRawData[1] = frameIDBytes[1];
tmpRawData[2] = frameIDBytes[2];
tmpRawData[3] = (byte)((_frameSizeExcludingAdditions >> 16) & 0xFF);
tmpRawData[4] = (byte)((_frameSizeExcludingAdditions >> 8) & 0xFF);
tmpRawData[5] = (byte)(_frameSizeExcludingAdditions & 0xFF);
}
else if (tagVersion == ID3v2TagVersion.ID3v23)
{
int tmpRawDataSize = 10;
byte tmpByte1 = (byte)((_isTagAlterPreservation ? 0x80 : 0) +
(_isFileAlterPreservation ? 0x40 : 0) +
(_isReadOnly ? 0x20 : 0));
byte tmpByte2 = (byte)((_isCompressed ? 0x80 : 0) +
(_encryptionMethod != null ? 0x40 : 0) +
(_groupingIdentity != null ? 0x20 : 0));
if (_isCompressed) tmpRawDataSize += 4;
if (_encryptionMethod != null) tmpRawDataSize++;
if (_groupingIdentity != null) tmpRawDataSize++;
int tmpFrameSize = _frameSizeExcludingAdditions + (tmpRawDataSize - 10);
tmpRawData = new byte[tmpRawDataSize];
if (frameIDBytes.Length != 4)
throw new ArgumentException(string.Format("FrameID must be 4 bytes ({0} bytes passed)", frameIDBytes.Length));
tmpRawData[0] = frameIDBytes[0];
tmpRawData[1] = frameIDBytes[1];
tmpRawData[2] = frameIDBytes[2];
tmpRawData[3] = frameIDBytes[3];
tmpRawData[4] = (byte)((tmpFrameSize >> 24) & 0xFF);
tmpRawData[5] = (byte)((tmpFrameSize >> 16) & 0xFF);
tmpRawData[6] = (byte)((tmpFrameSize >> 8) & 0xFF);
tmpRawData[7] = (byte)(tmpFrameSize & 0xFF);
tmpRawData[8] = tmpByte1;
tmpRawData[9] = tmpByte2;
int tmpCurrentPosition = 10;
if (_isCompressed)
{
tmpRawData[tmpCurrentPosition++] = (byte)(DecompressedSize >> 24);
tmpRawData[tmpCurrentPosition++] = (byte)(DecompressedSize >> 16);
tmpRawData[tmpCurrentPosition++] = (byte)(DecompressedSize >> 8);
tmpRawData[tmpCurrentPosition++] = (byte)DecompressedSize;
}
if (_encryptionMethod != null) tmpRawData[tmpCurrentPosition++] = _encryptionMethod.Value;
if (_groupingIdentity != null) tmpRawData[tmpCurrentPosition] = _groupingIdentity.Value;
}
else if (tagVersion == ID3v2TagVersion.ID3v24)
{
int tmpRawDataSize = 10;
byte tmpByte1 = (byte)((_isTagAlterPreservation ? 0x40 : 0) +
(_isFileAlterPreservation ? 0x20 : 0) +
(_isReadOnly ? 0x10 : 0));
byte tmpByte2 = (byte)((_groupingIdentity != null ? 0x40 : 0) +
(_isCompressed ? 0x08 : 0) +
(_encryptionMethod != null ? 0x04 : 0)/* +
(false Unsynchronization ? 0x02 : 0) +
(false Data length indicator ? 0x01 : 0)*/
);
if (_isCompressed) tmpRawDataSize += 4;
if (_encryptionMethod != null) tmpRawDataSize++;
if (_groupingIdentity != null) tmpRawDataSize++;
/*TODO: unsync,DLI*/
int tmpFrameSize = _frameSizeExcludingAdditions + (tmpRawDataSize - 10);
tmpRawData = new byte[tmpRawDataSize];
if (frameIDBytes.Length != 4)
throw new ArgumentException(string.Format("FrameID must be 4 bytes ({0} bytes passed)", frameIDBytes.Length));
// Note: ID3v2.4 uses sync safe frame sizes
tmpRawData[0] = frameIDBytes[0];
tmpRawData[1] = frameIDBytes[1];
tmpRawData[2] = frameIDBytes[2];
tmpRawData[3] = frameIDBytes[3];
tmpRawData[4] = (byte)((tmpFrameSize >> 21) & 0x7F);
tmpRawData[5] = (byte)((tmpFrameSize >> 14) & 0x7F);
tmpRawData[6] = (byte)((tmpFrameSize >> 7) & 0x7F);
tmpRawData[7] = (byte)(tmpFrameSize & 0x7F);
tmpRawData[8] = tmpByte1;
tmpRawData[9] = tmpByte2;
int tmpCurrentPosition = 10;
if (_groupingIdentity != null) tmpRawData[tmpCurrentPosition++] = _groupingIdentity.Value;
if (_isCompressed)
{
tmpRawData[tmpCurrentPosition++] = (byte)(DecompressedSize >> 24);
tmpRawData[tmpCurrentPosition++] = (byte)(DecompressedSize >> 16);
tmpRawData[tmpCurrentPosition++] = (byte)(DecompressedSize >> 8);
tmpRawData[tmpCurrentPosition++] = (byte)DecompressedSize;
}
if (_encryptionMethod != null) tmpRawData[tmpCurrentPosition++] = _encryptionMethod.Value;
/*TODO: unsync,DLI*/
}
else
{
throw new ArgumentOutOfRangeException("tagVersion", tagVersion, "Unknown tag version");
}
using (MemoryStream totalFrame = new MemoryStream())
{
totalFrame.Write(tmpRawData);
totalFrame.Write(frameData.ToArray());
return totalFrame.ToArray();
}
}
}
}
| |
using System.Collections.Generic;
using Ecosim.SceneData;
using Ecosim.SceneData.VegetationRules;
using Ecosim.SceneData.Rules;
using Ecosim.SceneData.Action;
using UnityEngine;
namespace Ecosim.SceneEditor
{
public class RulesExtraPanel : ExtraPanel
{
EditorCtrl ctrl;
VegetationType vegetation;
Vector2 scrollPos;
string[] selectableActionStrings;
UserInteraction[] selectableActions;
string[] parameters;
string[] vegetations;
private static GradualParameterChange[] copyBuffer;
private static VegetationRule[] copyBuffer2;
public static void ClearCopyBuffer () {
copyBuffer = null;
copyBuffer2 = null;
}
public RulesExtraPanel (EditorCtrl ctrl, VegetationType veg)
{
this.ctrl = ctrl;
vegetation = veg;
List<string> actionStrList = new List<string> ();
List<UserInteraction> actionList = new List<UserInteraction> ();
actionStrList.Add ("<No action>");
actionList.Add (null);
foreach (UserInteraction ui in ctrl.scene.actions.EnumerateUI()) {
if (ui.action is AreaAction) {
actionStrList.Add (ui.name);
actionList.Add (ui);
}
}
selectableActionStrings = actionStrList.ToArray ();
selectableActions = actionList.ToArray ();
List<string> pList = new List<string> ();
foreach (string p in ctrl.scene.progression.GetAllDataNames()) {
Data dataFindNames = ctrl.scene.progression.GetData (p);
if ((dataFindNames.GetMax () < 256) && (!p.StartsWith ("_")))
pList.Add (p);
}
parameters = pList.ToArray ();
vegetations = new string[vegetation.successionType.vegetations.Length];
for (int i = 0; i < vegetations.Length; i++) {
vegetations [i] = vegetation.successionType.vegetations [i].name;
}
}
int FindActionIndex (UserInteraction action)
{
for (int i = 0; i < selectableActions.Length; i++) {
if (selectableActions [i] == action)
return i;
}
return 0;
}
int FindParamIndex (string paramName)
{
for (int i = 0; i < parameters.Length; i++) {
if (parameters [i] == paramName)
return i;
}
return 0;
}
public bool Render (int mx, int my)
{
bool keepOpen = true;
GUILayout.BeginHorizontal ();
if (GUILayout.Button (ctrl.foldedOpen, ctrl.icon)) {
keepOpen = false;
}
GUILayout.Label ("Rules", GUILayout.Width (100));
GUILayout.Label (vegetation.successionType.name + "\n" + vegetation.name);
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Copy")) {
copyBuffer = new GradualParameterChange [vegetation.gradualChanges.Length];
for (int i = 0; i < copyBuffer.Length; i++) {
copyBuffer[i] = (GradualParameterChange) vegetation.gradualChanges[i].Clone ();
}
copyBuffer2 = new VegetationRule[vegetation.rules.Length];
for (int i = 0; i < copyBuffer2.Length; i++) {
copyBuffer2[i] = (VegetationRule) vegetation.rules[i].Clone ();
}
}
if ((copyBuffer != null) && GUILayout.Button ("Paste")) {
vegetation.gradualChanges = new GradualParameterChange[copyBuffer.Length];
for (int i = 0; i < copyBuffer.Length; i++) {
vegetation.gradualChanges[i] = (GradualParameterChange) copyBuffer[i].Clone ();
}
vegetation.rules = new VegetationRule[copyBuffer2.Length];
for (int i = 0; i < copyBuffer2.Length; i++) {
vegetation.rules[i] = (VegetationRule) copyBuffer2[i].Clone();
if (vegetation.rules[i].vegetation.successionType != vegetation.successionType) {
vegetation.rules[i].vegetation = vegetation;
vegetation.rules[i].vegetationId = vegetation.index;
}
}
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
scrollPos = GUILayout.BeginScrollView (scrollPos, false, false);
// GRADUAL PARAMETER CHANGE
GUILayout.BeginVertical (ctrl.skin.box);
GUILayout.Label ("Gradual Parameter Changes");
foreach (GradualParameterChange gpc in vegetation.gradualChanges) {
GUILayout.BeginVertical (ctrl.skin.box);
GUILayout.BeginHorizontal ();
GUILayout.Label ("Action type", GUILayout.Width (100));
UserInteraction action = gpc.action;
string actionName = (action != null) ? (action.name) : "<No action>";
if (GUILayout.Button (actionName, GUILayout.Width (100))) {
GradualParameterChange tmpGPC = gpc;
ctrl.StartSelection (selectableActionStrings, FindActionIndex (action),
newIndex => {
tmpGPC.actionName = (newIndex > 0) ? (selectableActionStrings [newIndex]) : null;
tmpGPC.action = selectableActions [newIndex]; });
}
GUILayout.FlexibleSpace ();
if (GUILayout.Button ("-", GUILayout.Width (20))) {
List<GradualParameterChange> gcList = new List<GradualParameterChange> (vegetation.gradualChanges);
gcList.Remove (gpc);
vegetation.gradualChanges = gcList.ToArray ();
break;
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
GUILayout.Label ("Chance (0..1)", GUILayout.Width (100));
gpc.chance = GUILayout.HorizontalSlider (gpc.chance, 0.0f, 1.0f, GUILayout.Width (100));
string chanceStr = gpc.chance.ToString ("0.00");
string newChanceStr = GUILayout.TextField (chanceStr, GUILayout.Width (40));
if (newChanceStr != chanceStr) {
float outVal;
if (float.TryParse (newChanceStr, out outVal)) {
gpc.chance = outVal;
}
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
if (GUILayout.Button (gpc.paramName, GUILayout.Width (100))) {
GradualParameterChange tmpGPC = gpc;
ctrl.StartSelection (parameters, FindParamIndex (gpc.paramName),
newIndex => {
tmpGPC.paramName = parameters [newIndex];
tmpGPC.data = ctrl.scene.progression.GetData (tmpGPC.paramName); });
}
string minStr = GUILayout.TextField (gpc.lowRange.ToString (), GUILayout.Width (40));
string maxStr = GUILayout.TextField (gpc.highRange.ToString (), GUILayout.Width (40));
GUILayout.Label ("(" + gpc.data.GetMin () + " - " + gpc.data.GetMax () + ") delta");
string deltaStr = GUILayout.TextField (gpc.deltaChange.ToString (), GUILayout.Width (40));
int outNr;
if (int.TryParse (minStr, out outNr))
gpc.lowRange = outNr;
if (int.TryParse (maxStr, out outNr))
gpc.highRange = outNr;
if (int.TryParse (deltaStr, out outNr))
gpc.deltaChange = outNr;
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
GUILayout.EndVertical ();
}
GUILayout.BeginHorizontal ();
if ((parameters.Length > 0) && GUILayout.Button ("+", GUILayout.Width (20))) {
List<GradualParameterChange> gcList = new List<GradualParameterChange> (vegetation.gradualChanges);
GradualParameterChange newGPC = new GradualParameterChange ();
newGPC.paramName = parameters [0];
newGPC.data = ctrl.scene.progression.GetData (newGPC.paramName);
newGPC.action = null;
newGPC.actionName = null;
gcList.Add (newGPC);
vegetation.gradualChanges = gcList.ToArray ();
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
GUILayout.EndVertical ();
// END GRADUAL PARAMETER CHANGE
// TRANSITION RULES
GUILayout.BeginVertical (ctrl.skin.box);
GUILayout.Label ("Transition Rules");
foreach (VegetationRule r in vegetation.rules) {
GUILayout.BeginVertical (ctrl.skin.box);
GUILayout.BeginHorizontal ();
GUILayout.Label ("Action type", GUILayout.Width (100));
UserInteraction action = r.action;
string actionName = (action != null) ? (action.name) : "<No action>";
if (GUILayout.Button (actionName, GUILayout.Width (100))) {
VegetationRule tmpR = r;
ctrl.StartSelection (selectableActionStrings, FindActionIndex (action),
newIndex => {
tmpR.actionName = (newIndex > 0) ? (selectableActionStrings [newIndex]) : null;
tmpR.action = selectableActions [newIndex]; });
}
GUILayout.FlexibleSpace ();
if (GUILayout.Button ("-", GUILayout.Width (20))) {
List<VegetationRule> rList = new List<VegetationRule> (vegetation.rules);
rList.Remove (r);
vegetation.rules = rList.ToArray ();
break;
}
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
GUILayout.Label ("Chance (0..1)", GUILayout.Width (100));
r.chance = GUILayout.HorizontalSlider (r.chance, 0.0f, 1.0f, GUILayout.Width (100));
string chanceStr = r.chance.ToString ("0.00");
string newChanceStr = GUILayout.TextField (chanceStr, GUILayout.Width (40));
if (newChanceStr != chanceStr) {
float outVal;
if (float.TryParse (newChanceStr, out outVal)) {
r.chance = outVal;
}
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
foreach (ParameterRange pr in r.ranges) {
GUILayout.BeginHorizontal ();
if (GUILayout.Button (pr.paramName, GUILayout.Width (100))) {
ParameterRange tmpPR = pr;
ctrl.StartSelection (parameters, FindParamIndex (tmpPR.paramName),
newIndex => {
tmpPR.paramName = parameters [newIndex];
tmpPR.data = ctrl.scene.progression.GetData (tmpPR.paramName); });
}
string minStr = GUILayout.TextField (pr.lowRange.ToString (), GUILayout.Width (40));
string maxStr = GUILayout.TextField (pr.highRange.ToString (), GUILayout.Width (40));
GUILayout.Label ("(" + pr.data.GetMin () + " - " + pr.data.GetMax () + ")");
int outNr;
if (int.TryParse (minStr, out outNr))
pr.lowRange = outNr;
if (int.TryParse (maxStr, out outNr))
pr.highRange = outNr;
GUILayout.FlexibleSpace ();
if (GUILayout.Button ("-", GUILayout.Width (20))) {
List<ParameterRange> prList = new List<ParameterRange> (r.ranges);
prList.Remove (pr);
r.ranges = prList.ToArray ();
break;
}
GUILayout.EndHorizontal ();
}
GUILayout.BeginHorizontal ();
if ((parameters.Length > 0) && GUILayout.Button ("+", GUILayout.Width (20))) {
ParameterRange newPR = new ParameterRange ();
newPR.paramName = parameters [0];
newPR.data = ctrl.scene.progression.GetData (parameters [0]);
newPR.lowRange = 0;
newPR.highRange = 255;
List<ParameterRange> prList = new List<ParameterRange> (r.ranges);
prList.Add (newPR);
r.ranges = prList.ToArray ();
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
GUILayout.BeginHorizontal ();
GUILayout.Label ("Target vegetation", GUILayout.Width (100));
if (GUILayout.Button (r.vegetation.name, GUILayout.Width (200))) {
ctrl.StartSelection (vegetations, r.vegetationId,
newIndex => {
r.vegetationId = newIndex;
r.vegetation = vegetation.successionType.vegetations [newIndex]; });
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
GUILayout.EndVertical ();
}
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("+", GUILayout.Width (20))) {
VegetationRule newR = new VegetationRule ();
newR.vegetationId = vegetation.index;
newR.vegetation = vegetation;
newR.ranges = new ParameterRange[0];
List<VegetationRule> list = new List<VegetationRule> (vegetation.rules);
list.Add (newR);
vegetation.rules = list.ToArray ();
}
GUILayout.FlexibleSpace ();
GUILayout.EndHorizontal ();
GUILayout.EndVertical ();
// END TRANSITION RULES
GUILayout.EndScrollView ();
return keepOpen;
}
public bool RenderSide (int mx, int my)
{
return false;
}
public void Dispose ()
{
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.IO;
namespace System.Data.ProviderBase
{
internal class DbMetaDataFactory
{ // V1.2.3300
private DataSet _metaDataCollectionsDataSet;
private string _normalizedServerVersion;
private string _serverVersionString;
// well known column names
private const string _collectionName = "CollectionName";
private const string _populationMechanism = "PopulationMechanism";
private const string _populationString = "PopulationString";
private const string _maximumVersion = "MaximumVersion";
private const string _minimumVersion = "MinimumVersion";
private const string _dataSourceProductVersionNormalized = "DataSourceProductVersionNormalized";
private const string _dataSourceProductVersion = "DataSourceProductVersion";
private const string _restrictionNumber = "RestrictionNumber";
private const string _numberOfRestrictions = "NumberOfRestrictions";
private const string _restrictionName = "RestrictionName";
private const string _parameterName = "ParameterName";
// population mechanisms
private const string _dataTable = "DataTable";
private const string _sqlCommand = "SQLCommand";
private const string _prepareCollection = "PrepareCollection";
public DbMetaDataFactory(Stream xmlStream, string serverVersion, string normalizedServerVersion)
{
ADP.CheckArgumentNull(xmlStream, "xmlStream");
ADP.CheckArgumentNull(serverVersion, "serverVersion");
ADP.CheckArgumentNull(normalizedServerVersion, "normalizedServerVersion");
LoadDataSetFromXml(xmlStream);
_serverVersionString = serverVersion;
_normalizedServerVersion = normalizedServerVersion;
}
protected DataSet CollectionDataSet
{
get
{
return _metaDataCollectionsDataSet;
}
}
protected string ServerVersion
{
get
{
return _serverVersionString;
}
}
protected string ServerVersionNormalized
{
get
{
return _normalizedServerVersion;
}
}
protected DataTable CloneAndFilterCollection(string collectionName, string[] hiddenColumnNames)
{
DataTable sourceTable;
DataTable destinationTable;
DataColumn[] filteredSourceColumns;
DataColumnCollection destinationColumns;
DataRow newRow;
sourceTable = _metaDataCollectionsDataSet.Tables[collectionName];
if ((sourceTable == null) || (collectionName != sourceTable.TableName))
{
throw ADP.DataTableDoesNotExist(collectionName);
}
destinationTable = new DataTable(collectionName);
destinationTable.Locale = CultureInfo.InvariantCulture;
destinationColumns = destinationTable.Columns;
filteredSourceColumns = FilterColumns(sourceTable, hiddenColumnNames, destinationColumns);
foreach (DataRow row in sourceTable.Rows)
{
if (SupportedByCurrentVersion(row) == true)
{
newRow = destinationTable.NewRow();
for (int i = 0; i < destinationColumns.Count; i++)
{
newRow[destinationColumns[i]] = row[filteredSourceColumns[i], DataRowVersion.Current];
}
destinationTable.Rows.Add(newRow);
newRow.AcceptChanges();
}
}
return destinationTable;
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_normalizedServerVersion = null;
_serverVersionString = null;
_metaDataCollectionsDataSet.Dispose();
}
}
private DataTable ExecuteCommand(DataRow requestedCollectionRow, string[] restrictions, DbConnection connection)
{
DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
DataColumn populationStringColumn = metaDataCollectionsTable.Columns[_populationString];
DataColumn numberOfRestrictionsColumn = metaDataCollectionsTable.Columns[_numberOfRestrictions];
DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName];
//DataColumn restrictionNameColumn = metaDataCollectionsTable.Columns[_restrictionName];
DataTable resultTable = null;
DbCommand command = null;
DataTable schemaTable = null;
Debug.Assert(requestedCollectionRow != null);
string sqlCommand = requestedCollectionRow[populationStringColumn, DataRowVersion.Current] as string;
int numberOfRestrictions = (int)requestedCollectionRow[numberOfRestrictionsColumn, DataRowVersion.Current];
string collectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string;
if ((restrictions != null) && (restrictions.Length > numberOfRestrictions))
{
throw ADP.TooManyRestrictions(collectionName);
}
command = connection.CreateCommand();
command.CommandText = sqlCommand;
command.CommandTimeout = System.Math.Max(command.CommandTimeout, 180);
for (int i = 0; i < numberOfRestrictions; i++)
{
DbParameter restrictionParameter = command.CreateParameter();
if ((restrictions != null) && (restrictions.Length > i) && (restrictions[i] != null))
{
restrictionParameter.Value = restrictions[i];
}
else
{
// This is where we have to assign null to the value of the parameter.
restrictionParameter.Value = DBNull.Value;
}
restrictionParameter.ParameterName = GetParameterName(collectionName, i + 1);
restrictionParameter.Direction = ParameterDirection.Input;
command.Parameters.Add(restrictionParameter);
}
DbDataReader reader = null;
try
{
try
{
reader = command.ExecuteReader();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
throw ADP.QueryFailed(collectionName, e);
}
// TODO: Consider using the DataAdapter.Fill
// Build a DataTable from the reader
resultTable = new DataTable(collectionName);
resultTable.Locale = CultureInfo.InvariantCulture;
schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
resultTable.Columns.Add(row["ColumnName"] as string, (Type)row["DataType"]);
}
object[] values = new object[resultTable.Columns.Count];
while (reader.Read())
{
reader.GetValues(values);
resultTable.Rows.Add(values);
}
}
finally
{
if (reader != null)
{
reader.Dispose();
reader = null;
}
}
return resultTable;
}
private DataColumn[] FilterColumns(DataTable sourceTable, string[] hiddenColumnNames, DataColumnCollection destinationColumns)
{
DataColumn newDestinationColumn;
int currentColumn;
DataColumn[] filteredSourceColumns = null;
int columnCount = 0;
foreach (DataColumn sourceColumn in sourceTable.Columns)
{
if (IncludeThisColumn(sourceColumn, hiddenColumnNames) == true)
{
columnCount++;
}
}
if (columnCount == 0)
{
throw ADP.NoColumns();
}
currentColumn = 0;
filteredSourceColumns = new DataColumn[columnCount];
foreach (DataColumn sourceColumn in sourceTable.Columns)
{
if (IncludeThisColumn(sourceColumn, hiddenColumnNames) == true)
{
newDestinationColumn = new DataColumn(sourceColumn.ColumnName, sourceColumn.DataType);
destinationColumns.Add(newDestinationColumn);
filteredSourceColumns[currentColumn] = sourceColumn;
currentColumn++;
}
}
return filteredSourceColumns;
}
internal DataRow FindMetaDataCollectionRow(string collectionName)
{
bool versionFailure;
bool haveExactMatch;
bool haveMultipleInexactMatches;
string candidateCollectionName;
DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
if (metaDataCollectionsTable == null)
{
throw ADP.InvalidXml();
}
DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName];
if ((null == collectionNameColumn) || (typeof(string) != collectionNameColumn.DataType))
{
throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName);
}
DataRow requestedCollectionRow = null;
string exactCollectionName = null;
// find the requested collection
versionFailure = false;
haveExactMatch = false;
haveMultipleInexactMatches = false;
foreach (DataRow row in metaDataCollectionsTable.Rows)
{
candidateCollectionName = row[collectionNameColumn, DataRowVersion.Current] as string;
if (ADP.IsEmpty(candidateCollectionName))
{
throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName);
}
if (ADP.CompareInsensitiveInvariant(candidateCollectionName, collectionName))
{
if (SupportedByCurrentVersion(row) == false)
{
versionFailure = true;
}
else
{
if (collectionName == candidateCollectionName)
{
if (haveExactMatch == true)
{
throw ADP.CollectionNameIsNotUnique(collectionName);
}
requestedCollectionRow = row;
exactCollectionName = candidateCollectionName;
haveExactMatch = true;
}
else
{
// have an inexact match - ok only if it is the only one
if (exactCollectionName != null)
{
// can't fail here becasue we may still find an exact match
haveMultipleInexactMatches = true;
}
requestedCollectionRow = row;
exactCollectionName = candidateCollectionName;
}
}
}
}
if (requestedCollectionRow == null)
{
if (versionFailure == false)
{
throw ADP.UndefinedCollection(collectionName);
}
else
{
throw ADP.UnsupportedVersion(collectionName);
}
}
if ((haveExactMatch == false) && (haveMultipleInexactMatches == true))
{
throw ADP.AmbigousCollectionName(collectionName);
}
return requestedCollectionRow;
}
private void FixUpVersion(DataTable dataSourceInfoTable)
{
Debug.Assert(dataSourceInfoTable.TableName == DbMetaDataCollectionNames.DataSourceInformation);
DataColumn versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion];
DataColumn normalizedVersionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersionNormalized];
if ((versionColumn == null) || (normalizedVersionColumn == null))
{
throw ADP.MissingDataSourceInformationColumn();
}
if (dataSourceInfoTable.Rows.Count != 1)
{
throw ADP.IncorrectNumberOfDataSourceInformationRows();
}
DataRow dataSourceInfoRow = dataSourceInfoTable.Rows[0];
dataSourceInfoRow[versionColumn] = _serverVersionString;
dataSourceInfoRow[normalizedVersionColumn] = _normalizedServerVersion;
dataSourceInfoRow.AcceptChanges();
}
private string GetParameterName(string neededCollectionName, int neededRestrictionNumber)
{
DataTable restrictionsTable = null;
DataColumnCollection restrictionColumns = null;
DataColumn collectionName = null;
DataColumn parameterName = null;
DataColumn restrictionName = null;
DataColumn restrictionNumber = null;
;
string result = null;
restrictionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.Restrictions];
if (restrictionsTable != null)
{
restrictionColumns = restrictionsTable.Columns;
if (restrictionColumns != null)
{
collectionName = restrictionColumns[_collectionName];
parameterName = restrictionColumns[_parameterName];
restrictionName = restrictionColumns[_restrictionName];
restrictionNumber = restrictionColumns[_restrictionNumber];
}
}
if ((parameterName == null) || (collectionName == null) || (restrictionName == null) || (restrictionNumber == null))
{
throw ADP.MissingRestrictionColumn();
}
foreach (DataRow restriction in restrictionsTable.Rows)
{
if (((string)restriction[collectionName] == neededCollectionName) &&
((int)restriction[restrictionNumber] == neededRestrictionNumber) &&
(SupportedByCurrentVersion(restriction)))
{
result = (string)restriction[parameterName];
break;
}
}
if (result == null)
{
throw ADP.MissingRestrictionRow();
}
return result;
}
public virtual DataTable GetSchema(DbConnection connection, string collectionName, string[] restrictions)
{
Debug.Assert(_metaDataCollectionsDataSet != null);
DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism];
DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName];
DataRow requestedCollectionRow = null;
DataTable requestedSchema = null;
string[] hiddenColumns;
string exactCollectionName = null;
requestedCollectionRow = FindMetaDataCollectionRow(collectionName);
exactCollectionName = requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string;
if (ADP.IsEmptyArray(restrictions) == false)
{
for (int i = 0; i < restrictions.Length; i++)
{
if ((restrictions[i] != null) && (restrictions[i].Length > 4096))
{
// use a non-specific error because no new beta 2 error messages are allowed
// TODO: will add a more descriptive error in RTM
throw ADP.NotSupported();
}
}
}
string populationMechanism = requestedCollectionRow[populationMechanismColumn, DataRowVersion.Current] as string;
switch (populationMechanism)
{
case _dataTable:
if (exactCollectionName == DbMetaDataCollectionNames.MetaDataCollections)
{
hiddenColumns = new string[2];
hiddenColumns[0] = _populationMechanism;
hiddenColumns[1] = _populationString;
}
else
{
hiddenColumns = null;
}
// none of the datatable collections support restrictions
if (ADP.IsEmptyArray(restrictions) == false)
{
throw ADP.TooManyRestrictions(exactCollectionName);
}
requestedSchema = CloneAndFilterCollection(exactCollectionName, hiddenColumns);
// TODO: Consider an alternate method that doesn't involve special casing -- perhaps _prepareCollection
// for the data source infomation table we need to fix up the version columns at run time
// since the version is determined at run time
if (exactCollectionName == DbMetaDataCollectionNames.DataSourceInformation)
{
FixUpVersion(requestedSchema);
}
break;
case _sqlCommand:
requestedSchema = ExecuteCommand(requestedCollectionRow, restrictions, connection);
break;
case _prepareCollection:
requestedSchema = PrepareCollection(exactCollectionName, restrictions, connection);
break;
default:
throw ADP.UndefinedPopulationMechanism(populationMechanism);
}
return requestedSchema;
}
private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNames)
{
bool result = true;
string sourceColumnName = sourceColumn.ColumnName;
switch (sourceColumnName)
{
case _minimumVersion:
case _maximumVersion:
result = false;
break;
default:
if (hiddenColumnNames == null)
{
break;
}
for (int i = 0; i < hiddenColumnNames.Length; i++)
{
if (hiddenColumnNames[i] == sourceColumnName)
{
result = false;
break;
}
}
break;
}
return result;
}
private void LoadDataSetFromXml(Stream XmlStream)
{
_metaDataCollectionsDataSet = new DataSet();
_metaDataCollectionsDataSet.Locale = System.Globalization.CultureInfo.InvariantCulture;
_metaDataCollectionsDataSet.ReadXml(XmlStream);
}
protected virtual DataTable PrepareCollection(string collectionName, string[] restrictions, DbConnection connection)
{
throw ADP.NotSupported();
}
private bool SupportedByCurrentVersion(DataRow requestedCollectionRow)
{
bool result = true;
DataColumnCollection tableColumns = requestedCollectionRow.Table.Columns;
DataColumn versionColumn;
object version;
// check the minimum version first
versionColumn = tableColumns[_minimumVersion];
if (versionColumn != null)
{
version = requestedCollectionRow[versionColumn];
if (version != null)
{
if (version != DBNull.Value)
{
if (0 > string.Compare(_normalizedServerVersion, (string)version, StringComparison.OrdinalIgnoreCase))
{
result = false;
}
}
}
}
// if the minmum version was ok what about the maximum version
if (result == true)
{
versionColumn = tableColumns[_maximumVersion];
if (versionColumn != null)
{
version = requestedCollectionRow[versionColumn];
if (version != null)
{
if (version != DBNull.Value)
{
if (0 < string.Compare(_normalizedServerVersion, (string)version, StringComparison.OrdinalIgnoreCase))
{
result = false;
}
}
}
}
}
return result;
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using OttoMail.Models;
namespace OttoMail.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20160518202500_FirstNameLastName")]
partial class FirstNameLastName
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("OttoMail.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<string>("FirstName");
b.Property<string>("LastName");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("OttoMail.Models.Email", b =>
{
b.Property<int>("EmailId")
.ValueGeneratedOnAdd();
b.Property<string>("Body");
b.Property<bool>("Checked");
b.Property<DateTime>("Date");
b.Property<bool>("Read");
b.Property<string>("Sender");
b.Property<string>("Subject");
b.Property<string>("UserId");
b.HasKey("EmailId");
b.HasAnnotation("Relational:TableName", "Emails");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("OttoMail.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("OttoMail.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("OttoMail.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("OttoMail.Models.Email", b =>
{
b.HasOne("OttoMail.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.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 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>
/// RoutesOperations operations.
/// </summary>
internal partial class RoutesOperations : IServiceOperations<NetworkClient>, IRoutesOperations
{
/// <summary>
/// Initializes a new instance of the RoutesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RoutesOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified route from a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified route from a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </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<Route>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (routeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("apiVersion", apiVersion);
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.Network/routeTables/{routeTableName}/routes/{routeName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
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 = Microsoft.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<Route>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_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>
/// Creates or updates a route in the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Parameters supplied to the create or update route operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Route>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<Route> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all routes in a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </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<IPage<Route>>> ListWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
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 = Microsoft.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<IPage<Route>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Route>>(_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>
/// Deletes the specified route from a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </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="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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (routeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", 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.Network/routeTables/{routeTableName}/routes/{routeName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
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("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route in the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Parameters supplied to the create or update route operation.
/// </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<Route>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (routeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeName");
}
if (routeParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeParameters");
}
if (routeParameters != null)
{
routeParameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("routeParameters", routeParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", 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.Network/routeTables/{routeTableName}/routes/{routeName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
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(routeParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(routeParameters, 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 = Microsoft.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<Route>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_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 all routes in a route table.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </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<IPage<Route>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
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 = Microsoft.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<IPage<Route>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Route>>(_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 (c) Contributors, http://aurora-sim.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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Web;
using OpenSim.Services.Interfaces;
using Aurora.Framework;
using Aurora.Framework.Servers.HttpServer;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using Aurora.DataManager;
using OpenMetaverse.StructuredData;
using System.Text;
namespace OpenSim.Services.CapsService
{
public class AssortedCAPS : ICapsServiceConnector
{
private IRegionClientCapsService m_service;
private IAgentInfoService m_agentInfoService;
private IAgentProcessing m_agentProcessing;
#region ICapsServiceConnector Members
public void RegisterCaps(IRegionClientCapsService service)
{
m_service = service;
m_agentInfoService = service.Registry.RequestModuleInterface<IAgentInfoService>();
m_agentProcessing = service.Registry.RequestModuleInterface<IAgentProcessing>();
HttpServerHandle method = delegate(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return ProcessUpdateAgentLanguage(request, m_service.AgentID);
};
service.AddStreamHandler("UpdateAgentLanguage", new GenericStreamHandler("POST", service.CreateCAPS("UpdateAgentLanguage", ""),
method));
method = delegate(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return ProcessUpdateAgentInfo(request, m_service.AgentID);
};
service.AddStreamHandler("UpdateAgentInformation", new GenericStreamHandler("POST", service.CreateCAPS("UpdateAgentInformation", ""),
method));
service.AddStreamHandler ("AvatarPickerSearch", new GenericStreamHandler ("GET", service.CreateCAPS("AvatarPickerSearch", ""),
ProcessAvatarPickerSearch));
method = delegate(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return HomeLocation(request, m_service.AgentID);
};
service.AddStreamHandler("HomeLocation", new GenericStreamHandler("POST", service.CreateCAPS("HomeLocation", ""),
method));
method = delegate(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return TeleportLocation(request, m_service.AgentID);
};
service.AddStreamHandler("TeleportLocation", new GenericStreamHandler("POST", service.CreateCAPS("TeleportLocation", ""),
method));
}
public void EnteringRegion()
{
}
public void DeregisterCaps()
{
m_service.RemoveStreamHandler ("UpdateAgentLanguage", "POST");
m_service.RemoveStreamHandler ("UpdateAgentInformation", "POST");
m_service.RemoveStreamHandler ("AvatarPickerSearch", "GET");
m_service.RemoveStreamHandler ("HomeLocation", "POST");
m_service.RemoveStreamHandler ("TeleportLocation", "POST");
}
#region Other CAPS
private byte[] HomeLocation(Stream request, UUID agentID)
{
OSDMap rm = (OSDMap)OSDParser.DeserializeLLSDXml(request);
OSDMap HomeLocation = rm["HomeLocation"] as OSDMap;
if (HomeLocation != null)
{
OSDMap pos = HomeLocation["LocationPos"] as OSDMap;
Vector3 position = new Vector3((float)pos["X"].AsReal(),
(float)pos["Y"].AsReal(),
(float)pos["Z"].AsReal());
OSDMap lookat = HomeLocation["LocationLookAt"] as OSDMap;
Vector3 lookAt = new Vector3((float)lookat["X"].AsReal(),
(float)lookat["Y"].AsReal(),
(float)lookat["Z"].AsReal());
//int locationID = HomeLocation["LocationId"].AsInteger();
m_agentInfoService.SetHomePosition(agentID.ToString(), m_service.Region.RegionID, position, lookAt);
}
rm.Add("success", OSD.FromBoolean(true));
return OSDParser.SerializeLLSDXmlBytes(rm);
}
private byte[] ProcessUpdateAgentLanguage(Stream request, UUID agentID)
{
OSDMap rm = OSDParser.DeserializeLLSDXml(request) as OSDMap;
if (rm == null)
return MainServer.BadRequest;
IAgentConnector AgentFrontend = DataManager.RequestPlugin<IAgentConnector>();
if (AgentFrontend != null)
{
IAgentInfo IAI = AgentFrontend.GetAgent(agentID);
if (IAI == null)
return MainServer.BadRequest;
IAI.Language = rm["language"].AsString();
IAI.LanguageIsPublic = int.Parse(rm["language_is_public"].AsString()) == 1;
AgentFrontend.UpdateAgent(IAI);
}
return MainServer.BlankResponse;
}
private byte[] ProcessAvatarPickerSearch(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
string amt = query.GetOne("page-size");
string name = query.GetOne("names");
List<UserAccount> accounts = m_service.Registry.RequestModuleInterface<IUserAccountService>().GetUserAccounts(m_service.ClientCaps.AccountInfo.AllScopeIDs, name, 0, uint.Parse(amt)) ??
new List<UserAccount>(0);
OSDMap body = new OSDMap();
OSDArray array = new OSDArray();
foreach (UserAccount account in accounts)
{
OSDMap map = new OSDMap();
map["agent_id"] = account.PrincipalID;
IUserProfileInfo profileInfo = DataManager.RequestPlugin<IProfileConnector>().GetUserProfile(account.PrincipalID);
map["display_name"] = (profileInfo == null || profileInfo.DisplayName == "") ? account.Name : profileInfo.DisplayName;
map["username"] = account.Name;
array.Add(map);
}
body["agents"] = array;
return OSDParser.SerializeLLSDXmlBytes(body);
}
private byte[] ProcessUpdateAgentInfo(Stream request, UUID agentID)
{
OSD r = OSDParser.DeserializeLLSDXml(request);
OSDMap rm = (OSDMap)r;
OSDMap access = (OSDMap)rm["access_prefs"];
string Level = access["max"].AsString();
int maxLevel = 0;
if (Level == "PG")
maxLevel = 0;
if (Level == "M")
maxLevel = 1;
if (Level == "A")
maxLevel = 2;
IAgentConnector data = DataManager.RequestPlugin<IAgentConnector>();
if (data != null)
{
IAgentInfo agent = data.GetAgent(agentID);
agent.MaturityRating = maxLevel;
data.UpdateAgent(agent);
}
return MainServer.BlankResponse;
}
private bool _isInTeleportCurrently = false;
private byte[] TeleportLocation (Stream request, UUID agentID)
{
OSDMap retVal = new OSDMap();
if (_isInTeleportCurrently)
{
retVal.Add("reason", "Duplicate teleport request.");
retVal.Add("success", OSD.FromBoolean(false));
return OSDParser.SerializeLLSDXmlBytes(retVal);
}
_isInTeleportCurrently = true;
OSDMap rm = (OSDMap)OSDParser.DeserializeLLSDXml(request);
OSDMap pos = rm["LocationPos"] as OSDMap;
Vector3 position = new Vector3((float)pos["X"].AsReal(),
(float)pos["Y"].AsReal(),
(float)pos["Z"].AsReal());
/*OSDMap lookat = rm["LocationLookAt"] as OSDMap;
Vector3 lookAt = new Vector3((float)lookat["X"].AsReal(),
(float)lookat["Y"].AsReal(),
(float)lookat["Z"].AsReal());*/
ulong RegionHandle = rm["RegionHandle"].AsULong();
const uint tpFlags = 16;
if (m_service.ClientCaps.GetRootCapsService().RegionHandle != m_service.RegionHandle)
{
retVal.Add("reason", "Contacted by non-root region for teleport. Protocol implemention is wrong.");
retVal.Add("success", OSD.FromBoolean(false));
return OSDParser.SerializeLLSDXmlBytes(retVal);
}
string reason = "";
int x, y;
Util.UlongToInts(RegionHandle, out x, out y);
GridRegion destination = m_service.Registry.RequestModuleInterface<IGridService>().GetRegionByPosition(
m_service.ClientCaps.AccountInfo.AllScopeIDs, x, y);
ISimulationService simService = m_service.Registry.RequestModuleInterface<ISimulationService>();
AgentData ad = new AgentData();
AgentCircuitData circuitData = null;
if (destination != null)
{
simService.RetrieveAgent(m_service.Region, m_service.AgentID, true, out ad, out circuitData);
if (ad != null)
{
ad.Position = position;
ad.Center = position;
circuitData.startpos = position;
}
}
if(destination == null || circuitData == null)
{
retVal.Add("reason", "Could not find the destination region.");
retVal.Add("success", OSD.FromBoolean(false));
return OSDParser.SerializeLLSDXmlBytes(retVal);
}
circuitData.reallyischild = false;
circuitData.child = false;
if (m_service.RegionHandle != destination.RegionHandle)
simService.MakeChildAgent(m_service.AgentID, m_service.Region.RegionID, destination, false);
if(m_agentProcessing.TeleportAgent(ref destination, tpFlags, ad == null ? 0 : (int)ad.Far, circuitData, ad,
m_service.AgentID, m_service.RegionHandle, out reason) || reason == "")
{
if (m_service.RegionHandle != destination.RegionHandle)
simService.MakeChildAgent(m_service.AgentID, m_service.Region.RegionID, destination, true);
retVal.Add("success", OSD.FromBoolean(true));
}
else
{
if (reason != "Already in a teleport")//If this error occurs... don't kick them out of their current region
simService.FailedToMoveAgentIntoNewRegion(m_service.AgentID, destination.RegionID);
retVal.Add("reason", reason);
retVal.Add("success", OSD.FromBoolean(false));
}
//Send back data
_isInTeleportCurrently = false;
return OSDParser.SerializeLLSDXmlBytes(retVal);
}
#endregion
#endregion
}
}
| |
// Copyright (c) The Mapsui authors.
// The Mapsui authors licensed this file under the MIT license.
// See the LICENSE file in the project root for full license information.
// This file was originally created by Morten Nielsen (www.iter.dk) as part of SharpMap
using System;
namespace Mapsui.Styles
{
/// <summary>
/// Defines a style used for rendering labels
/// </summary>
public class LabelStyle : Style
{
/// <summary>
/// Label text alignment
/// </summary>
public enum HorizontalAlignmentEnum : short
{
/// <summary>
/// Left oriented
/// </summary>
Left = 0,
/// <summary>
/// Right oriented
/// </summary>
Right = 2,
/// <summary>
/// Centered
/// </summary>
Center = 1
}
/// <summary>
/// Label text alignment
/// </summary>
public enum VerticalAlignmentEnum : short
{
/// <summary>
/// Left oriented
/// </summary>
Bottom = 2,
/// <summary>
/// Right oriented
/// </summary>
Top = 0,
/// <summary>
/// Centered
/// </summary>
Center = 1
}
public enum LineBreakMode : short
{
/// <summary>
/// Do not wrap text
/// </summary>
NoWrap,
/// <summary>
/// Wrap at character boundaries
/// </summary>
CharacterWrap,
/// <summary>
/// Truncate the head of text
/// </summary>
HeadTruncation,
/// <summary>
/// Truncate the middle of text. This may be done, for example, by replacing it with an ellipsis
/// </summary>
MiddleTruncation,
/// <summary>
/// Truncate the tail of text
/// </summary>
TailTruncation,
/// <summary>
/// Wrap at word boundaries
/// </summary>
WordWrap
}
public LabelStyle()
{
Font = new Font { FontFamily = "Verdana", Size = 12 };
Offset = new Offset { X = 0, Y = 0 };
CollisionDetection = false;
ForeColor = Color.Black;
BackColor = new Brush { Color = Color.White };
HorizontalAlignment = HorizontalAlignmentEnum.Center;
VerticalAlignment = VerticalAlignmentEnum.Center;
MaxWidth = 0;
LineHeight = 1.0;
WordWrap = LineBreakMode.NoWrap;
BorderColor = Color.Transparent;
BorderThickness = 1.0;
CornerRounding = 6;
}
public LabelStyle(LabelStyle labelStyle)
{
Font = new Font(labelStyle.Font);
Offset = new Offset(labelStyle.Offset);
CollisionDetection = false;
ForeColor = new Color(labelStyle.ForeColor);
BackColor = (labelStyle.BackColor == null) ? null : new Brush(labelStyle.BackColor);
HorizontalAlignment = HorizontalAlignmentEnum.Center;
VerticalAlignment = VerticalAlignmentEnum.Center;
MaxWidth = labelStyle.MaxWidth;
WordWrap = labelStyle.WordWrap;
LineHeight = labelStyle.LineHeight;
Text = labelStyle.Text;
LabelColumn = labelStyle.LabelColumn;
LabelMethod = labelStyle.LabelMethod;
Halo = labelStyle.Halo;
BorderColor = labelStyle.BorderColor;
BorderThickness = labelStyle.BorderThickness;
CornerRounding = labelStyle.CornerRounding;
}
/// <summary>
/// Label Font
/// </summary>
public Font Font { get; set; }
/// <summary>
/// Font color
/// </summary>
public Color ForeColor { get; set; }
/// <summary>
/// The background color of the label. Set to transparent brush or null if background isn't needed
/// </summary>
public Brush? BackColor { get; set; } // todo: rename
/// <summary>
/// The color of the border around the background.
/// </summary>
public Color BorderColor { get; set; }
/// <summary>
/// The thickness of the border around the background.
/// </summary>
public double BorderThickness { get; set; }
/// <summary>
/// The radius of the oval used to round the corners of the background. See <see cref="SkiaSharp.SkCanvas.DrawRoundRect"/>.
/// </summary>
public int CornerRounding { get; set; }
/// <summary>
/// Creates a halo around the text
/// </summary>
public Pen? Halo { get; set; }
/// <summary>
/// Specifies relative position of labels with respect to objects label point
/// </summary>
public Offset Offset { get; set; }
/// <summary>
/// Gets or sets whether Collision Detection is enabled for the labels.
/// If set to true, label collision will be tested.
/// </summary>
public bool CollisionDetection { get; set; }
/// <summary>
/// The horizontal alignment of the text in relation to the label point
/// </summary>
public HorizontalAlignmentEnum HorizontalAlignment { get; set; }
/// <summary>
/// The horizontal alignment of the text in relation to the label point
/// </summary>
public VerticalAlignmentEnum VerticalAlignment { get; set; }
/// <summary>
/// Maximum width of text in em. If text is wider than this, text is shorten or
/// word wrapped regarding WordWrap.
/// </summary>
public double MaxWidth { get; set; }
/// <summary>
/// Line break mode for text, if width is bigger than MaxWidth
/// </summary>
public LineBreakMode WordWrap { get; set; }
/// <summary>
/// Space from one text line to next text line in em
/// </summary>
public double LineHeight { get; set; }
/// <summary>The text used for this specific label.</summary>
/// <remarks>Used only when LabelColumn and LabelMethod are not set.</remarks>
public string? Text { private get; set; }
/// <summary>The column of the feature used by GetLabelText to return the label text.</summary>
/// <remarks>Used only when LabelMethod is not set. Overrides use of the Text field.</remarks>
public string? LabelColumn { get; set; }
/// <summary>Method used by GetLabelText to return the label text.</summary>
/// <remarks>Overrides use of Text and LabelColumn fields.</remarks>
public Func<IFeature, string?>? LabelMethod { get; set; }
/// <summary>The text used for this specific label.</summary>
public string? GetLabelText(IFeature feature)
{
if (LabelMethod != null) return LabelMethod(feature);
if (LabelColumn != null) return feature[LabelColumn]?.ToString();
return Text;
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace ForkEditor
{
/// <summary>
/// Summary description for TextureAtlas.
/// </summary>
public class TextureAtlas : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox txtAtlas;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.TextBox txtPrefix;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnCompile;
private ArrayList BMPS;
public TextureAtlas(ArrayList BitmapList)
{
BMPS = BitmapList;
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtAtlas = new System.Windows.Forms.TextBox();
this.txtPrefix = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnCompile = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// txtAtlas
//
this.txtAtlas.AcceptsReturn = true;
this.txtAtlas.AcceptsTab = true;
this.txtAtlas.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(204)), ((System.Byte)(209)), ((System.Byte)(247)));
this.txtAtlas.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtAtlas.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtAtlas.Location = new System.Drawing.Point(8, 24);
this.txtAtlas.Multiline = true;
this.txtAtlas.Name = "txtAtlas";
this.txtAtlas.ReadOnly = true;
this.txtAtlas.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtAtlas.Size = new System.Drawing.Size(472, 424);
this.txtAtlas.TabIndex = 0;
this.txtAtlas.Text = "";
//
// txtPrefix
//
this.txtPrefix.Location = new System.Drawing.Point(64, 8);
this.txtPrefix.Name = "txtPrefix";
this.txtPrefix.Size = new System.Drawing.Size(88, 20);
this.txtPrefix.TabIndex = 1;
this.txtPrefix.Text = "guiTexAt_";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(40, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Prefix";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.txtAtlas);
this.groupBox1.Location = new System.Drawing.Point(8, 64);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(496, 456);
this.groupBox1.TabIndex = 3;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Solution";
//
// btnCompile
//
this.btnCompile.Location = new System.Drawing.Point(440, 8);
this.btnCompile.Name = "btnCompile";
this.btnCompile.Size = new System.Drawing.Size(64, 24);
this.btnCompile.TabIndex = 4;
this.btnCompile.Text = "Compile";
this.btnCompile.Click += new System.EventHandler(this.btnCompile_Click);
//
// TextureAtlas
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(512, 526);
this.Controls.Add(this.btnCompile);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtPrefix);
this.Name = "TextureAtlas";
this.Text = "TextureAtlas";
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void WriteLine(string l)
{
/*
if(txtAtlas.Lines == null)
{
txtAtlas.Text = l;
}
string[] L = txtAtlas.Lines;
string[] N = new string[L.Length + 1];
for(int k = 0; k < L.Length; k++)
N[k] = L[k];
N[L.Length] = l;
*/
txtAtlas.AppendText(l + ("" + (char)13 + (char)10));
}
private void BeginAtlasPage(string filename)
{
WriteLine("tex2d { ");
WriteLine(" filename : \""+filename+"\"");
WriteLine(" env : \"replace\"");
WriteLine(" magfilter : \"linear\"");
WriteLine(" minfilter : \"linear\"");
WriteLine(" wrapt : \"clampedge\"");
WriteLine(" wraps : \"clampedge\"");
}
private void WriteAtlasEntry(string name, int x, int y, int w, int h, int Page)
{
double dX = x / (double) Page;
double dY = y / (double) Page;
double dW = w / (double) Page;
double dH = h / (double) Page;
WriteLine(" sub { handle : \""+name+"\" region : <"+dX+","+dY+","+dW+","+dH+"> }");
}
private void EndAtlasPage()
{
WriteLine("}");
}
private void ExtractSolution(Algo.BoxPacking BP, int cnt)
{
BeginAtlasPage(txtPrefix.Text + cnt + "_png.pix");
ArrayList Solution = BP.FilloutBoxRandomly(1024, 1024);
Bitmap B = new Bitmap(1024, 1024, PixelFormat.Format32bppArgb);
Graphics G = Graphics.FromImage(B);
G.Clear(Color.Transparent);
foreach(Algo.BoxPacking.Box bmp in Solution)
{
Bitmap L = new Bitmap(bmp.BMP);
WriteAtlasEntry(bmp.BMP, bmp.X, bmp.Y, bmp.Width, bmp.Height, 1024);
G.DrawImageUnscaled(L, bmp.X, bmp.Y, bmp.Width, bmp.Height);
BP.RemoveBox(bmp.BMP);
}
B.Save(txtPrefix.Text + cnt + ".png", ImageFormat.Png);
EndAtlasPage();
}
private void btnCompile_Click(object sender, System.EventArgs e)
{
Algo.BoxPacking BP = new Algo.BoxPacking();
foreach(string x in BMPS)
{
try
{
Bitmap X = new Bitmap(x);
BP.AddBox(X.Width, X.Height, x);
X.Dispose();
}
catch(Exception ee)
{
MessageBox.Show("Error Reading: " + x);
}
}
int S = 1;
while(BP.Size() > 0)
{
ExtractSolution(BP, S);
S++;
}
}
}
}
| |
namespace Nancy.Tests.Unit.ViewEngines
{
using System.Collections.Generic;
using System.Linq;
using FakeItEasy;
using Nancy.ViewEngines;
using Xunit;
using Xunit.Extensions;
public class DefaultViewLocatorFixture
{
private readonly ViewLocationResult viewLocation;
private readonly DefaultViewLocator viewLocator;
public DefaultViewLocatorFixture()
{
this.viewLocation = new ViewLocationResult("location", "view", "html", null);
this.viewLocator = CreateViewLocator();
}
[Fact]
public void Should_return_null_if_locate_view_is_invoked_with_null_view_name()
{
// Given
string viewName = null;
// When
var result = this.viewLocator.LocateView(viewName, null);
// Then
result.ShouldBeNull();
}
[Fact]
public void Should_return_null_if_locate_view_is_invoked_with_empty_view_name()
{
// Given
var viewName = string.Empty;
// When
var result = this.viewLocator.LocateView(viewName, null);
// Then
result.ShouldBeNull();
}
[Fact]
public void Should_locate_view_when_only_name_is_provided()
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", string.Empty, () => null);
var locator = CreateViewLocator(expectedView);
// When
var result = locator.LocateView("index", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Theory]
[InlineData("INDEX")]
[InlineData("InDEx")]
public void Should_ignore_case_when_locating_view_based_on_name(string viewName)
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", string.Empty, () => null);
var locator = CreateViewLocator(expectedView);
// When
var result = locator.LocateView(viewName, null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_throw_ambiguousviewsexception_when_locating_view_by_name_returns_multiple_results()
{
// Given
var expectedView1 = new ViewLocationResult(string.Empty, "index", string.Empty, () => null);
var expectedView2 = new ViewLocationResult(string.Empty, "index", string.Empty, () => null);
var locator = CreateViewLocator(expectedView1, expectedView2);
// When
var exception = Record.Exception(() => locator.LocateView("index", null));
// Then
exception.ShouldBeOfType<AmbiguousViewsException>();
}
[Fact]
public void Should_throw_ambiguousviewsexception_when_locating_view_by_name_and_multiple_views_share_the_same_name_and_location_but_different_extensions()
{
// Given
var expectedView1 = new ViewLocationResult(string.Empty, "index", "spark", () => null);
var expectedView2 = new ViewLocationResult(string.Empty, "index", "html", () => null);
var locator = CreateViewLocator(expectedView1, expectedView2);
// When
var exception = Record.Exception(() => locator.LocateView("index", null));
// Then
exception.ShouldBeOfType<AmbiguousViewsException>();
}
[Fact]
public void Should_set_message_on_ambiguousviewexception()
{
// Given
var expectedView1 = new ViewLocationResult(string.Empty, "index", "spark", () => null);
var expectedView2 = new ViewLocationResult(string.Empty, "index", "html", () => null);
var locator = CreateViewLocator(expectedView1, expectedView2);
const string expectedMessage = "This exception was thrown because multiple views were found. 2 view(s):\r\n\t/index.spark\r\n\t/index.html";
// When
var exception = Record.Exception(() => locator.LocateView("index", null));
// Then
exception.Message.ShouldEqual(expectedMessage);
}
[Fact]
public void Should_return_null_when_view_cannot_be_located_using_name()
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", string.Empty, () => null);
var locator = CreateViewLocator(expectedView);
// When
var result = locator.LocateView("main", null);
// Then
result.ShouldBeNull();
}
[Fact]
public void Should_locate_view_when_name_and_extension_are_provided()
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", "cshtml", () => null);
var locator = CreateViewLocator(expectedView);
// When
var result = locator.LocateView("index.cshtml", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Theory]
[InlineData("INDEX.CSHTML")]
[InlineData("InDEx.csHTml")]
public void Should_ignore_case_when_locating_view_based_on_name_and_extension(string viewName)
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", "cshtml", () => null);
var locator = CreateViewLocator(expectedView);
// When
var result = locator.LocateView(viewName, null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_return_null_when_view_cannot_be_located_using_name_and_extension()
{
// Given
var expectedView = new ViewLocationResult(string.Empty, "index", "spark", () => null);
var locator = CreateViewLocator(expectedView);
// When
var result = locator.LocateView("index.cshtml", null);
// Then
result.ShouldBeNull();
}
[Fact]
public void Should_locate_view_when_name_extension_and_location_are_provided()
{
// Given
var expectedView = new ViewLocationResult("views/sub", "index", "cshtml", () => null);
var locator = CreateViewLocator(expectedView);
// When
var result = locator.LocateView("views/sub/index.cshtml", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Theory]
[InlineData("VIEWS/SUB/INDEX.CSHTML")]
[InlineData("viEWS/sUb/InDEx.csHTml")]
public void Should_ignore_case_when_locating_view_based_on_name_extension_and_location(string viewName)
{
// Given
var expectedView = new ViewLocationResult("views/sub", "index", "cshtml", () => null);
var locator = CreateViewLocator(expectedView);
// When
var result = locator.LocateView(viewName, null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_return_null_when_view_cannot_be_located_using_name_extension_and_location()
{
// Given
var expectedView = new ViewLocationResult("views/sub", "index", "spark", () => null);
var locator = CreateViewLocator(expectedView);
// When
var result = locator.LocateView("views/feature/index.cshtml", null);
// Then
result.ShouldBeNull();
}
[Fact]
public void Should_be_able_to_locate_view_by_name_when_two_views_with_same_name_exists_at_different_locations()
{
// Given
var expectedView = new ViewLocationResult("views/sub", "index", string.Empty, () => null);
var additionalView = new ViewLocationResult("views", "index", string.Empty, () => null);
var locator = CreateViewLocator(expectedView, additionalView);
// When
var result = locator.LocateView("views/sub/index", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_be_able_to_locate_view_by_name_and_extension_when_two_view_with_same_name_but_different_extensions_exists_in_the_same_location()
{
// Given
var expectedView = new ViewLocationResult("views", "index", "cshtml", () => null);
var additionalView = new ViewLocationResult("views", "index", "spark", () => null);
var locator = CreateViewLocator(expectedView, additionalView);
// When
var result = locator.LocateView("views/index.cshtml", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_be_able_to_locate_view_by_name_when_two_views_with_same_name_and_extension_exists_at_different_locations()
{
// Given
var expectedView = new ViewLocationResult("views/sub", "index", "cshtml", () => null);
var additionalView = new ViewLocationResult("views", "index", "spark", () => null);
var locator = CreateViewLocator(expectedView, additionalView);
// When
var result = locator.LocateView("views/sub/index.cshtml", null);
// Then
result.ShouldBeSameAs(expectedView);
}
[Fact]
public void Should_be_able_to_locate_view_by_name_when_the_viewname_occures_in_the_location()
{
// Given
var expectedView = new ViewLocationResult( "views/hello", "hello", "cshtml", () => null );
//var additionalView = new ViewLocationResult( "views", "index", "spark", () => null );
var locator = CreateViewLocator(expectedView);
// When
var result = locator.LocateView( "views/hello/hello", null );
// Then
result.ShouldBeSameAs( expectedView );
}
[Fact]
public void Should_get_located_views_from_view_location_providers_with_available_extensions_when_created()
{
// Given
var viewEngine1 = A.Fake<IViewEngine>();
A.CallTo(() => viewEngine1.Extensions).Returns(new[] { "html" });
var viewEngine2 = A.Fake<IViewEngine>();
A.CallTo(() => viewEngine2.Extensions).Returns(new[] { "spark" });
var viewLocationProvider = A.Fake<IViewLocationProvider>();
var expectedViewEngineExtensions = new[] { "html", "spark" };
var viewEngine = A.Fake<IViewEngine>();
A.CallTo(() => viewEngine.Extensions).Returns(expectedViewEngineExtensions);
// When
new DefaultViewLocator(viewLocationProvider, new[] { viewEngine });
// Then
A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>.That.Matches(
x => x.All(expectedViewEngineExtensions.Contains)))).MustHaveHappened();
}
private static DefaultViewLocator CreateViewLocator(params ViewLocationResult[] results)
{
var viewLocationProvider = A.Fake<IViewLocationProvider>();
A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._))
.Returns(results);
var viewEngine = A.Fake<IViewEngine>();
A.CallTo(() => viewEngine.Extensions).Returns(new[] { "liquid" });
var viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine });
return viewLocator;
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using Mono.Cecil.Cil;
using NUnit.Framework;
using Mono.Cecil.PE;
namespace Mono.Cecil.Tests {
public abstract class BaseTestFixture {
protected static void IgnoreOnMono ()
{
if (Platform.OnMono)
Assert.Ignore ();
}
public static string GetResourcePath (string name, Assembly assembly)
{
return Path.Combine (FindResourcesDirectory (assembly), name);
}
public static string GetAssemblyResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("assemblies", name), assembly);
}
public static string GetCSharpResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("cs", name), assembly);
}
public static string GetILResourcePath (string name, Assembly assembly)
{
return GetResourcePath (Path.Combine ("il", name), assembly);
}
public ModuleDefinition GetResourceModule (string name)
{
return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, GetType ().Assembly));
}
public ModuleDefinition GetResourceModule (string name, ReaderParameters parameters)
{
return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, GetType ().Assembly), parameters);
}
public ModuleDefinition GetResourceModule (string name, ReadingMode mode)
{
return ModuleDefinition.ReadModule (GetAssemblyResourcePath (name, GetType ().Assembly), new ReaderParameters (mode));
}
internal Image GetResourceImage (string name)
{
using (var fs = new FileStream (GetAssemblyResourcePath (name, GetType ().Assembly), FileMode.Open, FileAccess.Read))
return ImageReader.ReadImageFrom (fs);
}
public ModuleDefinition GetCurrentModule ()
{
return ModuleDefinition.ReadModule (GetType ().Module.FullyQualifiedName);
}
public ModuleDefinition GetCurrentModule (ReaderParameters parameters)
{
return ModuleDefinition.ReadModule (GetType ().Module.FullyQualifiedName, parameters);
}
public static string FindResourcesDirectory (Assembly assembly)
{
var path = Path.GetDirectoryName (new Uri (assembly.CodeBase).LocalPath);
while (!Directory.Exists (Path.Combine (path, "Resources"))) {
var old = path;
path = Path.GetDirectoryName (path);
Assert.AreNotEqual (old, path);
}
return Path.Combine (path, "Resources");
}
public static void TestModule (string file, Action<ModuleDefinition> test, bool verify = true, bool readOnly = false, Type symbolReaderProvider = null, Type symbolWriterProvider = null, IAssemblyResolver assemblyResolver = null)
{
Run (new ModuleTestCase (file, test, verify, readOnly, symbolReaderProvider, symbolWriterProvider, assemblyResolver));
}
public static void TestCSharp (string file, Action<ModuleDefinition> test, bool verify = true, bool readOnly = false, Type symbolReaderProvider = null, Type symbolWriterProvider = null, IAssemblyResolver assemblyResolver = null)
{
Run (new CSharpTestCase (file, test, verify, readOnly, symbolReaderProvider, symbolWriterProvider, assemblyResolver));
}
public static void TestIL (string file, Action<ModuleDefinition> test, bool verify = true, bool readOnly = false, Type symbolReaderProvider = null, Type symbolWriterProvider = null, IAssemblyResolver assemblyResolver = null)
{
Run (new ILTestCase (file, test, verify, readOnly, symbolReaderProvider, symbolWriterProvider, assemblyResolver));
}
private static void Run (TestCase testCase)
{
var runner = new TestRunner (testCase, TestCaseType.ReadDeferred);
runner.RunTest ();
runner = new TestRunner (testCase, TestCaseType.ReadImmediate);
runner.RunTest ();
if (testCase.ReadOnly)
return;
runner = new TestRunner (testCase, TestCaseType.WriteFromDeferred);
runner.RunTest();
runner = new TestRunner (testCase, TestCaseType.WriteFromImmediate);
runner.RunTest();
}
}
abstract class TestCase {
public readonly bool Verify;
public readonly bool ReadOnly;
public readonly Type SymbolReaderProvider;
public readonly Type SymbolWriterProvider;
public readonly IAssemblyResolver AssemblyResolver;
public readonly Action<ModuleDefinition> Test;
public abstract string ModuleLocation { get; }
protected Assembly Assembly { get { return Test.Method.Module.Assembly; } }
protected TestCase (Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider, IAssemblyResolver assemblyResolver)
{
Test = test;
Verify = verify;
ReadOnly = readOnly;
SymbolReaderProvider = symbolReaderProvider;
SymbolWriterProvider = symbolWriterProvider;
AssemblyResolver = assemblyResolver;
}
}
class ModuleTestCase : TestCase {
public readonly string Module;
public ModuleTestCase (string module, Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider, IAssemblyResolver assemblyResolver)
: base (test, verify, readOnly, symbolReaderProvider, symbolWriterProvider, assemblyResolver)
{
Module = module;
}
public override string ModuleLocation
{
get { return BaseTestFixture.GetAssemblyResourcePath (Module, Assembly); }
}
}
class CSharpTestCase : TestCase {
public readonly string File;
public CSharpTestCase (string file, Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider, IAssemblyResolver assemblyResolver)
: base (test, verify, readOnly, symbolReaderProvider, symbolWriterProvider, assemblyResolver)
{
File = file;
}
public override string ModuleLocation
{
get
{
return CompilationService.CompileResource (BaseTestFixture.GetCSharpResourcePath (File, Assembly));
}
}
}
class ILTestCase : TestCase {
public readonly string File;
public ILTestCase (string file, Action<ModuleDefinition> test, bool verify, bool readOnly, Type symbolReaderProvider, Type symbolWriterProvider, IAssemblyResolver assemblyResolver)
: base (test, verify, readOnly, symbolReaderProvider, symbolWriterProvider, assemblyResolver)
{
File = file;
}
public override string ModuleLocation
{
get
{
return CompilationService.CompileResource (BaseTestFixture.GetILResourcePath (File, Assembly)); ;
}
}
}
class TestRunner {
readonly TestCase test_case;
readonly TestCaseType type;
public TestRunner (TestCase testCase, TestCaseType type)
{
this.test_case = testCase;
this.type = type;
}
ModuleDefinition GetModule ()
{
var location = test_case.ModuleLocation;
var parameters = new ReaderParameters {
SymbolReaderProvider = GetSymbolReaderProvider (),
AssemblyResolver = GetAssemblyResolver (),
};
switch (type) {
case TestCaseType.ReadImmediate:
parameters.ReadingMode = ReadingMode.Immediate;
return ModuleDefinition.ReadModule (location, parameters);
case TestCaseType.ReadDeferred:
parameters.ReadingMode = ReadingMode.Deferred;
return ModuleDefinition.ReadModule (location, parameters);
case TestCaseType.WriteFromImmediate:
parameters.ReadingMode = ReadingMode.Immediate;
return RoundTrip (location, parameters, "cecil-irt");
case TestCaseType.WriteFromDeferred:
parameters.ReadingMode = ReadingMode.Deferred;
return RoundTrip (location, parameters, "cecil-drt");
default:
return null;
}
}
ISymbolReaderProvider GetSymbolReaderProvider ()
{
if (test_case.SymbolReaderProvider == null)
return null;
return (ISymbolReaderProvider) Activator.CreateInstance (test_case.SymbolReaderProvider);
}
ISymbolWriterProvider GetSymbolWriterProvider ()
{
if (test_case.SymbolReaderProvider == null)
return null;
return (ISymbolWriterProvider) Activator.CreateInstance (test_case.SymbolWriterProvider);
}
IAssemblyResolver GetAssemblyResolver ()
{
if (test_case.AssemblyResolver != null)
return test_case.AssemblyResolver;
var resolver = new DefaultAssemblyResolver ();
var directory = Path.GetDirectoryName (test_case.ModuleLocation);
resolver.AddSearchDirectory (directory);
return resolver;
}
ModuleDefinition RoundTrip (string location, ReaderParameters reader_parameters, string folder)
{
var module = ModuleDefinition.ReadModule (location, reader_parameters);
var rt_folder = Path.Combine (Path.GetTempPath (), folder);
if (!Directory.Exists (rt_folder))
Directory.CreateDirectory (rt_folder);
var rt_module = Path.Combine (rt_folder, Path.GetFileName (location));
var writer_parameters = new WriterParameters {
SymbolWriterProvider = GetSymbolWriterProvider (),
};
test_case.Test (module);
module.Write (rt_module, writer_parameters);
if (test_case.Verify)
CompilationService.Verify (rt_module);
return ModuleDefinition.ReadModule (rt_module, reader_parameters);
}
public void RunTest ()
{
var module = GetModule ();
if (module == null)
return;
test_case.Test(module);
}
}
enum TestCaseType {
ReadImmediate,
ReadDeferred,
WriteFromImmediate,
WriteFromDeferred,
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UptimeCalculator
{
public partial class UptimeMathTests
{
[TestMethod]
public void Calculate_NoDowntime()
{
var now = DateTimeOffset.Now;
var period = new Interval(now.AddDays(-30), now);
var data = new UptimeData();
var uptime = UptimeMath.Calculate(period, data);
Assert.AreEqual(1.0, uptime.PercentUptime);
Assert.AreEqual(period.TimeSpan, uptime.TotalTime);
Assert.AreEqual(0.0, uptime.PercentDowntime);
Assert.AreEqual(TimeSpan.Zero, uptime.TotalDowntime);
Assert.AreEqual(0, uptime.DowntimeCount);
Assert.AreEqual(TimeSpan.Zero, uptime.LongestDowntime);
Assert.AreEqual(TimeSpan.Zero, uptime.ShortestDowntime);
Assert.AreEqual(TimeSpan.Zero, uptime.AverageDowntime);
}
[TestMethod]
public void Calculate_CompleteDowntime()
{
var now = DateTimeOffset.Now;
var period = new Interval(now.AddDays(-30), now);
var data = new UptimeData();
data.Downtimes = new List<Interval>()
{
new Interval(period.Start, period.End)
};
var uptime = UptimeMath.Calculate(period, data);
Assert.AreEqual(0.0, uptime.PercentUptime);
Assert.AreEqual(1.0, uptime.PercentDowntime);
Assert.AreEqual(period.TimeSpan, uptime.TotalTime);
Assert.AreEqual(period.TimeSpan, uptime.TotalDowntime);
Assert.AreEqual(1, uptime.DowntimeCount);
Assert.AreEqual(period.TimeSpan, uptime.LongestDowntime);
Assert.AreEqual(period.TimeSpan, uptime.ShortestDowntime);
Assert.AreEqual(period.TimeSpan, uptime.AverageDowntime);
}
[TestMethod]
public void Calculate_MultipleDowntimesCompleteExclusion()
{
var now = DateTimeOffset.Now;
var period = new Interval(now.AddDays(-30), now);
var data = new UptimeData();
data.Downtimes = new List<Interval>()
{
new Interval(now.AddHours(-52), now.AddHours(-51)),
new Interval(now.AddHours(-20), now.AddHours(-18)),
new Interval(now.AddHours(-53), now.AddHours(-51.5))
};
data.Exclusions = new List<Interval>()
{
period
};
var uptime = UptimeMath.Calculate(period, data);
Assert.AreEqual(1.0, uptime.PercentUptime);
Assert.AreEqual(0.0, uptime.PercentDowntime);
Assert.AreEqual(period.TimeSpan, uptime.TotalTime);
Assert.AreEqual(TimeSpan.Zero, uptime.TotalDowntime);
Assert.AreEqual(0, uptime.DowntimeCount);
Assert.AreEqual(TimeSpan.Zero, uptime.LongestDowntime);
Assert.AreEqual(TimeSpan.Zero, uptime.ShortestDowntime);
Assert.AreEqual(TimeSpan.Zero, uptime.AverageDowntime);
}
[TestMethod]
public void Calculate_SingleDowntime()
{
var now = DateTimeOffset.Now;
var period = new Interval(now.AddDays(-30), now);
var data = new UptimeData();
data.Downtimes = new List<Interval>()
{
new Interval(now.AddHours(-52), now.AddHours(-51))
};
var uptime = UptimeMath.Calculate(period, data);
AssertHelpers.AreClose((period.TimeSpan.TotalSeconds - TimeSpan.FromHours(1).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentUptime, 0.00001);
AssertHelpers.AreClose(1 - (period.TimeSpan.TotalSeconds - TimeSpan.FromHours(1).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentDowntime, 0.00001);
Assert.AreEqual(period.TimeSpan, uptime.TotalTime);
Assert.AreEqual(TimeSpan.FromHours(1), uptime.TotalDowntime);
Assert.AreEqual(1, uptime.DowntimeCount);
Assert.AreEqual(TimeSpan.FromHours(1), uptime.LongestDowntime);
Assert.AreEqual(TimeSpan.FromHours(1), uptime.ShortestDowntime);
Assert.AreEqual(TimeSpan.FromHours(1), uptime.AverageDowntime);
}
[TestMethod]
public void Calculate_MultipleDowntimes()
{
var now = DateTimeOffset.Now;
var period = new Interval(now.AddDays(-30), now);
var data = new UptimeData();
data.Downtimes = new List<Interval>()
{
new Interval(now.AddHours(-52), now.AddHours(-51)),
new Interval(now.AddHours(-20), now.AddHours(-18)),
new Interval(now.AddHours(-53), now.AddHours(-51.5)),
new Interval(now.AddDays(-60), now.AddDays(-59)),
new Interval(now.AddDays(59), now.AddDays(60))
};
var uptime = UptimeMath.Calculate(period, data);
AssertHelpers.AreClose((period.TimeSpan.TotalSeconds - TimeSpan.FromHours(4).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentUptime, 0.00001);
AssertHelpers.AreClose(1 - (period.TimeSpan.TotalSeconds - TimeSpan.FromHours(4).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentDowntime, 0.00001);
Assert.AreEqual(period.TimeSpan, uptime.TotalTime);
Assert.AreEqual(TimeSpan.FromHours(4), uptime.TotalDowntime);
Assert.AreEqual(2, uptime.DowntimeCount);
Assert.AreEqual(TimeSpan.FromHours(2), uptime.LongestDowntime);
Assert.AreEqual(TimeSpan.FromHours(2), uptime.ShortestDowntime);
Assert.AreEqual(TimeSpan.FromHours(2), uptime.AverageDowntime);
}
[TestMethod]
public void Calculate_MultipleDowntimesSingleDowntimeOutOfBounds()
{
var now = DateTimeOffset.Now;
var period = new Interval(now.AddDays(-30), now);
var data = new UptimeData();
data.Downtimes = new List<Interval>()
{
new Interval(now.AddHours(-52), now.AddHours(-51)),
new Interval(now.AddHours(-20), now.AddHours(-18)),
new Interval(now.AddHours(-53), now.AddHours(-51.5)),
new Interval(now.AddDays(-32), now.AddDays(-31))
};
var uptime = UptimeMath.Calculate(period, data);
AssertHelpers.AreClose((period.TimeSpan.TotalSeconds - TimeSpan.FromHours(4).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentUptime, 0.00001);
AssertHelpers.AreClose(1 - (period.TimeSpan.TotalSeconds - TimeSpan.FromHours(4).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentDowntime, 0.00001);
Assert.AreEqual(period.TimeSpan, uptime.TotalTime);
Assert.AreEqual(TimeSpan.FromHours(4), uptime.TotalDowntime);
Assert.AreEqual(2, uptime.DowntimeCount);
Assert.AreEqual(TimeSpan.FromHours(2), uptime.LongestDowntime);
Assert.AreEqual(TimeSpan.FromHours(2), uptime.ShortestDowntime);
Assert.AreEqual(TimeSpan.FromHours(2), uptime.AverageDowntime);
}
[TestMethod]
public void Calculate_SingleDowntimeSingleExclusionNoOverlap()
{
var now = DateTimeOffset.Now;
var period = new Interval(now.AddDays(-30), now);
var data = new UptimeData();
data.Downtimes = new List<Interval>()
{
new Interval(now.AddHours(-52), now.AddHours(-51))
};
data.Exclusions = new List<Interval>()
{
new Interval(now.AddHours(-62), now.AddHours(-61))
};
var uptime = UptimeMath.Calculate(period, data);
AssertHelpers.AreClose((period.TimeSpan.TotalSeconds - TimeSpan.FromHours(1).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentUptime, 0.00001);
AssertHelpers.AreClose(1 - (period.TimeSpan.TotalSeconds - TimeSpan.FromHours(1).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentDowntime, 0.00001);
Assert.AreEqual(period.TimeSpan, uptime.TotalTime);
Assert.AreEqual(TimeSpan.FromHours(1), uptime.TotalDowntime);
Assert.AreEqual(1, uptime.DowntimeCount);
Assert.AreEqual(TimeSpan.FromHours(1), uptime.LongestDowntime);
Assert.AreEqual(TimeSpan.FromHours(1), uptime.ShortestDowntime);
Assert.AreEqual(TimeSpan.FromHours(1), uptime.AverageDowntime);
}
[TestMethod]
public void Calculate_SingleDowntimeSingleExclusionOverlap()
{
var now = DateTimeOffset.Now;
var period = new Interval(now.AddDays(-30), now);
var data = new UptimeData();
data.Downtimes = new List<Interval>()
{
new Interval(now.AddHours(-52), now.AddHours(-51))
};
data.Exclusions = new List<Interval>()
{
new Interval(now.AddHours(-52.5), now.AddHours(-51.5))
};
var uptime = UptimeMath.Calculate(period, data);
AssertHelpers.AreClose((period.TimeSpan.TotalSeconds - TimeSpan.FromHours(.5).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentUptime, 0.00001);
AssertHelpers.AreClose(1 - (period.TimeSpan.TotalSeconds - TimeSpan.FromHours(.5).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentDowntime, 0.00001);
Assert.AreEqual(period.TimeSpan, uptime.TotalTime);
Assert.AreEqual(TimeSpan.FromHours(.5), uptime.TotalDowntime);
Assert.AreEqual(1, uptime.DowntimeCount);
Assert.AreEqual(TimeSpan.FromHours(.5), uptime.LongestDowntime);
Assert.AreEqual(TimeSpan.FromHours(.5), uptime.ShortestDowntime);
Assert.AreEqual(TimeSpan.FromHours(.5), uptime.AverageDowntime);
}
[TestMethod]
public void Calculate_MultipleDowntimesSingleExclusionOverlap()
{
var now = DateTimeOffset.Now;
var period = new Interval(now.AddDays(-30), now);
var data = new UptimeData();
data.Downtimes = new List<Interval>()
{
new Interval(now.AddHours(-52), now.AddHours(-51)),
new Interval(now.AddHours(-54), now.AddHours(-51.5))
};
data.Exclusions = new List<Interval>()
{
new Interval(now.AddHours(-52.5), now.AddHours(-51.5))
};
var uptime = UptimeMath.Calculate(period, data);
AssertHelpers.AreClose((period.TimeSpan.TotalSeconds - TimeSpan.FromHours(2).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentUptime, 0.00001);
AssertHelpers.AreClose(1 - (period.TimeSpan.TotalSeconds - TimeSpan.FromHours(2).TotalSeconds) / period.TimeSpan.TotalSeconds, uptime.PercentDowntime, 0.00001);
Assert.AreEqual(period.TimeSpan, uptime.TotalTime);
Assert.AreEqual(TimeSpan.FromHours(2), uptime.TotalDowntime);
Assert.AreEqual(2, uptime.DowntimeCount);
Assert.AreEqual(TimeSpan.FromHours(1.5), uptime.LongestDowntime);
Assert.AreEqual(TimeSpan.FromHours(.5), uptime.ShortestDowntime);
Assert.AreEqual(TimeSpan.FromHours(1), uptime.AverageDowntime);
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using Mono.Addins;
namespace OpenSim.Framework
{
/// <summary>
/// Exception thrown if an incorrect number of plugins are loaded
/// </summary>
public class PluginConstraintViolatedException : Exception
{
public PluginConstraintViolatedException () : base() {}
public PluginConstraintViolatedException (string msg) : base(msg) {}
public PluginConstraintViolatedException (string msg, Exception e) : base(msg, e) {}
}
/// <summary>
/// Classes wishing to impose constraints on plugin loading must implement
/// this class and pass it to PluginLoader AddConstraint()
/// </summary>
public interface IPluginConstraint
{
string Message { get; }
bool Apply(string extpoint);
}
/// <summary>
/// Classes wishing to select specific plugins from a range of possible options
/// must implement this class and pass it to PluginLoader Load()
/// </summary>
public interface IPluginFilter
{
bool Apply(PluginExtensionNode plugin);
}
/// <summary>
/// Generic Plugin Loader
/// </summary>
public class PluginLoader <T> : IDisposable where T : IPlugin
{
private const int max_loadable_plugins = 10000;
private List<T> loaded = new List<T>();
private List<string> extpoints = new List<string>();
private PluginInitialiserBase initialiser;
private Dictionary<string,IPluginConstraint> constraints
= new Dictionary<string,IPluginConstraint>();
private Dictionary<string,IPluginFilter> filters
= new Dictionary<string,IPluginFilter>();
private static readonly ILog log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public PluginInitialiserBase Initialiser
{
set { initialiser = value; }
get { return initialiser; }
}
public List<T> Plugins
{
get { return loaded; }
}
public T Plugin
{
get { return (loaded.Count == 1)? loaded [0] : default (T); }
}
public PluginLoader()
{
Initialiser = new PluginInitialiserBase();
initialise_plugin_dir_(".");
}
public PluginLoader(PluginInitialiserBase init)
{
Initialiser = init;
initialise_plugin_dir_(".");
}
public PluginLoader(PluginInitialiserBase init, string dir)
{
Initialiser = init;
initialise_plugin_dir_(dir);
}
public void Add(string extpoint)
{
if (extpoints.Contains(extpoint))
return;
extpoints.Add(extpoint);
}
public void Add(string extpoint, IPluginConstraint cons)
{
Add(extpoint);
AddConstraint(extpoint, cons);
}
public void Add(string extpoint, IPluginFilter filter)
{
Add(extpoint);
AddFilter(extpoint, filter);
}
public void AddConstraint(string extpoint, IPluginConstraint cons)
{
constraints.Add(extpoint, cons);
}
public void AddFilter(string extpoint, IPluginFilter filter)
{
filters.Add(extpoint, filter);
}
public void Load(string extpoint)
{
Add(extpoint);
Load();
}
public void Load()
{
foreach (string ext in extpoints)
{
log.Info("[PLUGINS]: Loading extension point " + ext);
if (constraints.ContainsKey(ext))
{
IPluginConstraint cons = constraints[ext];
if (cons.Apply(ext))
log.Error("[PLUGINS]: " + ext + " failed constraint: " + cons.Message);
}
IPluginFilter filter = null;
if (filters.ContainsKey(ext))
filter = filters[ext];
List<T> loadedPlugins = new List<T>();
foreach (PluginExtensionNode node in AddinManager.GetExtensionNodes(ext))
{
log.Info("[PLUGINS]: Trying plugin " + node.Path);
if ((filter != null) && (filter.Apply(node) == false))
continue;
T plugin = (T)node.CreateInstance();
loadedPlugins.Add(plugin);
}
// We do Initialise() in a second loop after CreateInstance
// So that modules who need init before others can do it
// Example: Script Engine Component System needs to load its components before RegionLoader starts
foreach (T plugin in loadedPlugins)
{
Initialiser.Initialise(plugin);
Plugins.Add(plugin);
}
}
}
public void Dispose()
{
foreach (T plugin in Plugins)
plugin.Dispose();
}
private void initialise_plugin_dir_(string dir)
{
if (AddinManager.IsInitialized == true)
return;
log.Info("[PLUGINS]: Initializing addin manager");
AddinManager.AddinLoadError += on_addinloaderror_;
AddinManager.AddinLoaded += on_addinloaded_;
if (System.Diagnostics.Process.GetCurrentProcess().ProcessName.Contains("OpenSim.Grid.UserServer"))
{
log.Info("[PLUGINS]: Cleaning out addins directory");
clear_registry_();
}
suppress_console_output_(true);
Directory.CreateDirectory("addin-db-001\\addin-dir-data");
AddinManager.Initialize(dir);
AddinManager.Registry.Update(null);
suppress_console_output_(false);
}
private void on_addinloaded_(object sender, AddinEventArgs args)
{
log.Info ("[PLUGINS]: Plugin Loaded: " + args.AddinId);
}
private void on_addinloaderror_(object sender, AddinErrorEventArgs args)
{
if (args.Exception == null)
log.Error ("[PLUGINS]: Plugin Error: "
+ args.Message);
else
log.Error ("[PLUGINS]: Plugin Error: "
+ args.Exception.Message + "\n"
+ args.Exception.StackTrace);
}
private void clear_registry_()
{
// The Mono addin manager (in Mono.Addins.dll version 0.2.0.0)
// occasionally seems to corrupt its addin cache
// Hence, as a temporary solution we'll remove it before each startup
try
{
if (Directory.Exists("addin-db-000"))
Directory.Delete("addin-db-000", true);
if (Directory.Exists("addin-db-001"))
Directory.Delete("addin-db-001", true);
}
catch (IOException)
{
// If multiple services are started simultaneously, they may
// each test whether the directory exists at the same time, and
// attempt to delete the directory at the same time. However,
// one of the services will likely succeed first, causing the
// second service to throw an IOException. We catch it here and
// continue on our merry way.
// Mike 2008.08.01, patch from Zaki
}
}
private static TextWriter prev_console_;
public void suppress_console_output_(bool save)
{
if (save)
{
prev_console_ = System.Console.Out;
System.Console.SetOut(new StreamWriter(Stream.Null));
}
else
{
if (prev_console_ != null)
System.Console.SetOut(prev_console_);
}
}
}
public class PluginExtensionNode : ExtensionNode
{
[NodeAttribute]
string id = "";
[NodeAttribute]
string provider = "";
[NodeAttribute]
string type = "";
Type typeobj;
public string ID { get { return id; } }
public string Provider { get { return provider; } }
public string TypeName { get { return type; } }
public Type TypeObject
{
get
{
if (typeobj != null)
return typeobj;
if (type.Length == 0)
throw new InvalidOperationException("Type name not specified.");
return typeobj = Addin.GetType(type, true);
}
}
public object CreateInstance()
{
return Activator.CreateInstance(TypeObject);
}
}
/// <summary>
/// Constraint that bounds the number of plugins to be loaded.
/// </summary>
public class PluginCountConstraint : IPluginConstraint
{
private int min;
private int max;
public PluginCountConstraint(int exact)
{
min = exact;
max = exact;
}
public PluginCountConstraint(int minimum, int maximum)
{
min = minimum;
max = maximum;
}
public string Message
{
get
{
return "The number of plugins is constrained to the interval ["
+ min + ", " + max + "]";
}
}
public bool Apply (string extpoint)
{
int count = AddinManager.GetExtensionNodes(extpoint).Count;
if ((count < min) || (count > max))
throw new PluginConstraintViolatedException(Message);
return true;
}
}
/// <summary>
/// Filters out which plugin to load based on the plugin name or names given. Plugin names are contained in
/// their addin.xml
/// </summary>
public class PluginProviderFilter : IPluginFilter
{
private string[] m_filters;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="p">
/// Plugin name or names on which to filter. Multiple names should be separated by commas.
/// </param>
public PluginProviderFilter(string p)
{
m_filters = p.Split(',');
for (int i = 0; i < m_filters.Length; i++)
{
m_filters[i] = m_filters[i].Trim();
}
}
/// <summary>
/// Apply this filter to the given plugin.
/// </summary>
/// <param name="plugin"></param>
/// <returns>true if the plugin's name matched one of the filters, false otherwise.</returns>
public bool Apply (PluginExtensionNode plugin)
{
for (int i = 0; i < m_filters.Length; i++)
{
if (m_filters[i] == plugin.Provider)
{
return true;
}
}
return false;
}
}
/// <summary>
/// Filters plugins according to their ID. Plugin IDs are contained in their addin.xml
/// </summary>
public class PluginIdFilter : IPluginFilter
{
private string[] m_filters;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="p">
/// Plugin ID or IDs on which to filter. Multiple names should be separated by commas.
/// </param>
public PluginIdFilter(string p)
{
m_filters = p.Split(',');
for (int i = 0; i < m_filters.Length; i++)
{
m_filters[i] = m_filters[i].Trim();
}
}
/// <summary>
/// Apply this filter to <paramref name="plugin" />.
/// </summary>
/// <param name="plugin">PluginExtensionNode instance to check whether it passes the filter.</param>
/// <returns>true if the plugin's ID matches one of the filters, false otherwise.</returns>
public bool Apply (PluginExtensionNode plugin)
{
for (int i = 0; i < m_filters.Length; i++)
{
if (m_filters[i] == plugin.ID)
{
return true;
}
}
return false;
}
}
}
| |
namespace ToolBelt
{
using System;
using System.Runtime.InteropServices;
#if WINDOWS
public unsafe sealed class Memory
{
#region NativeMethods
class NativeMethods
{
[DllImport("kernel32.dll")]
public unsafe static extern void CopyMemory(byte* pDst, byte* pSrc, int len);
}
#endregion
private Memory()
{
}
/// <summary>
/// Calculate length of a zero terminated string, C-style string.
/// </summary>
/// <param name="p"></param>
/// <returns>Length of the string.</returns>
private static int StringLength(char* p)
{
int len = 0;
while (*p != 0)
len++;
return len;
}
/// <summary>
/// Copy a string object to a char* location. String is always zero terminated, even if source is
/// bigger than <code>len</code> characters. Copying stops at first zero found in source characters.
/// </summary>
/// <param name="pDst">Destination</param>
/// <param name="src">Source</param>
/// <param name="len">Maximum number of characters (including terminating zero) to copy.</param>
public static void Copy(char* pDst, string src, int len)
{
if (len == 0)
return;
// We might as well use a pointer, as this is an unsafe method anyway!
fixed (char* pTmp = src)
{
// pTmp is read-only!
char* pSrc = pTmp;
while ((len != 0) && (*pSrc != 0))
{
*pDst++= *pSrc++;
len--;
}
if (len == 0)
pDst--;
*pDst = '\0';
}
}
/// <summary>
/// Copy a byte array to a byte* location.
/// </summary>
/// <param name="pDst">Destination</param>
/// <param name="src">Source</param>
/// <param name="len">Maximum number of bytes to copy</param>
public static void Copy(byte* pDst, byte[] src, int len)
{
fixed (byte* pTmp = src)
{
NativeMethods.CopyMemory(pDst, pTmp, len);
}
}
/// <summary>
/// Copy a shart array to a short* location.
/// </summary>
/// <param name="pDst">Destination</param>
/// <param name="src">Source</param>
/// <param name="len">Maximum number of bytes to copy</param>
public static void Copy(short* pDst, short[] src, int len)
{
fixed (short* pTmp = src)
{
NativeMethods.CopyMemory((byte*)pDst, (byte*)pTmp, len * sizeof(short));
}
}
/// <summary>
/// Copy a int array to an int* location.
/// </summary>
/// <param name="pDst">Destination</param>
/// <param name="src">Source</param>
/// <param name="len">Maximum number of bytes to copy</param>
public static void Copy(int* pDst, int[] src, int len)
{
fixed (int* pTmp = src)
{
NativeMethods.CopyMemory((byte*)pDst, (byte*)pTmp, len * sizeof(int));
}
}
/// <summary>
/// Copy a long array to a long* location.
/// </summary>
/// <param name="pDst">Destination</param>
/// <param name="src">Source</param>
/// <param name="len">Maximum number of bytes to copy</param>
public static void Copy(long* pDst, long[] src, int len)
{
fixed (long* pTmp = src)
{
NativeMethods.CopyMemory((byte*)pDst, (byte*)pTmp, len * sizeof(long));
}
}
/// <summary>
/// Copy a float array to a float* location.
/// </summary>
/// <param name="pDst">Destination</param>
/// <param name="src">Source</param>
/// <param name="len">Maximum number of bytes to copy</param>
public static void Copy(float* pDst, float[] src, int len)
{
fixed (float* pTmp = src)
{
NativeMethods.CopyMemory((byte*)pDst, (byte*)pTmp, len * sizeof(float));
}
}
/// <summary>
/// Copy a double array to a double* location.
/// </summary>
/// <param name="pDst">Destination</param>
/// <param name="src">Source</param>
/// <param name="len">Maximum number of bytes to copy</param>
public static void Copy(double* pDst, double[] src, int len)
{
fixed (double* pTmp = src)
{
NativeMethods.CopyMemory((byte*)pDst, (byte*)pTmp, len * sizeof(double));
}
}
/// <summary>
/// Compare one string with another. Assumes both strings have a terminating zero character.
/// </summary>
/// <returns>0 if strings are equal, -1 if first string < second string, 1 otherwise.</returns>
/// <param name="pStr1">First string</param>
/// <param name="pStr2">Second string</param>
public static int Compare(char* pStr1, char* pStr2)
{
int n = 0;
while ((n == 0) && (*pStr1 != '\0') && (*pStr2 != '\0'))
{
n = (*pStr1++ - *pStr2++);
}
// If they're different, return
if (n != 0)
return (n > 0 ? 1 : -1);
// They look the same so far, but one could be longer
if (*pStr1 != '\0')
return 1; // "abcdefg" > "abc"
else if (*pStr2 != '\0')
return -1; // "abc" < "abcdefg"
else
return 0; // They're the same
}
/// <summary>
/// Compare two blocks of memory.
/// </summary>
/// <returns><code>length</code> if memory blocks are equal, otherwise the offset of the first unequal byte.</returns>
/// <param name="pMem1">Pointer to first block of memory</param>
/// <param name="pMem2">Pointer to second block of memory</param>
/// <param name="length">Number of bytes to compare</param>
public static int Compare(byte* pMem1, byte* pMem2, int length)
{
int i;
for (i = 0; i < length; i++)
{
if (*pMem1++ != *pMem2++)
break;
}
return i;
}
/// <summary>
/// Compare two blocks of memory containing short values.
/// </summary>
/// <returns><code>length</code> if memory blocks are equal, otherwise the offset of the first unequal short.</returns>
/// <param name="pMem1">Pointer to first block of memory</param>
/// <param name="pMem2">Pointer to second block of memory</param>
/// <param name="length">Number of bytes to compare</param>
public static int Compare(short* pMem1, short* pMem2, int length)
{
return Compare((byte*)pMem1, (byte*)pMem2, length * sizeof(short)) / sizeof(short);
}
/// <summary>
/// Compare two blocks of memory containing int values
/// </summary>
/// <returns><code>length</code> if memory blocks are equal, otherwise the offset of the first unequal int.</returns>
/// <param name="pMem1">Pointer to first block of memory</param>
/// <param name="pMem2">Pointer to second block of memory</param>
/// <param name="length">Number of bytes to compare</param>
public static int Compare(int* pMem1, int* pMem2, int length)
{
return Compare((byte*)pMem1, (byte*)pMem2, length * sizeof(int)) / sizeof(int);
}
/// <summary>
/// Compare two blocks of memory containing long values
/// </summary>
/// <returns><code>length</code> if memory blocks are equal, otherwise the offset of the first unequal long.</returns>
/// <param name="pMem1">Pointer to first block of memory</param>
/// <param name="pMem2">Pointer to second block of memory</param>
/// <param name="length">Number of bytes to compare</param>
public static int Compare(long* pMem1, long* pMem2, int length)
{
return Compare((byte*)pMem1, (byte*)pMem2, length * sizeof(long)) / sizeof(long);
}
/// <summary>
/// Compare two blocks of memory containing float values.
/// </summary>
/// <returns><code>length</code> if memory blocks are equal, otherwise the offset of the first unequal float.</returns>
/// <param name="pMem1">Pointer to first block of memory</param>
/// <param name="pMem2">Pointer to second block of memory</param>
/// <param name="length">Number of bytes to compare</param>
public static int Compare(float* pMem1, float* pMem2, int length)
{
return Compare((byte*)pMem1, (byte*)pMem2, length * sizeof(float)) / sizeof(float);
}
/// <summary>
/// Compare two blocks of memory containing doubles.
/// </summary>
/// <returns><code>length</code> if memory blocks are equal, otherwise the offset of the first unequal double.</returns>
/// <param name="pMem1">Pointer to first block of memory</param>
/// <param name="pMem2">Pointer to second block of memory</param>
/// <param name="length">Number of bytes to compare</param>
public static int Compare(double* pMem1, double* pMem2, int length)
{
return Compare((byte*)pMem1, (byte*)pMem2, length * sizeof(double)) / sizeof(double);
}
}
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.noaccessibility004.noaccessibility004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.noaccessibility004.noaccessibility004;
// <Title>Call methods that have different accessibility</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class Foo
{
protected internal int this[int x]
{
set
{
Test.Status = 0;
}
}
}
public class Test
{
public static int Status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = 3;
f[d] = -1;
return Status;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param012.param012;
using System;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Resources;
using Microsoft.CSharp.RuntimeBinder;
public enum ErrorElementId
{
None,
SK_METHOD, // method
SK_CLASS, // type
SK_NAMESPACE, // namespace
SK_FIELD, // field
SK_PROPERTY, // property
SK_UNKNOWN, // element
SK_VARIABLE, // variable
SK_EVENT, // event
SK_TYVAR, // type parameter
SK_ALIAS, // using alias
ERRORSYM, // <error>
NULL, // <null>
GlobalNamespace, // <global namespace>
MethodGroup, // method group
AnonMethod, // anonymous method
Lambda, // lambda expression
AnonymousType, // anonymous type
}
public enum ErrorMessageId
{
None,
BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
IntDivByZero, // Division by constant zero
BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}'
BadIndexCount, // Wrong number of indices inside []; expected '{0}'
BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}'
NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}'
NoExplicitConv, // Cannot convert type '{0}' to '{1}'
ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}'
AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'
AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}'
ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type
WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}'
NoSuchMember, // '{0}' does not contain a definition for '{1}'
ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}'
AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}'
BadAccess, // '{0}' is inaccessible due to its protection level
MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}'
AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer
NoConstructors, // The type '{0}' has no constructors defined
BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor
PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor
ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead
AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer)
RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor)
AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only
AbstractBaseCall, // Cannot call an abstract base member: '{0}'
RefProperty, // A property or indexer may not be passed as an out or ref parameter
ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')
FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression
UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers
BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters
MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false
CheckedOverflow, // The operation overflows at compile time in checked mode
ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)
AmbigMember, // Ambiguity between '{0}' and '{1}'
SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}'
CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.
CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor.
BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression
NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)
InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible
InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible
BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments
BadTypeArgument, // The type '{0}' may not be used as a type argument
TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments
HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments
NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'
GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.
GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.
GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.
TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.
BadRetType, // '{1} {0}' has the wrong return type
CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.
MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?
RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'
ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'
CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}'
BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'
ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'
AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'
PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported
PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly
BindToBogus, // '{0}' is not supported by the language
CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor
BogusType, // '{0}' is a type not supported by the language
MissingPredefinedMember, // Missing compiler required member '{0}.{1}'
LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type
UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions
ConvertToStaticClass, // Cannot convert to static type '{0}'
GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments
PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer
NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)
ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates
BadArgCount, // No overload for method '{0}' takes '{1}' arguments
BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments
BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}'
RefLvalueExpected, // A ref or out argument must be an assignable variable
BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)
BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'
BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'
BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments
BadDelArgTypes, // Delegate '{0}' has some invalid arguments
AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only
RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only
ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable
BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword
// DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED)
BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword
AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)
RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor)
AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}'
RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}'
ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead.
DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>'
BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments
BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments
BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}'
BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method.
NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified
BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}'
BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}'
DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times
NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given
}
public enum RuntimeErrorId
{
None,
// RuntimeBinderInternalCompilerException
InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation
// ArgumentException
BindRequireArguments, // Cannot bind call with no calling object
// RuntimeBinderException
BindCallFailedOverloadResolution, // Overload resolution failed
// ArgumentException
BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments
// ArgumentException
BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument
// RuntimeBinderException
BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property
// RuntimeBinderException
BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -=
// RuntimeBinderException
BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type
// ArgumentException
BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument
// ArgumentException
BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument
// ArgumentException
BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument
// RuntimeBinderException
BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference
// RuntimeBinderException
NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference
// RuntimeBinderException
BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute
// RuntimeBinderException
BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object'
// EE?
EmptyDynamicView, // No further information on this object could be discovered
// MissingMemberException
GetValueonWriteOnlyProperty, // Write Only properties are not supported
}
public class ErrorVerifier
{
private static Assembly s_asm;
private static ResourceManager s_rm1;
private static ResourceManager s_rm2;
public static string GetErrorElement(ErrorElementId id)
{
return string.Empty;
}
public static bool Verify(ErrorMessageId id, string actualError, params string[] args)
{
return true;
}
public static bool Verify(RuntimeErrorId id, string actualError, params string[] args)
{
return true;
}
private static bool CompareMessages(ResourceManager rm, string id, string actualError, params string[] args)
{
// should not happen
if (null == rm)
return false;
if (String.IsNullOrEmpty(id) || String.IsNullOrEmpty(actualError))
{
System.Console.WriteLine("Empty error id or actual message");
return false;
}
string message = rm.GetString(id, null);
if ((null != args) && (0 < args.Length))
{
message = String.Format(CultureInfo.InvariantCulture, message, args);
}
bool ret = 0 == String.CompareOrdinal(message, actualError);
// debug
if (!ret)
{
System.Console.WriteLine("*** Expected= {0}\r\n*** Actual= {1}", message, actualError);
}
return ret;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param012.param012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param012.param012;
// <Title>Call methods that have different parameter modifiers with dynamic</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(23,23\).*CS0649</Expects>
public struct myStruct
{
public int Field;
}
public class Foo
{
public int this[params int[] x]
{
set
{
}
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = "foo";
try
{
f[d] = 1;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.this[params int[]]"))
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param014.param014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param014.param014;
// <Title>Call methods that have different parameter modifiers with dynamic</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public struct myStruct
{
public int Field;
}
public class Foo
{
public int this[params int[] x]
{
set
{
}
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = "foo";
dynamic d2 = 3;
try
{
f[d2, d] = 3;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.this[params int[]]"))
return 0;
}
return 1;
}
}
// </Code>
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Shouldly;
using Xunit;
using CanonicalError = Microsoft.Build.Shared.CanonicalError;
namespace Microsoft.Build.UnitTests
{
public class CanonicalErrorTest
{
[Fact]
public void EmptyOrigin()
{
ValidateToolError(@"error CS0006: Metadata file 'C:\WINDOWS\Microsoft.NET\Framework\v1.2.21213\System.dll' could not be found", "", CanonicalError.Parts.Category.Error, "CS0006", @"Metadata file 'C:\WINDOWS\Microsoft.NET\Framework\v1.2.21213\System.dll' could not be found");
}
[Fact]
public void Alink()
{
// From AL.EXE
ValidateToolError(@"ALINK: error AL1017: No target filename was specified", "ALINK", CanonicalError.Parts.Category.Error, "AL1017", @"No target filename was specified");
}
[Fact]
public void CscWithFilename()
{
// From CSC.EXE
ValidateFileNameLineColumnError(@"foo.resx(2,1): error CS0116: A namespace does not directly contain members such as fields or methods", @"foo.resx", 2, 1, CanonicalError.Parts.Category.Error, "CS0116", "A namespace does not directly contain members such as fields or methods");
ValidateFileNameLineColumnError(@"Main.cs(17,20): warning CS0168: The variable 'foo' is declared but never used", @"Main.cs", 17, 20, CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
}
[Fact]
public void VbcWithFilename()
{
// From VBC.EXE
ValidateFileNameLineError(@"C:\WINDOWS\Microsoft.NET\Framework\v1.2.x86fre\foo.resx(2) : error BC30188: Declaration expected.", @"C:\WINDOWS\Microsoft.NET\Framework\v1.2.x86fre\foo.resx", 2, CanonicalError.Parts.Category.Error, "BC30188", "Declaration expected.");
}
[Fact]
public void ClWithFilename()
{
// From CL.EXE
ValidateFileNameLineError(@"foo.cpp(1) : error C2143: syntax error : missing ';' before '++'", @"foo.cpp", 1, CanonicalError.Parts.Category.Error, "C2143", "syntax error : missing ';' before '++'");
}
[Fact]
public void JscWithFilename()
{
// From JSC.EXE
ValidateFileNameLineColumnError(@"foo.resx(2,1) : error JS1135: Variable 'blech' has not been declared", @"foo.resx", 2, 1, CanonicalError.Parts.Category.Error, "JS1135", "Variable 'blech' has not been declared");
}
[Fact]
public void LinkWithFilename()
{
// From Link.exe
// Note that this is impossible to distinguish from a tool error without
// actually looking at the disk to see if the given file is there.
ValidateFileNameError(@"foo.cpp : fatal error LNK1106: invalid file or disk full: cannot seek to 0x5361", @"foo.cpp", CanonicalError.Parts.Category.Error, "LNK1106", "invalid file or disk full: cannot seek to 0x5361");
}
[Fact]
public void BscMake()
{
// From BSCMAKE.EXE
ValidateToolError(@"BSCMAKE: error BK1510 : corrupt .SBR file 'foo.cpp'", "BSCMAKE", CanonicalError.Parts.Category.Error, "BK1510", @"corrupt .SBR file 'foo.cpp'");
}
[Fact]
public void CvtRes()
{
// From CVTRES.EXE
ValidateToolError(@"CVTRES : warning CVT4001: machine type not specified; assumed X86", "CVTRES", CanonicalError.Parts.Category.Warning, "CVT4001", @"machine type not specified; assumed X86");
ValidateToolError(@"CVTRES : fatal error CVT1103: cannot read file", "CVTRES", CanonicalError.Parts.Category.Error, "CVT1103", @"cannot read file");
}
[Fact]
public void DumpBinWithFilename()
{
// From DUMPBIN.EXE (notice that an 'LNK' error is returned).
ValidateFileNameError(@"foo.cpp : warning LNK4048: Invalid format file; ignored", @"foo.cpp", CanonicalError.Parts.Category.Warning, "LNK4048", "Invalid format file; ignored");
}
[Fact]
public void LibWithFilename()
{
// From LIB.EXE
ValidateFileNameError(@"foo.cpp : fatal error LNK1106: invalid file or disk full: cannot seek to 0x5361", @"foo.cpp", CanonicalError.Parts.Category.Error, "LNK1106", "invalid file or disk full: cannot seek to 0x5361");
}
[Fact]
public void MlWithFilename()
{
// From ML.EXE
ValidateFileNameLineError(@"bar.h(2) : error A2008: syntax error : lksdflksj", @"bar.h", 2, CanonicalError.Parts.Category.Error, "A2008", "syntax error : lksdflksj");
ValidateFileNameLineError(@"bar.h(2) : error A2088: END directive required at end of file", @"bar.h", 2, CanonicalError.Parts.Category.Error, "A2088", "END directive required at end of file");
}
[Fact]
public void VcDeployWithFilename()
{
// From VCDEPLOY.EXE
ValidateToolError(@"vcdeploy : error VCD0041: IIS must be installed on this machine in order for this program to function correctly.", "vcdeploy", CanonicalError.Parts.Category.Error, "VCD0041", @"IIS must be installed on this machine in order for this program to function correctly.");
}
[Fact]
public void VCBuildError()
{
// From VCBUILD.EXE
ValidateFileNameLineError(@"1>c:\temp\testprefast\testprefast\testprefast.cpp(12) : error C4996: 'sprintf' was declared deprecated", @"c:\temp\testprefast\testprefast\testprefast.cpp", 12, CanonicalError.Parts.Category.Error, "C4996", "'sprintf' was declared deprecated");
ValidateFileNameLineError(@"1234>c:\temp\testprefast\testprefast\testprefast.cpp(12) : error C4996: 'sprintf' was declared deprecated", @"c:\temp\testprefast\testprefast\testprefast.cpp", 12, CanonicalError.Parts.Category.Error, "C4996", "'sprintf' was declared deprecated");
}
[Fact]
public void FileNameLine()
{
ValidateFileNameMultiLineColumnError("foo.cpp(1):error TST0000:Text", "foo.cpp", 1, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.Category.Error, "TST0000", "Text");
}
[Fact]
public void FileNameLineLine()
{
ValidateFileNameMultiLineColumnError("foo.cpp(1-5):error TST0000:Text", "foo.cpp", 1, CanonicalError.Parts.numberNotSpecified, 5, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.Category.Error, "TST0000", "Text");
}
[Fact]
public void FileNameLineCol()
{
ValidateFileNameMultiLineColumnError("foo.cpp(1,15):error TST0000:Text", "foo.cpp", 1, 15, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.Category.Error, "TST0000", "Text");
}
[Fact]
public void FileNameLineColCol()
{
ValidateFileNameMultiLineColumnError("foo.cpp(1,15-25):error TST0000:Text", "foo.cpp", 1, 15, CanonicalError.Parts.numberNotSpecified, 25, CanonicalError.Parts.Category.Error, "TST0000", "Text");
}
[Fact]
public void FileNameLineColLineCol()
{
ValidateFileNameMultiLineColumnError("foo.cpp(1,15,2,25):error TST0000:Text", "foo.cpp", 1, 15, 2, 25, CanonicalError.Parts.Category.Error, "TST0000", "Text");
}
[Fact]
public void PathologicalFileNameWithParens()
{
// Pathological case, there is actually a file with () at the end (Doesn't work, treats the (1) as a line number anyway).
ValidateFileNameMultiLineColumnError("PathologicalFile.txt(1):error TST0000:Text", "PathologicalFile.txt", 1, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.Category.Error, "TST0000", "Text");
}
[Fact]
public void OverflowTrimmingShouldNotDropChar()
{
// A devdiv build produced a huge message like this!
string message = @"The name 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' does not exist in the current context";
string error = @"test.cs(1,32): error CS0103: " + message;
CanonicalError.Parts parts = CanonicalError.Parse(error);
parts.text.ShouldBe(message);
}
[Fact]
public void ValidateErrorMessageWithFileName()
{
ValidateFileNameError("error CS2011: Error opening response file 'e:\foo\test.rsp' -- 'The device is not ready. '",
"", CanonicalError.Parts.Category.Error, "CS2011", "Error opening response file 'e:\foo\test.rsp' -- 'The device is not ready. '");
}
[Fact]
public void ValidateErrorMessageWithFileName2()
{
ValidateFileNameError(@"BUILDMSG: error: Path 'c:\binaries.x86chk\bin\i386\System.AddIn.Contract.dll' is not under client's root 'c:\vstamq'.",
"BUILDMSG", CanonicalError.Parts.Category.Error, "", @"Path 'c:\binaries.x86chk\bin\i386\System.AddIn.Contract.dll' is not under client's root 'c:\vstamq'.");
ValidateFileNameError(@"BUILDMSG: error : Path 'c:\binaries.x86chk\bin\i386\System.AddIn.Contract.dll' is not under client's root 'c:\vstamq'.",
"BUILDMSG", CanonicalError.Parts.Category.Error, "", @"Path 'c:\binaries.x86chk\bin\i386\System.AddIn.Contract.dll' is not under client's root 'c:\vstamq'.");
}
[Fact]
public void ValidateErrorMessageWithFileName3()
{
ValidateNormalMessage(@"BUILDMSG: errorgarbage: Path 'c:\binaries.x86chk\bin\i386\System.AddIn.Contract.dll' is not under client's root 'c:\vstamq'.");
ValidateNormalMessage(@"BUILDMSG: errorgarbage : Path 'c:\binaries.x86chk\bin\i386\System.AddIn.Contract.dll' is not under client's root 'c:\vstamq'.");
}
[Fact]
public void ValidateErrorMessageVariableNotUsed()
{
// (line)
ValidateFileNameMultiLineColumnError("Main.cs():Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
// This one actually falls under the (line-line) category. I'm not going to tweak the regex for this incorrect input just so we can
// pretend -3 == 0, and just leaving it here for completeness
ValidateFileNameMultiLineColumnError("Main.cs(-3):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, 3, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
// (line-line)
ValidateFileNameMultiLineColumnError("Main.cs(-):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(-2):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, 2, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(1-):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", 1, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
// (line,col)
ValidateFileNameMultiLineColumnError("Main.cs(,):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(,2):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, 2, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(1,):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", 1, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
// Similarly to the previous odd case, this really falls under (line,col-col). Included for completeness, even if results are
// not intuitive
ValidateFileNameMultiLineColumnError("Main.cs(,-2):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, 2,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(-1,):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
// (line,col-col)
ValidateFileNameMultiLineColumnError("Main.cs(,-):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(2,-):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", 2, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(,4-):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, 4, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(,-6):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, 6,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(-1,-):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
// (line,col,line,col)
ValidateFileNameMultiLineColumnError("Main.cs(,,,):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(2,,,):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", 2, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(,3,,):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, 3, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(,,4,):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, 4, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(,,,5):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, 5,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
// negative numbers are not matched at all for this format and I don't think we should tweak regexes to accept invalid input
// in that form
ValidateFileNameMultiLineColumnError("Main.cs(-2,,1,):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(,-3,,2):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(3,,-4,):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
ValidateFileNameMultiLineColumnError("Main.cs(,4,,-5):Command line warning CS0168: The variable 'foo' is declared but never used",
"Main.cs", CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Warning, "CS0168", "The variable 'foo' is declared but never used");
}
[Fact]
public void ClangGccError()
{
CanonicalError.Parts errorParts = CanonicalError.Parse(
"err.cpp:6:3: error: use of undeclared identifier 'force_an_error'");
errorParts.ShouldNotBeNull();
errorParts.origin.ShouldBe("err.cpp");
errorParts.category.ShouldBe(CanonicalError.Parts.Category.Error);
errorParts.code.ShouldStartWith("G");
errorParts.code.Length.ShouldBe(9);
errorParts.text.ShouldBe("use of undeclared identifier 'force_an_error'");
errorParts.line.ShouldBe(6);
errorParts.column.ShouldBe(3);
errorParts.endLine.ShouldBe(CanonicalError.Parts.numberNotSpecified);
errorParts.endColumn.ShouldBe(CanonicalError.Parts.numberNotSpecified);
}
[Fact]
public void ClangGccErrorWithEmptyText()
{
ValidateFileNameMultiLineColumnError(
"tests\\Tests\\Syntax.hs:1:1: error:",
"tests\\Tests\\Syntax.hs",
1, 1,
CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.numberNotSpecified,
CanonicalError.Parts.Category.Error,
"G00000000",
string.Empty);
}
#region Support functions.
private static void ValidateToolError(string message, string tool, CanonicalError.Parts.Category severity, string code, string text)
{
CanonicalError.Parts errorParts = CanonicalError.Parse(message);
errorParts.ShouldNotBeNull(); // "The message '" + message + "' could not be interpreted."
errorParts.origin.ShouldBe(tool);
errorParts.category.ShouldBe(severity);
errorParts.code.ShouldBe(code);
errorParts.text.ShouldBe(text);
errorParts.line.ShouldBe(CanonicalError.Parts.numberNotSpecified);
errorParts.column.ShouldBe(CanonicalError.Parts.numberNotSpecified);
errorParts.endLine.ShouldBe(CanonicalError.Parts.numberNotSpecified);
errorParts.endColumn.ShouldBe(CanonicalError.Parts.numberNotSpecified);
}
private static void ValidateFileNameMultiLineColumnError(string message, string filename, int line, int column, int endLine, int endColumn, CanonicalError.Parts.Category severity, string code, string text)
{
CanonicalError.Parts errorParts = CanonicalError.Parse(message);
errorParts.ShouldNotBeNull(); // "The message '" + message + "' could not be interpreted."
errorParts.origin.ShouldBe(filename);
errorParts.category.ShouldBe(severity);
errorParts.code.ShouldBe(code);
errorParts.text.ShouldBe(text);
errorParts.line.ShouldBe(line);
errorParts.column.ShouldBe(column);
errorParts.endLine.ShouldBe(endLine);
errorParts.endColumn.ShouldBe(endColumn);
}
private static void ValidateFileNameLineColumnError(string message, string filename, int line, int column, CanonicalError.Parts.Category severity, string code, string text)
{
ValidateFileNameMultiLineColumnError(message, filename, line, column, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, severity, code, text);
}
private static void ValidateFileNameLineError(string message, string filename, int line, CanonicalError.Parts.Category severity, string code, string text)
{
ValidateFileNameMultiLineColumnError(message, filename, line, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, severity, code, text);
}
private static void ValidateFileNameError(string message, string filename, CanonicalError.Parts.Category severity, string code, string text)
{
ValidateFileNameMultiLineColumnError(message, filename, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, CanonicalError.Parts.numberNotSpecified, severity, code, text);
}
private static void ValidateNormalMessage(string message)
{
CanonicalError.Parts errorParts = CanonicalError.Parse(message);
errorParts.ShouldBeNull(); // "The message '" + message + "' is an error/warning message"
}
}
#endregion
}
| |
// 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.IO;
using System.Xml;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class has static methods to determine line numbers and column numbers for given
/// XML nodes.
/// </summary>
/// <owner>RGoel</owner>
internal static class XmlSearcher
{
/// <summary>
/// Given an XmlNode belonging to a document that lives on disk, this method determines
/// the line/column number of that node in the document. It does this by re-reading the
/// document from disk and searching for the given node.
/// </summary>
/// <param name="xmlNodeToFind">Any XmlElement or XmlAttribute node (preferably in a document that still exists on disk).</param>
/// <param name="foundLineNumber">(out) The line number where the specified node begins.</param>
/// <param name="foundColumnNumber">(out) The column number where the specified node begins.</param>
/// <returns>true if found, false otherwise. Should not throw any exceptions.</returns>
/// <owner>RGoel</owner>
internal static bool GetLineColumnByNode
(
XmlNode xmlNodeToFind,
out int foundLineNumber,
out int foundColumnNumber
)
{
// Initialize the output parameters.
foundLineNumber = 0;
foundColumnNumber = 0;
if (xmlNodeToFind == null)
{
return false;
}
// Get the filename where this XML node came from. Make sure it still
// exists on disk. If not, there's nothing we can do. Sorry.
string fileName = XmlUtilities.GetXmlNodeFile(xmlNodeToFind, String.Empty);
if ((fileName.Length == 0) || (!File.Exists(fileName)))
{
return false;
}
// Next, we need to compute the "element number" and "attribute number" of
// the given XmlNode in its original container document. Element number is
// simply a 1-based number identifying a particular XML element starting from
// the beginning of the document, ignoring depth. As you're walking the tree,
// visiting each node in order, and recursing deeper whenever possible, the Nth
// element you visit has element number N. Attribute number is simply the
// 1-based index of the attribute within the given Xml element. An attribute
// number of zero indicates that we're not searching for a particular attribute,
// and all we care about is the element as a whole.
int elementNumber;
int attributeNumber;
if (!GetElementAndAttributeNumber(xmlNodeToFind, out elementNumber, out attributeNumber))
{
return false;
}
// Now that we know what element/attribute number we're searching for, find
// it in the Xml document on disk, and grab the line/column number.
return GetLineColumnByNodeNumber(fileName, elementNumber, attributeNumber,
out foundLineNumber, out foundColumnNumber);
}
/// <summary>
/// Determines the element number and attribute number of a given XmlAttribute node,
/// or just the element number for a given XmlElement node.
/// </summary>
/// <param name="xmlNodeToFind">Any XmlElement or XmlAttribute within an XmlDocument.</param>
/// <param name="elementNumber">(out) The element number of the given node.</param>
/// <param name="attributeNumber">(out) If the given node was an XmlAttribute node, then the attribute number of that node, otherwise zero.</param>
/// <returns>true if found, false otherwise. Should not throw any exceptions.</returns>
/// <owner>RGoel</owner>
internal static bool GetElementAndAttributeNumber
(
XmlNode xmlNodeToFind,
out int elementNumber,
out int attributeNumber
)
{
ErrorUtilities.VerifyThrow(xmlNodeToFind != null, "No Xml node!");
// Initialize output parameters.
elementNumber = 0;
attributeNumber = 0;
XmlNode elementToFind;
// First determine the XmlNode in the main hierarchy to search for. If the passed-in
// node is already an XmlElement or Text node, then we already have the node
// that we're searching for. But if the passed-in node is an XmlAttribute, then
// we want to search for the XmlElement that contains that attribute.
// If the node is any other type, try the parent node. It's a better line number than no line number.
if ((xmlNodeToFind.NodeType != XmlNodeType.Element) &&
(xmlNodeToFind.NodeType != XmlNodeType.Text) &&
(xmlNodeToFind.NodeType != XmlNodeType.Attribute))
{
if (xmlNodeToFind.ParentNode != null)
{
xmlNodeToFind = xmlNodeToFind.ParentNode;
}
}
if ((xmlNodeToFind.NodeType == XmlNodeType.Element) || (xmlNodeToFind.NodeType == XmlNodeType.Text))
{
elementToFind = xmlNodeToFind;
}
else if (xmlNodeToFind.NodeType == XmlNodeType.Attribute)
{
elementToFind = ((XmlAttribute) xmlNodeToFind).OwnerElement;
ErrorUtilities.VerifyThrow(elementToFind != null, "How can an xml attribute not have a parent?");
}
else
{
// We don't support searching for anything other than XmlAttribute, XmlElement, or text node.
return false;
}
// Figure out the element number for this particular XML element, by iteratively
// visiting every single node in the XmlDocument in sequence. Start with the
// root node which is the XmlDocument node.
XmlNode xmlNode = xmlNodeToFind.OwnerDocument;
while (true)
{
// If the current node is an XmlElement or text node, bump up our variable which tracks the
// number of XmlElements visited so far.
if ((xmlNode.NodeType == XmlNodeType.Element) || (xmlNode.NodeType == XmlNodeType.Text))
{
elementNumber++;
// If the current XmlElement node is actually the one the caller wanted
// us to search for, then we've found the element number. Yippee.
if (xmlNode == elementToFind)
{
break;
}
}
// The rest of this is all about moving to the next node in the tree.
if (xmlNode.HasChildNodes)
{
// If the current node has any children, then the next node to visit
// is the first child.
xmlNode = xmlNode.FirstChild;
}
else
{
// Current node has no children. So we basically want its next
// sibling. Unless of course it has no more siblings, in which
// case we want its parent's next sibling. Unless of course its
// parent doesn't have any more siblings, in which case we want
// its parent's parent's sibling. Etc, etc.
while ((xmlNode != null) && (xmlNode.NextSibling == null))
{
xmlNode = xmlNode.ParentNode;
}
if (xmlNode == null)
{
// Oops, we reached the end of the document, so bail.
break;
}
else
{
xmlNode = xmlNode.NextSibling;
}
}
}
if (xmlNode == null)
{
// We visited every XmlElement in the document without finding the
// specific XmlElement we were supposed to. Oh well, too bad.
elementNumber = 0;
return false;
}
// If we were originally asked to actually find an XmlAttribute within
// an XmlElement, now comes Part 2. We've already found the correct
// element, so now we just need to iterate through the attributes within
// the element in order until we find the desired one.
if (xmlNodeToFind.NodeType == XmlNodeType.Attribute)
{
bool foundAttribute = false;
XmlAttribute xmlAttributeToFind = xmlNodeToFind as XmlAttribute;
foreach (XmlAttribute xmlAttribute in ((XmlElement)elementToFind).Attributes)
{
attributeNumber++;
if (xmlAttribute == xmlAttributeToFind)
{
foundAttribute = true;
break;
}
}
if (!foundAttribute)
{
return false;
}
}
return true;
}
/// <summary>
/// Read through the entire XML of a given project file, searching for the element/attribute
/// specified by element number and attribute number. Return the line number and column
/// number where it was found.
/// </summary>
/// <param name="projectFile">Path to project file on disk.</param>
/// <param name="xmlElementNumberToSearchFor">Which Xml element to search for.</param>
/// <param name="xmlAttributeNumberToSearchFor">
/// Which Xml attribute within the above Xml element to search for. Pass in zero
/// if you are searching for the Element as a whole and not a particular attribute.
/// </param>
/// <param name="foundLineNumber">(out) The line number where the given element/attribute begins.</param>
/// <param name="foundColumnNumber">The column number where the given element/attribute begins.</param>
/// <returns>true if found, false otherwise. Should not throw any exceptions.</returns>
/// <owner>RGoel</owner>
internal static bool GetLineColumnByNodeNumber
(
string projectFile,
int xmlElementNumberToSearchFor,
int xmlAttributeNumberToSearchFor,
out int foundLineNumber,
out int foundColumnNumber
)
{
ErrorUtilities.VerifyThrow(xmlElementNumberToSearchFor != 0, "No element to search for!");
ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(projectFile), "No project file!");
// Initialize output parameters.
foundLineNumber = 0;
foundColumnNumber = 0;
try
{
// We're going to need to re-read the file from disk in order to find
// the line/column number of the specified node.
using (XmlTextReader reader = new XmlTextReader(projectFile))
{
reader.DtdProcessing = DtdProcessing.Ignore;
int currentXmlElementNumber = 0;
// While we haven't reached the end of the file, and we haven't found the
// specified node ...
while (reader.Read() && (foundColumnNumber == 0) && (foundLineNumber == 0))
{
// Read to the next node. If it is an XML element or Xml text node, then ...
if ((reader.NodeType == XmlNodeType.Element) || (reader.NodeType == XmlNodeType.Text))
{
// Bump up our current XML element count.
currentXmlElementNumber++;
// Check to see if this XML element is the one we've been searching for,
// based on if the numbers match.
if (currentXmlElementNumber == xmlElementNumberToSearchFor)
{
// We've found the desired XML element. If the caller didn't care
// for a particular attribute, then we're done. Return the current
// position of the XmlTextReader.
if (0 == xmlAttributeNumberToSearchFor)
{
foundLineNumber = reader.LineNumber;
foundColumnNumber = reader.LinePosition;
if (reader.NodeType == XmlNodeType.Element)
{
// Do a minus-one here, because the XmlTextReader points us at the first
// letter of the tag name, whereas we would prefer to point at the opening
// left-angle-bracket. (Whitespace between the left-angle-bracket and
// the tag name is not allowed in XML, so this is safe.)
foundColumnNumber--;
}
}
else if (reader.MoveToFirstAttribute())
{
// Caller wants a particular attribute within the element,
// and the element does have 1 or more attributes. So let's
// try to find the right one.
int currentXmlAttributeNumber = 0;
// Loop through all the XML attributes on the current element.
do
{
// Bump the current attribute number and check to see if this
// is the one.
currentXmlAttributeNumber++;
if (currentXmlAttributeNumber == xmlAttributeNumberToSearchFor)
{
// We found the desired attribute. Return the current
// position of the XmlTextReader.
foundLineNumber = reader.LineNumber;
foundColumnNumber = reader.LinePosition;
}
} while (reader.MoveToNextAttribute() && (foundColumnNumber == 0) && (foundLineNumber == 0));
}
}
}
}
}
}
catch (XmlException)
{
// Eat the exception. If anything fails, we simply don't surface the line/column number.
}
catch (IOException)
{
// Eat the exception. If anything fails, we simply don't surface the line/column number.
}
catch (UnauthorizedAccessException)
{
// Eat the exception. If anything fails, we simply don't surface the line/column number.
}
return (foundColumnNumber != 0) && (foundLineNumber != 0);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace Ets2Map
{
public class Ets2NavigationRoute
{
public Ets2Item Start;
public Ets2Item End;
public Ets2Mapper Mapper;
public bool Loading = false;
public List<Tuple<Ets2Item, int, int>> Prefabs;
public List<Ets2Item> Roads;
public List<Ets2NavigationSegment> Segments;
private Ets2Point From;
private Ets2Point To;
public Ets2NavigationRoute(Ets2Item start, Ets2Item end, Ets2Point from, Ets2Point to, Ets2Mapper mapper)
{
Start = start;
End = end;
From = from;
To = to;
Mapper = mapper;
if (Start != End)
{
ThreadPool.QueueUserWorkItem(FindRoute);
}
}
private void FindRoute(object state)
{
Loading = true;
Dictionary<ulong, Tuple<float, Ets2Item>> nodeMap = new Dictionary<ulong, Tuple<float, Ets2Item>>();
List<Ets2Item> nodesToWalk = new List<Ets2Item>();
// Fill node map
foreach (var node in Mapper.Items.Values.Where(x => x.Type == Ets2ItemType.Prefab && x.HideUI == false))
{
nodesToWalk.Add(node);
nodeMap.Add(node.ItemUID, new Tuple<float, Ets2Item>(float.MaxValue, null));
}
// Walk first node (START)
if (nodeMap.ContainsKey(Start.ItemUID) == false)
{
// Nope
return;
}
if (nodeMap.ContainsKey(End.ItemUID) == false)
{
// Nope
return;
}
// <Weight, LastItem>
nodeMap[Start.ItemUID] = new Tuple<float, Ets2Item>(0, null);
while (nodesToWalk.Any())
{
float distanceWalked = float.MaxValue;
Ets2Item toWalk = null;
foreach (var node in nodesToWalk)
{
var dTmp = nodeMap[node.ItemUID].Item1;
if (dTmp != float.MaxValue && distanceWalked > dTmp)
{
distanceWalked = dTmp;
toWalk = node;
}
}
if (toWalk == null)
break;
nodesToWalk.Remove(toWalk);
var currentWeight = nodeMap[toWalk.ItemUID].Item1;
// Iterate all destination nodes from this node
foreach (var jump in toWalk.Navigation)
{
var newWeight = jump.Value.Item1 + currentWeight;
var newNode = jump.Key;
if (nodeMap.ContainsKey(newNode.ItemUID) && nodeMap[newNode.ItemUID].Item1 > newWeight)
nodeMap[newNode.ItemUID] = new Tuple<float, Ets2Item>(newWeight, toWalk);
// add route with weight + previous node
}
}
List<Ets2Item> routeNodes = new List<Ets2Item>();
List<Ets2Item> routeRoads = new List<Ets2Item>();
List<Ets2NavigationSegment> segments = new List<Ets2NavigationSegment>();
var goingViaNode = (ulong) 0;
var route = End;
while (route != null)
{
// we add this prefab to the route list
routeNodes.Add(route);
var prefabSeg = new Ets2NavigationSegment(route);
segments.Add(prefabSeg);
// find the next prefab in the route description
var gotoNew = nodeMap[route.ItemUID].Item2;
if (gotoNew == null) break;
// get a path from the current prefab to the new one
var path = route.Navigation[gotoNew];
var roadPath = path.Item3;
// add the path to road list
routeRoads.AddRange(roadPath);
segments.Add(new Ets2NavigationSegment(roadPath, prefabSeg));
// Set the new prefab as route
route = gotoNew;
}
routeNodes.Add(Start);
segments.Reverse();
Roads = routeRoads;
Prefabs = routeNodes.Select(x => new Tuple<Ets2Item, int, int>(x, 0, 0)).ToList();
Loading = false;
// TODO: find routes on prefabs
// The following code is a start to that, but not finished yet.
// It divides the route into segments, that describe the path(s) on a road or prefab to get from A to B.
// Find entry/exit of start/end segment
var foundDst = float.MaxValue;
var foundNode = default(Ets2Node);
// Find the closest road to startpoint
foreach (var node in segments[0].Prefab.NodesList)
{
var dst = node.Value.Point.DistanceTo(From);
if (foundDst > dst)
{
foundDst = dst;
foundNode = node.Value;
}
}
// We found the node; find the road that exists at this point
segments[0].Entry = foundNode;
foundDst = float.MaxValue;
foundNode = default(Ets2Node);
// Find the closest road to startpoint
foreach (var node in segments[segments.Count - 1].Prefab.NodesList)
{
var dst = node.Value.Point.DistanceTo(To);
if (foundDst > dst)
{
foundDst = dst;
foundNode = node.Value;
}
}
// We found the node; find the road that exists at this point
segments[segments.Count - 1].Exit = foundNode;
// Iterate all segments
for (int seg = 0; seg < segments.Count; seg++)
{
// Generate prefab routes
if (segments[seg].Type == Ets2NavigationSegmentType.Prefab)
{
var prevRoad = seg > 0 ? segments[seg - 1] : null;
var nextRoad = seg + 1 < segments.Count ? segments[seg + 1] : null;
// Link segments together
if (prevRoad != null) segments[seg].Entry = prevRoad.Entry;
if (nextRoad != null) segments[seg].Exit = nextRoad.Exit;
segments[seg].GenerateOptions(prevRoad,nextRoad);
}
// Generate lane data
if (segments[seg].Type == Ets2NavigationSegmentType.Road)
{
var prefFab = seg > 0 ? segments[seg - 1] : null;
var nextFab = seg + 1 < segments.Count ? segments[seg + 1] : null;
segments[seg].GenerateOptions(prefFab, nextFab);
}
}
//for (int seg = 1; seg < segments.Count - 1; seg++)
for (int seg = 0; seg < segments.Count; seg++)
{
// Validate routes
if (segments[seg].Type == Ets2NavigationSegmentType.Prefab)
{
var prevRoad = seg > 0 ? segments[seg - 1] : null;
var nextRoad = seg + 1 < segments.Count ? segments[seg + 1] : null;
foreach (var opt in segments[seg].Options)
{
if (prevRoad == null)
{
// start point; validate if it is close to our start node
if (opt.Points.FirstOrDefault().DistanceTo(segments[seg].Entry.Point) < 10)
{
opt.EntryLane = 0; // yep; sure
}
}
else
{
var entryPoint = opt.Points.FirstOrDefault();
foreach (var roadOpt in prevRoad.Options)
{
if (roadOpt.Points.Any(x => x.CloseTo(entryPoint)))
{
// We've got a match ! :D
opt.EntryLane = roadOpt.ExitLane;
roadOpt.Valid = roadOpt.EntryLane >= 0 && roadOpt.ExitLane >= 0;
}
}
}
if (nextRoad == null)
{
// last point.
if (opt.Points.FirstOrDefault().DistanceTo(segments[seg].Exit.Point) < 10)
{
opt.ExitLane = 0; // yep; sure
}
}
else
{
var exitPoint = opt.Points.LastOrDefault();
foreach (var roadOpt in nextRoad.Options)
{
if (roadOpt.Points.Any(x => x.CloseTo(exitPoint)))
{
// We've got a match ! :D
opt.ExitLane= roadOpt.EntryLane;
roadOpt.Valid = roadOpt.EntryLane >= 0 && roadOpt.ExitLane >= 0;
}
}
}
opt.Valid = opt.EntryLane >= 0 && opt.ExitLane >= 0;
}
}
// Generate prefab routes
if (segments[seg].Type == Ets2NavigationSegmentType.Road && false)
{
var nextPrefab = segments[seg + 1];
var prevPrefab = segments[seg - 1];
if (nextPrefab.Type != Ets2NavigationSegmentType.Prefab ||
prevPrefab.Type != Ets2NavigationSegmentType.Prefab)
continue;
// Deduct road options by matching entry/exits
for (int solI = 0; solI < segments[seg].Options.Count; solI++)
{
// Find if there is any route in prefab that matches our entry lane
var okStart = prevPrefab.Options.Any(x => segments[seg].MatchEntry(solI, prevPrefab));
var okEnd = nextPrefab.Options.Any(x => segments[seg].MatchExit(solI, nextPrefab));
// This road has a valid end & Start
if (okStart && okEnd)
{
segments[seg].Options[solI].Valid = true;
}
}
}
}
// There is probably only 1 valid solution for entry/exit
//if (segments[0].Options.Any()) segments[0].Options[0].Valid = true;
//if (segments[segments.Count - 1].Options.Any()) segments[segments.Count - 1].Options[0].Valid = true;
Segments = segments;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="LoginView.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System.Collections;
using System.ComponentModel;
using System.Security.Permissions;
using System.Security.Principal;
using System.Web.Security;
using System.Web.UI;
/// <devdoc>
/// Renders exactly one of its templates, chosen by whether a user is logged in
/// and the roles that contain the user.
/// </devdoc>
[
Bindable(false),
ParseChildren(true),
PersistChildren(false),
Designer("System.Web.UI.Design.WebControls.LoginViewDesigner," + AssemblyRef.SystemDesign),
DefaultProperty("CurrentView"),
DefaultEvent("ViewChanged"),
Themeable(true),
]
public class LoginView : Control, INamingContainer {
private RoleGroupCollection _roleGroups;
private ITemplate _loggedInTemplate;
private ITemplate _anonymousTemplate;
private int _templateIndex;
private const int anonymousTemplateIndex = 0;
private const int loggedInTemplateIndex = 1;
private const int roleGroupStartingIndex = 2;
private static readonly object EventViewChanging = new object();
private static readonly object EventViewChanged = new object();
/// <devdoc>
/// Template shown when no user is logged in.
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(LoginView)),
]
public virtual ITemplate AnonymousTemplate {
get {
return _anonymousTemplate;
}
set {
_anonymousTemplate = value;
}
}
[
Browsable(true),
]
public override bool EnableTheming {
get {
return base.EnableTheming;
}
set {
base.EnableTheming = value;
}
}
[
Browsable(true),
]
public override string SkinID {
get {
return base.SkinID;
}
set {
base.SkinID = value;
}
}
/// <devdoc>
/// Copied from CompositeControl. This control does not extend CompositeControl because it should not be a WebControl.
/// </devdoc>
public override ControlCollection Controls {
get {
EnsureChildControls();
return base.Controls;
}
}
/// <devdoc>
/// Copied from CompositeControl. This control does not extend CompositeControl because it should not be a WebControl.
/// Does not call Base.DataBind(), since we need to call EnsureChildControls() between
/// OnDataBinding() and DataBindChildren().
/// </devdoc>
public override void DataBind() {
// Do our own databinding
OnDataBinding(EventArgs.Empty);
EnsureChildControls();
// Do all of our children's databinding
DataBindChildren();
}
/// <devdoc>
/// Template shown when a user is logged in, but the user is not in any role associated with a template.
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(LoginView)),
]
public virtual ITemplate LoggedInTemplate {
get {
return _loggedInTemplate;
}
set {
_loggedInTemplate = value;
}
}
/// <devdoc>
/// Maps groups of roles to templates.
/// </devdoc>
[
WebCategory("Behavior"),
MergableProperty(false),
Themeable(false),
Filterable(false),
PersistenceMode(PersistenceMode.InnerProperty),
WebSysDescription(SR.LoginView_RoleGroups)
]
public virtual RoleGroupCollection RoleGroups {
get {
if (_roleGroups == null) {
_roleGroups = new RoleGroupCollection();
}
return _roleGroups;
}
}
/// <devdoc>
/// Index of the template rendered on the previous page load. Saved in ControlState.
/// 0: AnonymousTemplate
/// 1: LoggedInTemplate
/// >=2: RoleGroup template with index n-2
/// </devdoc>
private int TemplateIndex {
get {
return _templateIndex;
}
set {
if (value != TemplateIndex) {
OnViewChanging(EventArgs.Empty);
_templateIndex = value;
ChildControlsCreated = false;
OnViewChanged(EventArgs.Empty);
}
}
}
/// <devdoc>
/// Raised after the view is changed.
/// </devdoc>
[
WebCategory("Action"),
WebSysDescription(SR.LoginView_ViewChanged)
]
public event EventHandler ViewChanged {
add {
Events.AddHandler(EventViewChanged, value);
}
remove {
Events.RemoveHandler(EventViewChanged, value);
}
}
/// <devdoc>
/// Raised before the view is changed. Not cancellable, because the view is changed
/// when the logged-in user changes, and it wouldn't make sense to cancel this.
/// </devdoc>
[
WebCategory("Action"),
WebSysDescription(SR.LoginView_ViewChanging)
]
public event EventHandler ViewChanging {
add {
Events.AddHandler(EventViewChanging, value);
}
remove {
Events.RemoveHandler(EventViewChanging, value);
}
}
/// <devdoc>
/// Instantiate the appropriate template.
/// </devdoc>
protected internal override void CreateChildControls() {
Controls.Clear();
// For the first request, set _templateIndex now, so the correct template is
// instantiated and we do not raise the ViewChanging/ViewChanged events.
Page page = Page;
if (page != null && !page.IsPostBack && !DesignMode) {
_templateIndex = GetTemplateIndex();
}
int templateIndex = TemplateIndex;
ITemplate template = null;
switch (templateIndex) {
case anonymousTemplateIndex:
template = AnonymousTemplate;
break;
case loggedInTemplateIndex:
template = LoggedInTemplate;
break;
default:
int roleGroupIndex = templateIndex - roleGroupStartingIndex;
RoleGroupCollection roleGroups = RoleGroups;
if (0 <= roleGroupIndex && roleGroupIndex < roleGroups.Count) {
template = roleGroups[roleGroupIndex].ContentTemplate;
}
break;
}
if (template != null) {
Control templateContainer = new Control();
template.InstantiateIn(templateContainer);
Controls.Add(templateContainer);
}
}
[
EditorBrowsable(EditorBrowsableState.Never),
]
public override void Focus() {
throw new NotSupportedException(SR.GetString(SR.NoFocusSupport, this.GetType().Name));
}
/// <devdoc>
/// Loads the control state for those properties that should persist across postbacks
/// even when EnableViewState=false.
/// </devdoc>
protected internal override void LoadControlState(object savedState) {
if (savedState != null) {
Pair state = (Pair)savedState;
if (state.First != null) {
base.LoadControlState(state.First);
}
if (state.Second != null) {
_templateIndex = (int)state.Second;
}
}
}
protected internal override void OnInit(EventArgs e) {
base.OnInit(e);
if (Page != null) {
Page.RegisterRequiresControlState(this);
}
}
/// <devdoc>
/// Sets the TemplateIndex based on the current user.
/// </devdoc>
protected internal override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
TemplateIndex = GetTemplateIndex();
// This is called in Control.PreRenderRecursiveInteral, but we need to call it again
// since we may have changed the TemplateIndex
EnsureChildControls();
}
/// <devdoc>
/// Raises the ViewChanged event.
/// </devdoc>
protected virtual void OnViewChanged(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventViewChanged];
if (handler != null) {
handler(this, e);
}
}
/// <devdoc>
/// Raises the ViewChanging event.
/// </devdoc>
protected virtual void OnViewChanging(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventViewChanging];
if (handler != null) {
handler(this, e);
}
}
protected internal override void Render(HtmlTextWriter writer) {
EnsureChildControls();
base.Render(writer);
}
/// <devdoc>
/// Saves the control state for those properties that should persist across postbacks
/// even when EnableViewState=false.
/// </devdoc>
protected internal override object SaveControlState() {
object baseState = base.SaveControlState();
if (baseState != null || _templateIndex != 0) {
object templateIndexState = null;
if (_templateIndex != 0) {
templateIndexState = _templateIndex;
}
return new Pair(baseState, templateIndexState);
}
return null;
}
/// <devdoc>
/// Allows the designer to set the TemplateIndex, so the different templates can be shown in the designer.
/// </devdoc>
[SecurityPermission(SecurityAction.Demand, Unrestricted = true)]
protected override void SetDesignModeState(IDictionary data) {
if (data != null) {
object o = data["TemplateIndex"];
if (o != null) {
TemplateIndex = (int)o;
// Note: we always recreate the child controls in the designer to correctly handle the case of
// the currently selected role group being deleted. This is necessary because the
// setter for TemplateIndex won't recreate the controls if the TemplateIndex is unchanged,
// which is the case when deleting all but the last role group. [Fix for Bug 148406]
ChildControlsCreated = false;
}
}
}
private int GetTemplateIndex() {
if (!DesignMode && Page != null && Page.Request.IsAuthenticated) {
IPrincipal user = LoginUtil.GetUser(this);
int roleGroupIndex = -1;
// Unlikely but possible for Page.Request.IsAuthenticated to be true and
// user to be null.
if (user != null) {
roleGroupIndex = RoleGroups.GetMatchingRoleGroupInternal(user);
}
if (roleGroupIndex >= 0) {
return roleGroupIndex + roleGroupStartingIndex;
}
else {
return loggedInTemplateIndex;
}
}
else {
return anonymousTemplateIndex;
}
}
}
}
| |
// 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 Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PagingOperations operations.
/// </summary>
public partial interface IPagingOperations
{
/// <summary>
/// A paging operation that finishes on the first call without a
/// nextlink
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// 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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink in odata format that
/// has 10 pages
/// </summary>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// 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="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<IPage<Product>>> GetOdataMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesWithOffsetWithHttpMessagesAsync(PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetryFirstWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetrySecondWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesFailureWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureUriWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFragmentNextLinkWithHttpMessagesAsync(string apiVersion, string tenant, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// with parameters grouped
/// </summary>
/// <param name='customParameterGroup'>
/// 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="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFragmentWithGroupingNextLinkWithHttpMessagesAsync(CustomParameterGroup customParameterGroup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> NextFragmentWithHttpMessagesAsync(string apiVersion, string tenant, string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='customParameterGroup'>
/// 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="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> NextFragmentWithGroupingWithHttpMessagesAsync(string nextLink, CustomParameterGroup customParameterGroup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that finishes on the first call without a
/// nextlink
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink in odata format that
/// has 10 pages
/// </summary>
/// <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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetOdataMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <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='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <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='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <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='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetSinglePagesFailureNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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>
Task<AzureOperationResponse<IPage<Product>>> GetMultiplePagesFailureUriNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
#region copyright
// VZF
// Copyright (C) 2014-2016 Vladimir Zakharov
//
// http://www.code.coolhobby.ru/
// File Db.cs created on 2.6.2015 in 6:29 AM.
// Last changed on 5.20.2016 in 3:20 PM.
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#endregion
namespace VZF.Data.Postgre
{
using System.Collections.Generic;
using System.Text;
using VZF.Types.Objects;
using YAF.Classes;
using YAF.Types;
/// <summary>
/// All the Database functions for YAF
/// </summary>
public static class Db
{
// added vzrus
#region ConnectionStringOptions
/// <summary>
/// Gets the provider assembly name.
/// </summary>
public static string ProviderAssemblyName
{
get
{
return "Npgsql";
}
}
/// <summary>
/// Gets a value indicating whether password placeholder visible.
/// </summary>
public static bool PasswordPlaceholderVisible
{
get
{
return true;
}
}
#endregion
public static bool DbInstallTransactions
{
get { return true; }
}
/// <summary>
/// The full text supported.
/// </summary>
public static bool FullTextSupported = false;
/// <summary>
/// The full text script.
/// </summary>
public static string FullTextScript = "postgre/fulltext.sql";
#region Miscelaneous vzrus addons
#region reindex page controls
// DB Maintenance page buttons name
/// <summary>
/// Gets a value indicating whether panel get stats.
/// </summary>
public static bool PanelGetStats
{
get
{
return true;
}
}
/// <summary>
/// Gets a value indicating whether panel recovery mode.
/// </summary>
public static bool PanelRecoveryMode
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether panel reindex.
/// </summary>
public static bool PanelReindex
{
get
{
return true;
}
}
/// <summary>
/// Gets a value indicating whether panel shrink.
/// </summary>
public static bool PanelShrink
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether btn reindex visible.
/// </summary>
public static bool btnReindexVisible
{
get
{
return true;
}
}
/// <summary>
/// Gets the sql scripts delimiter regex pattern.
/// </summary>
public static string SqlScriptsDelimiterRegexPattern
{
get
{
return "(?:--GO)";
}
}
#endregion
/// <summary>
/// The db_reindex_warning.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_reindex_warning()
{
return "Operation completed. Database tables reindexing can take a lot of time.";
}
/// <summary>
/// The db_getstats_warning.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_getstats_warning()
{
return
"Operation completed. Vacuum operation blocks all database objects! If there is a lot of indexes, the database can be blocked for a long time. Choose a right timing!";
}
/// <summary>
/// Gets ScriptFolder.
/// </summary>
public static string ScriptFolder
{
get
{
return "pgsql";
}
}
#endregion
#region Touradg Mods
// Shinking Operation
/// <summary>
/// The db_shrink_warning.
/// </summary>
/// <param name="connectionString">
/// The connection string.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_shrink_warning()
{
return string.Empty;
}
/// <summary>
/// The db_shrink_new.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_shrink_new(out string message)
{
message = "Vacuum full operation is completed";
return "VACUUM FULL;";
}
/// <summary>
/// The db_recovery_mode_new.
/// </summary>
/// <param name="connectionString">
/// The connection string.
/// </param>
/// <param name="dbRecoveryMode">
/// The db recovery mode.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_recovery_mode_new([NotNull] string connectionString, string dbRecoveryMode)
{
return string.Empty;
}
/// <summary>
/// The db_recovery_mode_warning.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_recovery_mode_warning()
{
return string.Empty;
}
/// <summary>
/// Gets the connection parameters.
/// </summary>
public static List<ConnectionStringParameter> ConnectionParameters
{
get
{
var cstr = new StringBuilder();
var connectionParametersBuilder = new List<ConnectionStringParameter>
{
new ConnectionStringParameter(
"Host",
typeof(string),
"localhost",
false),
new ConnectionStringParameter(
"Port",
typeof(string),
"5432",
false),
new ConnectionStringParameter(
"Database",
typeof(string),
"yafnet",
false),
new ConnectionStringParameter(
"CommandTimeout",
typeof(string),
"120",
false),
new ConnectionStringParameter(
"Pooling",
typeof(string),
"true",
false),
new ConnectionStringParameter(
"PreloadReader",
typeof(string),
"true",
false),
new ConnectionStringParameter(
"Database",
typeof(string),
"5432",
false),
new ConnectionStringParameter(
"SyncNotification",
typeof(string),
"true",
false),
new ConnectionStringParameter(
"UseExtendedTypes",
typeof(string),
"true",
false),
new ConnectionStringParameter(
"SSL",
typeof(string),
"false",
false),
new ConnectionStringParameter(
"IntegratedSecurity",
typeof(string),
"false",
false),
new ConnectionStringParameter(
"UserName",
typeof(string),
"admin",
false),
new ConnectionStringParameter(
"Password",
typeof(string),
"password",
false)
};
return connectionParametersBuilder;
}
}
/// <summary>
/// The db_reindex_new.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_reindex_new()
{
// VACUUM ANALYZE VERBOSE;VACUUM cannot be implemeneted within function or multiline command line string
return string.Format(@"REINDEX DATABASE {0};", Config.DatabaseSchemaName);
// ex.Message + "\r\n" + ex.StackTrace
}
/// <summary>
/// The db_getstats.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_getstats(out string message)
{
message = "Vacuume analize completed successfully.";
return "VACUUM ANALYZE VERBOSE;";
}
/// <summary>
/// The db_getfirstcharset.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_getfirstcharset()
{
return string.Empty;
}
/// <summary>
/// The db_getfirstcollation.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_getfirstcollation()
{
return string.Empty;
}
/// <summary>
/// The db_checkvalidcharset.
/// </summary>
/// <param name="charsetColumn">
/// The charset column.
/// </param>
/// <param name="value">
/// The value.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_checkvalidcharset(out string charsetColumn, out string value)
{
charsetColumn = value = string.Empty;
return string.Empty;
}
/// <summary>
/// The db_collations_data.
/// </summary>
/// <param name="charsetColumn">
/// The charset column.
/// </param>
/// <param name="collationColumn">
/// The collation column.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string db_collations_data(out string charsetColumn, out string collationColumn)
{
charsetColumn = collationColumn = string.Empty;
return string.Empty;
}
public static string GetProfileStructure()
{
return "select * from {0} limit 1;";
}
#endregion
}
}
| |
using UnityEngine;
using System.IO;
#if UNITY_EDITOR
using UnityEditor;
[InitializeOnLoad]
#endif
public class FBSettings : ScriptableObject
{
const string facebookSettingsAssetName = "FacebookSettings";
const string facebookSettingsPath = "Facebook/Resources";
const string facebookSettingsAssetExtension = ".asset";
private static FBSettings instance;
public static FBSettings Instance {
get {
if (instance == null) {
instance = Resources.Load (facebookSettingsAssetName) as FBSettings;
if (instance == null) {
// If not found, autocreate the asset object.
instance = CreateInstance<FBSettings> ();
#if UNITY_EDITOR
string properPath = Path.Combine (Application.dataPath, facebookSettingsPath);
if (!Directory.Exists (properPath)) {
AssetDatabase.CreateFolder ("Assets/Facebook", "Resources");
}
string fullPath = Path.Combine (Path.Combine ("Assets", facebookSettingsPath),
facebookSettingsAssetName + facebookSettingsAssetExtension
);
AssetDatabase.CreateAsset (instance, fullPath);
#endif
}
}
return instance;
}
}
#if UNITY_EDITOR
[MenuItem("Facebook/Edit Settings")]
public static void Edit ()
{
Selection.activeObject = Instance;
}
[MenuItem("Facebook/Developers Page")]
public static void OpenAppPage ()
{
string url = "https://developers.facebook.com/apps/";
if (Instance.AppIds [Instance.SelectedAppIndex] != "0")
url += Instance.AppIds [Instance.SelectedAppIndex];
Application.OpenURL (url);
}
[MenuItem("Facebook/SDK Documentation")]
public static void OpenDocumentation ()
{
string url = "https://developers.facebook.com/games/unity/";
Application.OpenURL (url);
}
[MenuItem("Facebook/SDK Facebook Group")]
public static void OpenFacebookGroup ()
{
string url = "https://www.facebook.com/groups/491736600899443/";
Application.OpenURL (url);
}
[MenuItem("Facebook/Report a SDK Bug")]
public static void ReportABug ()
{
string url = "https://developers.facebook.com/bugs/create";
Application.OpenURL (url);
}
#endif
#region App Settings
[SerializeField]
private int
selectedAppIndex = 0;
[SerializeField]
private string[]
appIds = new[] { "0" };
[SerializeField]
private string[]
appLabels = new[] { "App Name" };
[SerializeField]
private bool
cookie = true;
[SerializeField]
private bool
logging = true;
[SerializeField]
private bool
status = true;
[SerializeField]
private bool
xfbml = false;
[SerializeField]
private bool
frictionlessRequests = true;
[SerializeField]
private string
iosURLSuffix = "";
public void SetAppIndex (int index)
{
if (selectedAppIndex != index) {
selectedAppIndex = index;
DirtyEditor ();
}
}
public int SelectedAppIndex {
get { return selectedAppIndex; }
}
public void SetAppId (int index, string value)
{
if (appIds [index] != value) {
appIds [index] = value;
DirtyEditor ();
}
}
public string[] AppIds {
get { return appIds; }
set {
if (appIds != value) {
appIds = value;
DirtyEditor ();
}
}
}
public void SetAppLabel (int index, string value)
{
if (appLabels [index] != value) {
AppLabels [index] = value;
DirtyEditor ();
}
}
public string[] AppLabels {
get { return appLabels; }
set {
if (appLabels != value) {
appLabels = value;
DirtyEditor ();
}
}
}
public static string[] AllAppIds {
get {
return Instance.AppIds;
}
}
public static string AppId {
get {
return Instance.AppIds [Instance.SelectedAppIndex];
}
}
public static bool IsValidAppId {
get {
return FBSettings.AppId != null
&& FBSettings.AppId.Length > 0
&& !FBSettings.AppId.Equals ("0");
}
}
public static bool Cookie {
get { return Instance.cookie; }
set {
if (Instance.cookie != value) {
Instance.cookie = value;
DirtyEditor ();
}
}
}
public static bool Logging {
get { return Instance.logging; }
set {
if (Instance.logging != value) {
Instance.logging = value;
DirtyEditor ();
}
}
}
public static bool Status {
get { return Instance.status; }
set {
if (Instance.status != value) {
Instance.status = value;
DirtyEditor ();
}
}
}
public static bool Xfbml {
get { return Instance.xfbml; }
set {
if (Instance.xfbml != value) {
Instance.xfbml = value;
DirtyEditor ();
}
}
}
public static string IosURLSuffix {
get { return Instance.iosURLSuffix; }
set {
if (Instance.iosURLSuffix != value) {
Instance.iosURLSuffix = value;
DirtyEditor ();
}
}
}
public static string ChannelUrl {
get { return "/channel.html"; }
}
public static bool FrictionlessRequests {
get { return Instance.frictionlessRequests; }
set {
if (Instance.frictionlessRequests != value) {
Instance.frictionlessRequests = value;
DirtyEditor ();
}
}
}
#if UNITY_EDITOR
private string testFacebookId = "";
private string testAccessToken = "";
public static string TestFacebookId {
get { return Instance.testFacebookId; }
set {
if (Instance.testFacebookId != value) {
Instance.testFacebookId = value;
DirtyEditor ();
}
}
}
public static string TestAccessToken {
get { return Instance.testAccessToken; }
set {
if (Instance.testAccessToken != value) {
Instance.testAccessToken = value;
DirtyEditor ();
}
}
}
#endif
private static void DirtyEditor ()
{
#if UNITY_EDITOR
EditorUtility.SetDirty (Instance);
#endif
}
#endregion
}
| |
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Paramore.Darker.Testing;
using Paramore.Darker.Testing.Ports;
using Shouldly;
using Xunit;
namespace Paramore.Darker.Tests
{
public class FakeQueryProcessorTests
{
[Fact]
public void ReturnsExecutedQueries()
{
// Arrange
var guid = Guid.NewGuid();
var queryProcessor = new FakeQueryProcessor();
// Act
queryProcessor.Execute(new TestQueryA(guid));
queryProcessor.Execute(new TestQueryB(100));
queryProcessor.Execute(new TestQueryB(200));
queryProcessor.Execute(new TestQueryB(300));
// Assert
queryProcessor.GetExecutedQueries().Count().ShouldBe(4);
queryProcessor.GetExecutedQueries<TestQueryA>().Count().ShouldBe(1);
queryProcessor.GetExecutedQueries<TestQueryB>().Count().ShouldBe(3);
queryProcessor.GetExecutedQueries<TestQueryC>().Count().ShouldBe(0);
queryProcessor.GetExecutedQueries<TestQueryA>().Single().Id.ShouldBe(guid);
queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(0).Number.ShouldBe(100);
queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(1).Number.ShouldBe(200);
queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(2).Number.ShouldBe(300);
}
[Fact]
public async Task ReturnsExecutedQueriesAsync()
{
// Arrange
var guid = Guid.NewGuid();
var queryProcessor = new FakeQueryProcessor();
// Act
await queryProcessor.ExecuteAsync(new TestQueryA(guid));
await queryProcessor.ExecuteAsync(new TestQueryB(100));
await queryProcessor.ExecuteAsync(new TestQueryB(200));
await queryProcessor.ExecuteAsync(new TestQueryB(300));
// Assert
queryProcessor.GetExecutedQueries().Count().ShouldBe(4);
queryProcessor.GetExecutedQueries<TestQueryA>().Count().ShouldBe(1);
queryProcessor.GetExecutedQueries<TestQueryB>().Count().ShouldBe(3);
queryProcessor.GetExecutedQueries<TestQueryC>().Count().ShouldBe(0);
queryProcessor.GetExecutedQueries<TestQueryA>().Single().Id.ShouldBe(guid);
queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(0).Number.ShouldBe(100);
queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(1).Number.ShouldBe(200);
queryProcessor.GetExecutedQueries<TestQueryB>().ElementAt(2).Number.ShouldBe(300);
}
[Fact]
public void ReturnsDefaultValueOfQueriesWithoutSetup()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupResultFor<TestQueryB>(1234);
// Act
var result = queryProcessor.Execute(new TestQueryA(Guid.NewGuid()));
// Assert
result.ShouldBe(default(Guid));
}
[Fact]
public void ReturnsValueThatWasSetUpForQuery()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupResultFor<TestQueryB>(1234);
// Act
var result = queryProcessor.Execute(new TestQueryB(1337));
// Assert
result.ShouldBe(1234);
}
[Fact]
public void ReturnsValueThatWasSetUpForQueryWithPredicate()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, 1234);
// Act
var result = queryProcessor.Execute(new TestQueryB(1337));
// Assert
result.ShouldBe(1234);
}
[Fact]
public void ReturnsComputedValueThatWasSetUpForQueryWithPredicate()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, q => (int)q.Number);
// Act
var result = queryProcessor.Execute(new TestQueryB(1337));
// Assert
result.ShouldBe(1337);
}
[Fact]
public void ReturnsDefaultValueIfQueryDoesntMatchPredicate()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, 1234);
// Act
var result = queryProcessor.Execute(new TestQueryB(9999));
// Assert
result.ShouldBe(default(int));
}
[Fact]
public void ThrowsForQueryWithThrowSetup()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupExceptionFor<TestQueryB>(new AbandonedMutexException());
// Act + Assert
Assert.Throws<AbandonedMutexException>(() => queryProcessor.Execute(new TestQueryB(1337)));
}
[Fact]
public void ThrowsForQueryWithThrowSetupMatchingPredicate()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupExceptionFor<TestQueryB>(q => q.Number == 1337, new AbandonedMutexException());
// Act + Assert
Assert.Throws<AbandonedMutexException>(() => queryProcessor.Execute(new TestQueryB(1337)));
}
[Fact]
public void DoesNotThrowIfQueryDoesntMatchPredicate()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupExceptionFor<TestQueryB>(q => q.Number == 1337, new AbandonedMutexException());
// Act
var result = queryProcessor.Execute(new TestQueryB(9999));
// Assert
result.ShouldBe(default(int));
}
[Fact]
public async Task ReturnsDefaultValueOfQueriesWithoutSetupAsync()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupResultFor<TestQueryB>(1234);
// Act
var result = await queryProcessor.ExecuteAsync(new TestQueryA(Guid.NewGuid()));
// Assert
result.ShouldBe(default(Guid));
}
[Fact]
public async Task ReturnsValueThatWasSetUpForQueryAsync()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupResultFor<TestQueryB>(1234);
// Act
var result = await queryProcessor.ExecuteAsync(new TestQueryB(1337));
// Assert
result.ShouldBe(1234);
}
[Fact]
public async Task ReturnsValueThatWasSetUpForQueryWithPredicateAsync()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, 1234);
// Act
var result = await queryProcessor.ExecuteAsync(new TestQueryB(1337));
// Assert
result.ShouldBe(1234);
}
[Fact]
public async Task ReturnsComputedValueThatWasSetUpForQueryWithPredicateAsync()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, q => (int)q.Number);
// Act
var result = await queryProcessor.ExecuteAsync(new TestQueryB(1337));
// Assert
result.ShouldBe(1337);
}
[Fact]
public async Task ReturnsDefaultValueIfQueryDoesntMatchPredicateAsync()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupResultFor<TestQueryB>(q => q.Number == 1337, 1234);
// Act
var result = await queryProcessor.ExecuteAsync(new TestQueryB(9999));
// Assert
result.ShouldBe(default(int));
}
[Fact]
public async Task ThrowsForQueryWithThrowSetupAsync()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupExceptionFor<TestQueryB>(new AbandonedMutexException());
// Act + Assert
await Assert.ThrowsAsync<AbandonedMutexException>(async () => await queryProcessor.ExecuteAsync(new TestQueryB(1337)));
}
[Fact]
public async Task ThrowsForQueryWithThrowSetupMatchingPredicateAsync()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupExceptionFor<TestQueryB>(q => q.Number == 1337, new AbandonedMutexException());
// Act + Assert
await Assert.ThrowsAsync<AbandonedMutexException>(async () => await queryProcessor.ExecuteAsync(new TestQueryB(1337)));
}
[Fact]
public async Task DoesNotThrowIfQueryDoesntMatchPredicateAsync()
{
// Arrange
var queryProcessor = new FakeQueryProcessor();
queryProcessor.SetupExceptionFor<TestQueryB>(q => q.Number == 1337, new AbandonedMutexException());
// Act
var result = await queryProcessor.ExecuteAsync(new TestQueryB(9999));
// Assert
result.ShouldBe(default(int));
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using NUnit.Framework;
using Moq;
using Rothko.Model;
using Rothko.Interfaces.Services;
using Rothko.Interfaces.Components;
using Rothko.Services;
namespace Rothko.Tests.Services
{
[TestFixture]
public class UnitRangeServiceTests
{
private const int U = 0;
private const int R = 1;
private const int N = 2;
private const int E = 3;
private IUnitRangeService _UnitRangeService;
[SetUp]
public void SetUp()
{
_UnitRangeService = new UnitRangeService();
}
[Test]
public void TestUnitRangeOneRangePointNoDeadZonePoints ()
{
int [,]expectedRangeMap = new int [,]
{
{ N, N, N, N, N },
{ N, N, R, N, N },
{ N, R, U, R, N },
{ N, N, R, N, N },
{ N, N, N, N, N }
};
AssertUnitRange(expectedRangeMap, 1, 0);
}
[Test]
public void TestUnitRangeOneRangePointOneDeadZonePoints ()
{
int [,]expectedRangeMap = new int [,]
{
{ N, N, R, N, N },
{ N, R, N, R, N },
{ R, N, U, N, R },
{ N, R, N, R, N },
{ N, N, R, N, N }
};
AssertUnitRange(expectedRangeMap, 1, 1);
}
[Test]
public void TestUnitRangeOneRangePointTwoDeadZonePoints ()
{
int [,]expectedRangeMap = new int [,]
{
{ N, R, N, R, N },
{ R, N, N, N, R },
{ N, N, U, N, N },
{ R, N, N, N, R },
{ N, R, N, R, N }
};
AssertUnitRange(expectedRangeMap, 1, 2);
}
[Test]
public void TestUnitRangeTwoRangePointNoDeadZonePoints ()
{
int [,]expectedRangeMap = new int [,]
{
{ N, N, R, N, N },
{ N, R, R, R, N },
{ R, R, U, R, R },
{ N, R, R, R, N },
{ N, N, R, N, N }
};
AssertUnitRange(expectedRangeMap, 2, 0);
}
[Test]
public void TestUnitRangeTwoRangePointOneDeadZonePoints ()
{
int [,]expectedRangeMap = new int [,]
{
{ N, R, R, R, N },
{ R, R, N, R, R },
{ R, N, U, N, R },
{ R, R, N, R, R },
{ N, R, R, R, N }
};
AssertUnitRange(expectedRangeMap, 2, 1);
}
[Test]
public void TestUnitRangeTwoRangePointOneDeadZonePointsFromTheTopLeft ()
{
int [,]expectedRangeMap = new int [,]
{
{ U, N, R, R, N },
{ N, R, R, N, N },
{ R, R, N, N, N },
{ R, N, N, N, N },
{ N, N, N, N, N }
};
AssertUnitRange(expectedRangeMap, 2, 1);
}
[Test]
public void TestUnitRangeOneRangePointZeroDeadZonePoints ()
{
int [,]expectedRangeMap = new int [,]
{
{ E, N, E, N, N },
{ N, E, N, N, N },
{ N, N, U, R, N },
{ N, N, N, E, N },
{ N, N, N, N, E }
};
AssertEnemyUnitsOnRange(expectedRangeMap, 1, 0);
}
[Test]
public void TestUnitRangeTwoRangePointZeroDeadZonePoints ()
{
int [,]expectedRangeMap = new int [,]
{
{ E, N, R, N, N },
{ N, R, N, N, N },
{ N, N, U, R, N },
{ N, N, N, R, N },
{ N, N, N, N, E }
};
AssertEnemyUnitsOnRange(expectedRangeMap, 2, 0);
}
[Test]
public void TestUnitRangeSpecifyingPosition ()
{
int [,]expectedRangeMap = new int [,]
{
{ U, N, N, R, E },
{ E, E, R, N, N },
{ N, N, E, N, N },
{ N, N, N, N, N },
{ N, N, N, N, N }
};
AssertEnemyUnitsOnRange(expectedRangeMap, 1, 0, 2, 0);
}
[Test]
public void TestUnitRangeSpecifyingPositionVariation ()
{
int [,]expectedRangeMap = new int [,]
{
{ N, E, R, E, N },
{ N, N, E, N, N },
{ N, N, E, N, N },
{ N, N, U, N, N },
{ N, N, R, N, N }
};
AssertEnemyUnitsOnRange(expectedRangeMap, 1, 1, 2, 2);
}
public void AssertEnemyUnitsOnRange(int [,] rangeMap, int rangePoints, int deadZoneRangePoints, int x, int y)
{
List<IPlottable> lstRangeLocations = _UnitRangeService
.GetEnemyUnitLocationsInAttackRange(GetUnitFromIntArray(rangeMap, rangePoints, deadZoneRangePoints),
GetLocationsFromIntArray(rangeMap), GetUnitsFromIntArray(rangeMap), x, y);
AssertExpectedRangeIsActualRange(GetLocationsFromIntArray(rangeMap, R), lstRangeLocations);
}
public void AssertEnemyUnitsOnRange(int [,] rangeMap, int rangePoints, int deadZoneRangePoints)
{
List<IPlottable> lstRangeLocations = _UnitRangeService
.GetEnemyUnitLocationsInAttackRange(GetUnitFromIntArray(rangeMap, rangePoints, deadZoneRangePoints),
GetLocationsFromIntArray(rangeMap), GetUnitsFromIntArray(rangeMap));
AssertExpectedRangeIsActualRange(GetLocationsFromIntArray(rangeMap, R), lstRangeLocations);
}
public void AssertUnitRange(int [,] rangeMap, int rangePoints, int deadZoneRangePoints)
{
List<IPlottable> lstRangeLocations = _UnitRangeService
.GetAttackRange(GetUnitFromIntArray(rangeMap, rangePoints, deadZoneRangePoints),
GetLocationsFromIntArray(rangeMap));
AssertExpectedRangeIsActualRange(GetLocationsFromIntArray(rangeMap, R), lstRangeLocations);
}
private void AssertExpectedRangeIsActualRange (List<IPlottable> expectedLocations, List<IPlottable> actualLocations)
{
foreach (var item in expectedLocations)
if (!actualLocations.Any(a => a.X == item.X && a.Y == item.Y))
Assert.Fail("Expected location at " + item.X + ", " + item.Y + " does not exist");
foreach (var item in actualLocations)
if (!expectedLocations.Any(e => e.X == item.X && e.Y == item.Y))
Assert.Fail("Actual location at " + item.X + ", " + item.Y + " was not expected");
Assert.Pass();
}
private List<IPlottable> GetLocationsFromIntArray (int[,] mapArray, int? filter = null)
{
List<IPlottable> locations = new List<IPlottable> ();
for (int y = 0; y < mapArray.GetLength(0); y++)
for (int x = 0; x < mapArray.GetLength(1); x++)
{
if (filter == null || mapArray[y, x] == filter.Value)
locations.Add (new Coordinate () { X = x, Y = y });
}
return locations;
}
private List<IUnitable> GetUnitsFromIntArray(int [,] mapArray)
{
List<IUnitable> lstEnemyUnits = new List<IUnitable>();
for (int y = 0; y < mapArray.GetLength(0); y++)
for (int x = 0; x < mapArray.GetLength(1); x++)
if (mapArray[y,x] == R ||
mapArray[y,x] == E)
lstEnemyUnits.Add (new Unit()
{
X = x,
Y = y,
HealthPoints = 10,
IDTeam = 2
});
return lstEnemyUnits;
}
private IUnitable GetUnitFromIntArray(int [,] mapArray, int rangePoints, int deadZoneRangePoints)
{
for (int y = 0; y < mapArray.GetLength(0); y++)
for (int x = 0; x < mapArray.GetLength(1); x++)
if (mapArray[y,x] == U)
return new Unit()
{
X = x,
Y = y,
HealthPoints = 10,
RangePoints = rangePoints,
DeadZoneRangePoints = deadZoneRangePoints,
IDTeam = 1
};
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 MBCorpHeatlhTestRestAPI.Areas.HelpPage.ModelDescriptions;
using MBCorpHeatlhTestRestAPI.Areas.HelpPage.Models;
namespace MBCorpHeatlhTestRestAPI.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;
}
if (complexTypeDescription != null)
{
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 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);
}
}
}
}
| |
/******************************************************************************
* The MIT License
* Copyright (c) 2003 Novell Inc. www.novell.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*******************************************************************************/
//
// Novell.Directory.Ldap.LdapConstraints.cs
//
// Author:
// Sunil Kumar ([email protected])
//
// (C) 2003 Novell, Inc (http://www.novell.com)
//
using System;
namespace Novell.Directory.Ldap
{
/// <summary> Defines options controlling Ldap operations on the directory.
///
/// An LdapConstraints object is always associated with an LdapConnection
/// object; its values can be changed with LdapConnection.setConstraints, or
/// overridden by passing an LdapConstraints object to an operation.
///
/// </summary>
/// <seealso cref="LdapConnection.Constraints">
/// </seealso>
public class LdapConstraints
{
/// <summary> Returns the maximum number of referrals to follow during automatic
/// referral following. The operation will be abandoned and terminated by
/// the API with a result code of LdapException.REFERRAL_LIMIT_EXCEEDED
/// if the number of referrals in a sequence exceeds the limit.
/// It is ignored for asynchronous operations.
///
/// </summary>
/// <returns> The maximum number of referrals to follow in sequence
///
/// </returns>
/// <seealso cref="HopLimit">
/// </seealso>
/// <seealso cref="LdapException.REFERRAL_LIMIT_EXCEEDED">
/// </seealso>
/// <summary> Sets the maximum number of referrals to follow in sequence during
/// automatic referral following.
///
/// </summary>
/// <param name="hop_limit">The maximum number of referrals to follow in a
/// sequence during automatic referral following.
/// The default value is 10. A value of 0 means no limit.
/// The operation will be abandoned and terminated by the
/// API with a result code of
/// LdapException.REFERRAL_LIMIT_EXCEEDED if the
/// number of referrals in a sequence exceeds the limit.
/// It is ignored for asynchronous operations.
///
/// </param>
/// <seealso cref="LdapException.REFERRAL_LIMIT_EXCEEDED">
/// </seealso>
virtual public int HopLimit
{
get
{
return hopLimit;
}
set
{
hopLimit = value;
}
}
/// <summary> Gets all the properties of the constraints object which has been
/// assigned with {@link #setProperty(String, Object)}.
/// A value of <code>null</code> is returned if no properties are defined.
///
/// </summary>
/// <seealso cref="Object">
/// </seealso>
/// <seealso cref="LdapConnection.getProperty">
/// </seealso>
/// <summary> Sets all the properties of the constraints object.
///
/// </summary>
/// <param name="props">the properties represented by the Hashtable object to set.
/// </param>
virtual internal System.Collections.Hashtable Properties
{
/* package */
get
{
return properties;
}
/* package */
set
{
properties = (System.Collections.Hashtable)value.Clone();
}
}
/// <summary> Specified whether or not referrals are followed automatically.
///
/// </summary>
/// <returns> True if referrals are followed automatically, or
/// false if referrals throw an LdapReferralException.
/// </returns>
/// <summary> Specifies whether referrals are followed automatically or if
/// referrals throw an LdapReferralException.
///
/// Referrals of any type other than to an Ldap server (for example, a
/// referral URL other than ldap://something) are ignored on automatic
/// referral following.
///
/// The default is false.
///
/// </summary>
/// <param name="doReferrals"> True to follow referrals automatically.
/// False to throw an LdapReferralException if
/// the server returns a referral.
/// </param>
virtual public bool ReferralFollowing
{
get
{
return doReferrals;
}
set
{
doReferrals = value;
}
}
/// <summary> Returns the maximum number of milliseconds to wait for any operation
/// under these constraints.
///
/// If the value is 0, there is no maximum time limit on waiting
/// for operation results. The actual granularity of the timeout depends
/// platform. This limit is enforced the the API on an
/// operation, not by the server.
/// The operation will be abandoned and terminated by the
/// API with a result code of LdapException.Ldap_TIMEOUT if the
/// operation exceeds the time limit.
///
/// </summary>
/// <returns> The maximum number of milliseconds to wait for the operation.
///
/// </returns>
/// <seealso cref="LdapException.Ldap_TIMEOUT">
/// </seealso>
/// <summary> Sets the maximum number of milliseconds the client waits for
/// any operation under these constraints to complete.
///
/// If the value is 0, there is no maximum time limit enforced by the
/// API on waiting for the operation results. The actual granularity of
/// the timeout depends on the platform.
/// The operation will be abandoned and terminated by the
/// API with a result code of LdapException.Ldap_TIMEOUT if the
/// operation exceeds the time limit.
///
/// </summary>
/// <param name="msLimit"> The maximum milliseconds to wait.
///
/// </param>
/// <seealso cref="LdapException.Ldap_TIMEOUT">
/// </seealso>
virtual public int TimeLimit
{
get
{
return msLimit;
}
set
{
msLimit = value;
}
}
private int msLimit = 0;
private int hopLimit = 10;
private bool doReferrals = false;
private LdapReferralHandler refHandler = null;
private LdapControl[] controls = null;
private static object nameLock; // protect agentNum
private static int lConsNum = 0; // Debug, LdapConstraints num
private string name; // String name for debug
private System.Collections.Hashtable properties = null; // Properties
/// <summary> Constructs a new LdapConstraints object that specifies the default
/// set of constraints.
/// </summary>
public LdapConstraints()
{
// Get a unique constraints name for debug
}
/// <summary> Constructs a new LdapConstraints object specifying constraints that
/// control wait time, and referral handling.
///
/// </summary>
/// <param name="msLimit"> The maximum time in milliseconds to wait for results.
/// The default is 0, which means that there is no
/// maximum time limit. This limit is enforced for an
/// operation by the API, not by the server.
/// The operation will be abandoned and terminated by the
/// API with a result code of LdapException.Ldap_TIMEOUT
/// if the operation exceeds the time limit.
///
/// </param>
/// <param name="doReferrals">Determines whether to automatically follow
/// referrals or not. Specify true to follow
/// referrals automatically, and false to throw
/// an LdapReferralException if the server responds
/// with a referral. False is the default value.
/// The way referrals are followed automatically is
/// determined by the setting of the handler parameter.
/// It is ignored for asynchronous operations.
///
/// </param>
/// <param name="handler"> The custom authentication handler called when
/// LdapConnection needs to authenticate, typically on
/// following a referral. A null may be specified to
/// indicate default authentication processing, i.e.
/// referrals are followed with anonymous authentication.
/// The handler object may be an implemention of either the
/// LdapBindHandler or LdapAuthHandler interface.
/// The implementation of these interfaces determines how
/// authentication is performed when following referrals.
/// It is ignored for asynchronous operations.
///
/// </param>
/// <param name="hop_limit">The maximum number of referrals to follow in a
/// sequence during automatic referral following.
/// The default value is 10. A value of 0 means no limit.
/// The operation will be abandoned and terminated by the
/// API with a result code of
/// LdapException.REFERRAL_LIMIT_EXCEEDED if the
/// number of referrals in a sequence exceeds the limit.
/// It is ignored for asynchronous operations.
///
/// </param>
/// <seealso cref="LdapException.Ldap_TIMEOUT">
/// </seealso>
/// <seealso cref="LdapException.REFERRAL_LIMIT_EXCEEDED">
/// </seealso>
/// <seealso cref="LdapException.REFERRAL">
/// </seealso>
/// <seealso cref="LdapReferralException">
/// </seealso>
/// <seealso cref="LdapBindHandler">
/// </seealso>
/// <seealso cref="LdapAuthHandler">
/// </seealso>
public LdapConstraints(int msLimit, bool doReferrals, LdapReferralHandler handler, int hop_limit)
{
this.msLimit = msLimit;
this.doReferrals = doReferrals;
refHandler = handler;
hopLimit = hop_limit;
// Get a unique constraints name for debug
}
/// <summary> Returns the controls to be sent to the server.
///
/// </summary>
/// <returns> The controls to be sent to the server, or null if none.
///
/// </returns>
/// <seealso cref="Controls">
/// </seealso>
public virtual LdapControl[] getControls()
{
return controls;
}
/// <summary> Gets a property of the constraints object which has been
/// assigned with {@link #setProperty(String, Object)}.
///
/// </summary>
/// <param name="name"> Name of the property to be returned.
///
/// </param>
/// <returns> the object associated with the property,
/// or <code>null</code> if the property is not set.
///
/// </returns>
/// <seealso cref="Object">
/// </seealso>
/// <seealso cref="LdapConnection.getProperty(string)">
/// </seealso>
public virtual object getProperty(string name)
{
if (properties == null)
{
return null; // Requested property not available.
}
return properties[name];
}
/// <summary> Returns an object that can process authentication for automatic
/// referral handling.
///
/// It may be null.
///
/// </summary>
/// <returns> An LdapReferralHandler object that can process authentication.
/// </returns>
/*package*/
internal virtual LdapReferralHandler getReferralHandler()
{
return refHandler;
}
/// <summary> Sets a single control to be sent to the server.
///
/// </summary>
/// <param name="control"> A single control to be sent to the server or
/// null if none.
/// </param>
public virtual void setControls(LdapControl control)
{
if (control == null)
{
controls = null;
return;
}
controls = new LdapControl[1];
controls[0] = (LdapControl)control.Clone();
}
/// <summary> Sets controls to be sent to the server.
///
/// </summary>
/// <param name="controls"> An array of controls to be sent to the server or
/// null if none.
/// </param>
public virtual void setControls(LdapControl[] controls)
{
if ((controls == null) || (controls.Length == 0))
{
this.controls = null;
return;
}
this.controls = new LdapControl[controls.Length];
for (int i = 0; i < controls.Length; i++)
{
this.controls[i] = (LdapControl)controls[i].Clone();
}
return;
}
/// <summary> Sets a property of the constraints object.
///
/// No property names have been defined at this time, but the
/// mechanism is in place in order to support revisional as well as
/// dynamic and proprietary extensions to operation modifiers.
///
/// </summary>
/// <param name="name"> Name of the property to set.
///
/// </param>
/// <param name="value"> Value to assign to the property.
/// property is not supported.
///
/// @throws NullPointerException if name or value are null
///
/// </param>
/// <seealso cref="LdapConnection.getProperty">
/// </seealso>
public virtual void setProperty(string name, object value_Renamed)
{
if (properties == null)
{
properties = new System.Collections.Hashtable();
}
SupportClass.PutElement(properties, name, value_Renamed);
}
/// <summary> Specifies the object that will process authentication requests
/// during automatic referral following.
///
/// The default is null.
///
/// </summary>
/// <param name="handler"> An object that implements LdapBindHandler or
/// LdapAuthHandler
///
/// </param>
/// <seealso cref="LdapAuthHandler">
/// </seealso>
/// <seealso cref="LdapBindHandler">
/// </seealso>
public virtual void setReferralHandler(LdapReferralHandler handler)
{
refHandler = handler;
}
/// <summary> Clones an LdapConstraints object.
///
/// </summary>
/// <returns> An LdapConstraints object.
/// </returns>
public object Clone()
{
try
{
object newObj = MemberwiseClone();
if (controls != null)
{
((LdapConstraints)newObj).controls = new LdapControl[controls.Length];
controls.CopyTo(((LdapConstraints)newObj).controls, 0);
}
if (properties != null)
{
((LdapConstraints)newObj).properties = (System.Collections.Hashtable)properties.Clone();
}
return newObj;
}
catch (Exception ce)
{
throw new Exception("Internal error, cannot create clone");
}
}
static LdapConstraints()
{
nameLock = new object();
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests
{
private static DiagnosticResult GetCA3075LoadCSharpResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("Load");
#pragma warning restore RS0030 // Do not used banned APIs
private static DiagnosticResult GetCA3075LoadBasicResultAt(int line, int column)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("Load");
#pragma warning restore RS0030 // Do not used banned APIs
[Fact]
public async Task UseXmlDocumentLoadShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
namespace TestNamespace
{
public class TestClass
{
public void TestMethod(string path)
{
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(path);
}
}
}
",
GetCA3075LoadCSharpResultAt(12, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Namespace TestNamespace
Public Class TestClass
Public Sub TestMethod(path As String)
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(path)
End Sub
End Class
End Namespace",
GetCA3075LoadBasicResultAt(9, 13)
);
}
[Fact]
public async Task UseXmlDocumentLoadInGetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
class TestClass
{
public XmlDocument Test
{
get {
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
return doc;
}
}
}",
GetCA3075LoadCSharpResultAt(12, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Class TestClass
Public ReadOnly Property Test() As XmlDocument
Get
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
Return doc
End Get
End Property
End Class",
GetCA3075LoadBasicResultAt(10, 13)
);
}
[Fact]
public async Task UseXmlDocumentLoadInSetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
class TestClass
{
XmlDocument privateDoc;
public XmlDocument GetDoc
{
set
{
if (value == null)
{
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
privateDoc = doc;
}
else
privateDoc = value;
}
}
}",
GetCA3075LoadCSharpResultAt(16, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Class TestClass
Private privateDoc As XmlDocument
Public WriteOnly Property GetDoc() As XmlDocument
Set
If value Is Nothing Then
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
privateDoc = doc
Else
privateDoc = value
End If
End Set
End Property
End Class",
GetCA3075LoadBasicResultAt(12, 17)
);
}
[Fact]
public async Task UseXmlDocumentLoadInTryBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try
{
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
}
catch (Exception) { throw; }
finally { }
}
}",
GetCA3075LoadCSharpResultAt(14, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
Catch generatedExceptionName As Exception
Throw
Finally
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(11, 13)
);
}
[Fact]
public async Task UseXmlDocumentLoadInCatchBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception)
{
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
}
finally { }
}
}",
GetCA3075LoadCSharpResultAt(15, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
Finally
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(12, 13)
);
}
[Fact]
public async Task UseXmlDocumentLoadInFinallyBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception) { throw; }
finally
{
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
}
}
}",
GetCA3075LoadCSharpResultAt(16, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Throw
Finally
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(14, 13)
);
}
[Fact]
public async Task UseXmlDocumentLoadInAsyncAwaitShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Threading.Tasks;
using System.Xml;
class TestClass
{
private async Task TestMethod()
{
await Task.Run(() => {
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
});
}
private async void TestMethod2()
{
await TestMethod();
}
}",
GetCA3075LoadCSharpResultAt(13, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Threading.Tasks
Imports System.Xml
Class TestClass
Private Async Function TestMethod() As Task
Await Task.Run(Function()
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod()
End Sub
End Class",
GetCA3075LoadBasicResultAt(11, 17)
);
}
[Fact]
public async Task UseXmlDocumentLoadInDelegateShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
class TestClass
{
delegate void Del();
Del d = delegate () {
var xml = """";
var doc = new XmlDocument();
doc.XmlResolver = null;
doc.Load(xml);
};
}",
GetCA3075LoadCSharpResultAt(12, 9)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Class TestClass
Private Delegate Sub Del()
Private d As Del = Sub()
Dim xml = """"
Dim doc = New XmlDocument()
doc.XmlResolver = Nothing
doc.Load(xml)
End Sub
End Class",
GetCA3075LoadBasicResultAt(11, 5)
);
}
[Fact]
public async Task UseXmlDataDocumentLoadShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
namespace TestNamespace
{
public class TestClass
{
public void TestMethod(string path)
{
new XmlDataDocument().Load(path);
}
}
}
",
GetCA3075LoadCSharpResultAt(10, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Namespace TestNamespace
Public Class TestClass
Public Sub TestMethod(path As String)
Call New XmlDataDocument().Load(path)
End Sub
End Class
End Namespace",
GetCA3075LoadBasicResultAt(7, 18)
);
}
[Fact]
public async Task UseXmlDataDocumentLoadInGetShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
class TestClass
{
public XmlDataDocument Test
{
get
{
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
return doc;
}
}
}",
GetCA3075LoadCSharpResultAt(12, 13)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Class TestClass
Public ReadOnly Property Test() As XmlDataDocument
Get
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
Return doc
End Get
End Property
End Class",
GetCA3075LoadBasicResultAt(11, 13)
);
}
[Fact]
public async Task UseXmlDataDocumentLoadInTryBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try
{
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
}
catch (Exception) { throw; }
finally { }
}
}",
GetCA3075LoadCSharpResultAt(13, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
Catch generatedExceptionName As Exception
Throw
Finally
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(12, 13)
);
}
[Fact]
public async Task UseXmlDataDocumentLoadInCatchBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception)
{
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
}
finally { }
}
}",
GetCA3075LoadCSharpResultAt(14, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
Finally
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(13, 13)
);
}
[Fact]
public async Task UseXmlDataDocumentLoadInFinallyBlockShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Xml;
class TestClass
{
private void TestMethod()
{
try { }
catch (Exception) { throw; }
finally
{
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
}
}
}",
GetCA3075LoadCSharpResultAt(15, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System
Imports System.Xml
Class TestClass
Private Sub TestMethod()
Try
Catch generatedExceptionName As Exception
Throw
Finally
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
End Try
End Sub
End Class",
GetCA3075LoadBasicResultAt(15, 13)
);
}
[Fact]
public async Task UseXmlDataDocumentLoadInAsyncAwaitShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Threading.Tasks;
using System.Xml;
class TestClass
{
private async Task TestMethod()
{
await Task.Run(() => {
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
});
}
private async void TestMethod2()
{
await TestMethod();
}
}",
GetCA3075LoadCSharpResultAt(12, 17)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Threading.Tasks
Imports System.Xml
Class TestClass
Private Async Function TestMethod() As Task
Await Task.Run(Function()
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
End Function)
End Function
Private Async Sub TestMethod2()
Await TestMethod()
End Sub
End Class",
GetCA3075LoadBasicResultAt(12, 9)
);
}
[Fact]
public async Task UseXmlDataDocumentLoadInDelegateShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System.Xml;
class TestClass
{
delegate void Del();
Del d = delegate () {
var xml = """";
XmlDataDocument doc = new XmlDataDocument() { XmlResolver = null };
doc.Load(xml);
};
}",
GetCA3075LoadCSharpResultAt(11, 9)
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Class TestClass
Private Delegate Sub Del()
Private d As Del = Sub()
Dim xml = """"
Dim doc As New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(xml)
End Sub
End Class",
GetCA3075LoadBasicResultAt(12, 5)
);
}
[Fact]
public async Task UseXmlDocumentLoadWithXmlReaderParameterShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
new XmlDocument(){ XmlResolver = null }.Load(reader);
}
}
}"
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Call New XmlDocument() With { _
.XmlResolver = Nothing _
}.Load(reader)
End Sub
End Class
End Namespace");
}
[Fact]
public async Task UseXmlDataDocumentLoadWithXmlReaderParameterShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
var doc = new XmlDataDocument(){XmlResolver = null};
doc.Load(reader);
}
}
}"
);
await VerifyVisualBasicAnalyzerAsync(
ReferenceAssemblies.NetFramework.Net472.Default,
@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Dim doc = New XmlDataDocument() With { _
.XmlResolver = Nothing _
}
doc.Load(reader)
End Sub
End Class
End Namespace");
}
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Management.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.PowerShell.Management\Register-WmiEvent command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class RegisterWmiEvent : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public RegisterWmiEvent()
{
this.DisplayName = "Register-WmiEvent";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.PowerShell.Management\\Register-WmiEvent"; } }
// Arguments
/// <summary>
/// Provides access to the Namespace parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Namespace { get; set; }
/// <summary>
/// Provides access to the Credential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> Credential { get; set; }
/// <summary>
/// Provides access to the ComputerName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ComputerName { get; set; }
/// <summary>
/// Provides access to the Class parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Class { get; set; }
/// <summary>
/// Provides access to the Query parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Query { get; set; }
/// <summary>
/// Provides access to the Timeout parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int64> Timeout { get; set; }
/// <summary>
/// Provides access to the SourceIdentifier parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> SourceIdentifier { get; set; }
/// <summary>
/// Provides access to the Action parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.ScriptBlock> Action { get; set; }
/// <summary>
/// Provides access to the MessageData parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSObject> MessageData { get; set; }
/// <summary>
/// Provides access to the SupportEvent parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> SupportEvent { get; set; }
/// <summary>
/// Provides access to the Forward parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Forward { get; set; }
/// <summary>
/// Provides access to the MaxTriggerCount parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int32> MaxTriggerCount { get; set; }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(Namespace.Expression != null)
{
targetCommand.AddParameter("Namespace", Namespace.Get(context));
}
if(Credential.Expression != null)
{
targetCommand.AddParameter("Credential", Credential.Get(context));
}
if(ComputerName.Expression != null)
{
targetCommand.AddParameter("ComputerName", ComputerName.Get(context));
}
if(Class.Expression != null)
{
targetCommand.AddParameter("Class", Class.Get(context));
}
if(Query.Expression != null)
{
targetCommand.AddParameter("Query", Query.Get(context));
}
if(Timeout.Expression != null)
{
targetCommand.AddParameter("Timeout", Timeout.Get(context));
}
if(SourceIdentifier.Expression != null)
{
targetCommand.AddParameter("SourceIdentifier", SourceIdentifier.Get(context));
}
if(Action.Expression != null)
{
targetCommand.AddParameter("Action", Action.Get(context));
}
if(MessageData.Expression != null)
{
targetCommand.AddParameter("MessageData", MessageData.Get(context));
}
if(SupportEvent.Expression != null)
{
targetCommand.AddParameter("SupportEvent", SupportEvent.Get(context));
}
if(Forward.Expression != null)
{
targetCommand.AddParameter("Forward", Forward.Get(context));
}
if(MaxTriggerCount.Expression != null)
{
targetCommand.AddParameter("MaxTriggerCount", MaxTriggerCount.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// This file contains the IDN functions and implementation.
//
// This allows encoding of non-ASCII domain names in a "punycode" form,
// for example:
//
// \u5B89\u5BA4\u5948\u7F8E\u6075-with-SUPER-MONKEYS
//
// is encoded as:
//
// xn---with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n
//
// Additional options are provided to allow unassigned IDN characters and
// to validate according to the Std3ASCII Rules (like DNS names).
//
// There are also rules regarding bidirectionality of text and the length
// of segments.
//
// For additional rules see also:
// RFC 3490 - Internationalizing Domain Names in Applications (IDNA)
// RFC 3491 - Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN)
// RFC 3492 - Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA)
using System.Diagnostics;
using System.Text;
namespace System.Globalization
{
// IdnMapping class used to map names to Punycode
public sealed partial class IdnMapping
{
private bool _allowUnassigned;
private bool _useStd3AsciiRules;
public IdnMapping()
{
}
public bool AllowUnassigned
{
get { return _allowUnassigned; }
set { _allowUnassigned = value; }
}
public bool UseStd3AsciiRules
{
get { return _useStd3AsciiRules; }
set { _useStd3AsciiRules = value; }
}
// Gets ASCII (Punycode) version of the string
public string GetAscii(string unicode)
{
return GetAscii(unicode, 0);
}
public string GetAscii(string unicode, int index)
{
if (unicode == null)
throw new ArgumentNullException(nameof(unicode));
return GetAscii(unicode, index, unicode.Length - index);
}
public string GetAscii(string unicode, int index, int count)
{
if (unicode == null)
throw new ArgumentNullException(nameof(unicode));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (index > unicode.Length)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
if (index > unicode.Length - count)
throw new ArgumentOutOfRangeException(nameof(unicode), SR.ArgumentOutOfRange_IndexCountBuffer);
if (count == 0)
{
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
}
if (unicode[index + count - 1] == 0)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, index + count - 1), nameof(unicode));
}
if (GlobalizationMode.Invariant)
{
return GetAsciiInvariant(unicode, index, count);
}
unsafe
{
fixed (char* pUnicode = unicode)
{
return GetAsciiCore(pUnicode + index, count);
}
}
}
// Gets Unicode version of the string. Normalized and limited to IDNA characters.
public string GetUnicode(string ascii)
{
return GetUnicode(ascii, 0);
}
public string GetUnicode(string ascii, int index)
{
if (ascii == null)
throw new ArgumentNullException(nameof(ascii));
return GetUnicode(ascii, index, ascii.Length - index);
}
public string GetUnicode(string ascii, int index, int count)
{
if (ascii == null)
throw new ArgumentNullException(nameof(ascii));
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (index > ascii.Length)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
if (index > ascii.Length - count)
throw new ArgumentOutOfRangeException(nameof(ascii), SR.ArgumentOutOfRange_IndexCountBuffer);
// This is a case (i.e. explicitly null-terminated input) where behavior in .NET and Win32 intentionally differ.
// The .NET APIs should (and did in v4.0 and earlier) throw an ArgumentException on input that includes a terminating null.
// The Win32 APIs fail on an embedded null, but not on a terminating null.
if (count > 0 && ascii[index + count - 1] == (char)0)
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
if (GlobalizationMode.Invariant)
{
return GetUnicodeInvariant(ascii, index, count);
}
unsafe
{
fixed (char* pAscii = ascii)
{
return GetUnicodeCore(pAscii + index, count);
}
}
}
public override bool Equals(object obj)
{
IdnMapping that = obj as IdnMapping;
return
that != null &&
_allowUnassigned == that._allowUnassigned &&
_useStd3AsciiRules == that._useStd3AsciiRules;
}
public override int GetHashCode()
{
return (_allowUnassigned ? 100 : 200) + (_useStd3AsciiRules ? 1000 : 2000);
}
//
// Invariant implementation
//
private const char c_delimiter = '-';
private const string c_strAcePrefix = "xn--";
private const int c_labelLimit = 63; // Not including dots
private const int c_defaultNameLimit = 255; // Including dots
private const int c_initialN = 0x80;
private const int c_maxint = 0x7ffffff;
private const int c_initialBias = 72;
private const int c_punycodeBase = 36;
private const int c_tmin = 1;
private const int c_tmax = 26;
private const int c_skew = 38;
private const int c_damp = 700;
// Legal "dot" separators (i.e: . in www.microsoft.com)
private static char[] c_Dots = { '.', '\u3002', '\uFF0E', '\uFF61' };
private string GetAsciiInvariant(string unicode, int index, int count)
{
if (index > 0 || count < unicode.Length)
{
unicode = unicode.Substring(index, count);
}
// Check for ASCII only string, which will be unchanged
if (ValidateStd3AndAscii(unicode, UseStd3AsciiRules, true))
{
return unicode;
}
// Cannot be null terminated (normalization won't help us with this one, and
// may have returned false before checking the whole string above)
Debug.Assert(count >= 1, "[IdnMapping.GetAscii] Expected 0 length strings to fail before now.");
if (unicode[unicode.Length - 1] <= 0x1f)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, unicode.Length - 1), nameof(unicode));
}
// Have to correctly IDNA normalize the string and Unassigned flags
bool bHasLastDot = (unicode.Length > 0) && IsDot(unicode[unicode.Length - 1]);
// Make sure we didn't normalize away something after a last dot
if ((!bHasLastDot) && unicode.Length > 0 && IsDot(unicode[unicode.Length - 1]))
{
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
}
// May need to check Std3 rules again for non-ascii
if (UseStd3AsciiRules)
{
ValidateStd3AndAscii(unicode, true, false);
}
// Go ahead and encode it
return PunycodeEncode(unicode);
}
// See if we're only ASCII
static bool ValidateStd3AndAscii(string unicode, bool bUseStd3, bool bCheckAscii)
{
// If its empty, then its too small
if (unicode.Length == 0)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
int iLastDot = -1;
// Loop the whole string
for (int i = 0; i < unicode.Length; i++)
{
// Aren't allowing control chars (or 7f, but idn tables catch that, they don't catch \0 at end though)
if (unicode[i] <= 0x1f)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, i ), nameof(unicode));
}
// If its Unicode or a control character, return false (non-ascii)
if (bCheckAscii && unicode[i] >= 0x7f)
return false;
// Check for dots
if (IsDot(unicode[i]))
{
// Can't have 2 dots in a row
if (i == iLastDot + 1)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
// If its too far between dots then fail
if (i - iLastDot > c_labelLimit + 1)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
// If validating Std3, then char before dot can't be - char
if (bUseStd3 && i > 0)
ValidateStd3(unicode[i - 1], true);
// Remember where the last dot is
iLastDot = i;
continue;
}
// If necessary, make sure its a valid std3 character
if (bUseStd3)
{
ValidateStd3(unicode[i], (i == iLastDot + 1));
}
}
// If we never had a dot, then we need to be shorter than the label limit
if (iLastDot == -1 && unicode.Length > c_labelLimit)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
// Need to validate entire string length, 1 shorter if last char wasn't a dot
if (unicode.Length > c_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1))
throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize,
c_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1)), nameof(unicode));
// If last char wasn't a dot we need to check for trailing -
if (bUseStd3 && !IsDot(unicode[unicode.Length - 1]))
ValidateStd3(unicode[unicode.Length - 1], true);
return true;
}
/* PunycodeEncode() converts Unicode to Punycode. The input */
/* is represented as an array of Unicode code points (not code */
/* units; surrogate pairs are not allowed), and the output */
/* will be represented as an array of ASCII code points. The */
/* output string is *not* null-terminated; it will contain */
/* zeros if and only if the input contains zeros. (Of course */
/* the caller can leave room for a terminator and add one if */
/* needed.) The input_length is the number of code points in */
/* the input. The output_length is an in/out argument: the */
/* caller passes in the maximum number of code points that it */
/* can receive, and on successful return it will contain the */
/* number of code points actually output. The case_flags array */
/* holds input_length boolean values, where nonzero suggests that */
/* the corresponding Unicode character be forced to uppercase */
/* after being decoded (if possible), and zero suggests that */
/* it be forced to lowercase (if possible). ASCII code points */
/* are encoded literally, except that ASCII letters are forced */
/* to uppercase or lowercase according to the corresponding */
/* uppercase flags. If case_flags is a null pointer then ASCII */
/* letters are left as they are, and other code points are */
/* treated as if their uppercase flags were zero. The return */
/* value can be any of the punycode_status values defined above */
/* except punycode_bad_input; if not punycode_success, then */
/* output_size and output might contain garbage. */
static string PunycodeEncode(string unicode)
{
// 0 length strings aren't allowed
if (unicode.Length == 0)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
StringBuilder output = new StringBuilder(unicode.Length);
int iNextDot = 0;
int iAfterLastDot = 0;
int iOutputAfterLastDot = 0;
// Find the next dot
while (iNextDot < unicode.Length)
{
// Find end of this segment
iNextDot = unicode.IndexOfAny(c_Dots, iAfterLastDot);
Debug.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
if (iNextDot < 0)
iNextDot = unicode.Length;
// Only allowed to have empty . section at end (www.microsoft.com.)
if (iNextDot == iAfterLastDot)
{
// Only allowed to have empty sections as trailing .
if (iNextDot != unicode.Length)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
// Last dot, stop
break;
}
// We'll need an Ace prefix
output.Append(c_strAcePrefix);
// Everything resets every segment.
bool bRightToLeft = false;
// Check for RTL. If right-to-left, then 1st & last chars must be RTL
BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iAfterLastDot);
if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic)
{
// It has to be right to left.
bRightToLeft = true;
// Check last char
int iTest = iNextDot - 1;
if (Char.IsLowSurrogate(unicode, iTest))
{
iTest--;
}
eBidi = CharUnicodeInfo.GetBidiCategory(unicode, iTest);
if (eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic)
{
// Oops, last wasn't RTL, last should be RTL if first is RTL
throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode));
}
}
// Handle the basic code points
int basicCount;
int numProcessed = 0; // Num code points that have been processed so far (this segment)
for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++)
{
// Can't be lonely surrogate because it would've thrown in normalization
Debug.Assert(Char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate");
// Double check our bidi rules
BidiCategory testBidi = CharUnicodeInfo.GetBidiCategory(unicode, basicCount);
// If we're RTL, we can't have LTR chars
if (bRightToLeft && testBidi == BidiCategory.LeftToRight)
{
// Oops, throw error
throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode));
}
// If we're not RTL we can't have RTL chars
if (!bRightToLeft && (testBidi == BidiCategory.RightToLeft || testBidi == BidiCategory.RightToLeftArabic))
{
// Oops, throw error
throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode));
}
// If its basic then add it
if (Basic(unicode[basicCount]))
{
output.Append(EncodeBasic(unicode[basicCount]));
numProcessed++;
}
// If its a surrogate, skip the next since our bidi category tester doesn't handle it.
else if (Char.IsSurrogatePair(unicode, basicCount))
basicCount++;
}
int numBasicCodePoints = numProcessed; // number of basic code points
// Stop if we ONLY had basic code points
if (numBasicCodePoints == iNextDot - iAfterLastDot)
{
// Get rid of xn-- and this segments done
output.Remove(iOutputAfterLastDot, c_strAcePrefix.Length);
}
else
{
// If it has some non-basic code points the input cannot start with xn--
if (unicode.Length - iAfterLastDot >= c_strAcePrefix.Length &&
unicode.Substring(iAfterLastDot, c_strAcePrefix.Length).Equals(
c_strAcePrefix, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(unicode));
// Need to do ACE encoding
int numSurrogatePairs = 0; // number of surrogate pairs so far
// Add a delimiter (-) if we had any basic code points (between basic and encoded pieces)
if (numBasicCodePoints > 0)
{
output.Append(c_delimiter);
}
// Initialize the state
int n = c_initialN;
int delta = 0;
int bias = c_initialBias;
// Main loop
while (numProcessed < (iNextDot - iAfterLastDot))
{
/* All non-basic code points < n have been */
/* handled already. Find the next larger one: */
int j;
int m;
int test = 0;
for (m = c_maxint, j = iAfterLastDot;
j < iNextDot;
j += IsSupplementary(test) ? 2 : 1)
{
test = Char.ConvertToUtf32(unicode, j);
if (test >= n && test < m) m = test;
}
/* Increase delta enough to advance the decoder's */
/* <n,i> state to <m,0>, but guard against overflow: */
delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1));
Debug.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int");
n = m;
for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1)
{
// Make sure we're aware of surrogates
test = Char.ConvertToUtf32(unicode, j);
// Adjust for character position (only the chars in our string already, some
// haven't been processed.
if (test < n)
{
delta++;
Debug.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
}
if (test == n)
{
// Represent delta as a generalized variable-length integer:
int q, k;
for (q = delta, k = c_punycodeBase; ; k += c_punycodeBase)
{
int t = k <= bias ? c_tmin : k >= bias + c_tmax ? c_tmax : k - bias;
if (q < t) break;
Debug.Assert(c_punycodeBase != t, "[IdnMapping.punycode_encode]Expected c_punycodeBase (36) to be != t");
output.Append(EncodeDigit(t + (q - t) % (c_punycodeBase - t)));
q = (q - t) / (c_punycodeBase - t);
}
output.Append(EncodeDigit(q));
bias = Adapt(delta, (numProcessed - numSurrogatePairs) + 1, numProcessed == numBasicCodePoints);
delta = 0;
numProcessed++;
if (IsSupplementary(m))
{
numProcessed++;
numSurrogatePairs++;
}
}
}
++delta;
++n;
Debug.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int");
}
}
// Make sure its not too big
if (output.Length - iOutputAfterLastDot > c_labelLimit)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
// Done with this segment, add dot if necessary
if (iNextDot != unicode.Length)
output.Append('.');
iAfterLastDot = iNextDot + 1;
iOutputAfterLastDot = output.Length;
}
// Throw if we're too long
if (output.Length > c_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1))
throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize,
c_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)), nameof(unicode));
// Return our output string
return output.ToString();
}
// Is it a dot?
// are we U+002E (., full stop), U+3002 (ideographic full stop), U+FF0E (fullwidth full stop), or
// U+FF61 (halfwidth ideographic full stop).
// Note: IDNA Normalization gets rid of dots now, but testing for last dot is before normalization
private static bool IsDot(char c)
{
return c == '.' || c == '\u3002' || c == '\uFF0E' || c == '\uFF61';
}
private static bool IsSupplementary(int cTest)
{
return cTest >= 0x10000;
}
private static bool Basic(uint cp)
{
// Is it in ASCII range?
return cp < 0x80;
}
// Validate Std3 rules for a character
private static void ValidateStd3(char c, bool bNextToDot)
{
// Check for illegal characters
if ((c <= ',' || c == '/' || (c >= ':' && c <= '@') || // Lots of characters not allowed
(c >= '[' && c <= '`') || (c >= '{' && c <= (char)0x7F)) ||
(c == '-' && bNextToDot))
throw new ArgumentException(SR.Format(SR.Argument_IdnBadStd3, c), nameof(c));
}
private string GetUnicodeInvariant(string ascii, int index, int count)
{
if (index > 0 || count < ascii.Length)
{
// We're only using part of the string
ascii = ascii.Substring(index, count);
}
// Convert Punycode to Unicode
string strUnicode = PunycodeDecode(ascii);
// Output name MUST obey IDNA rules & round trip (casing differences are allowed)
if (!ascii.Equals(GetAscii(strUnicode), StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(ascii));
return strUnicode;
}
/* PunycodeDecode() converts Punycode to Unicode. The input is */
/* represented as an array of ASCII code points, and the output */
/* will be represented as an array of Unicode code points. The */
/* input_length is the number of code points in the input. The */
/* output_length is an in/out argument: the caller passes in */
/* the maximum number of code points that it can receive, and */
/* on successful return it will contain the actual number of */
/* code points output. The case_flags array needs room for at */
/* least output_length values, or it can be a null pointer if the */
/* case information is not needed. A nonzero flag suggests that */
/* the corresponding Unicode character be forced to uppercase */
/* by the caller (if possible), while zero suggests that it be */
/* forced to lowercase (if possible). ASCII code points are */
/* output already in the proper case, but their flags will be set */
/* appropriately so that applying the flags would be harmless. */
/* The return value can be any of the punycode_status values */
/* defined above; if not punycode_success, then output_length, */
/* output, and case_flags might contain garbage. On success, the */
/* decoder will never need to write an output_length greater than */
/* input_length, because of how the encoding is defined. */
private static string PunycodeDecode(string ascii)
{
// 0 length strings aren't allowed
if (ascii.Length == 0)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii));
// Throw if we're too long
if (ascii.Length > c_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1))
throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize,
c_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), nameof(ascii));
// output stringbuilder
StringBuilder output = new StringBuilder(ascii.Length);
// Dot searching
int iNextDot = 0;
int iAfterLastDot = 0;
int iOutputAfterLastDot = 0;
while (iNextDot < ascii.Length)
{
// Find end of this segment
iNextDot = ascii.IndexOf('.', iAfterLastDot);
if (iNextDot < 0 || iNextDot > ascii.Length)
iNextDot = ascii.Length;
// Only allowed to have empty . section at end (www.microsoft.com.)
if (iNextDot == iAfterLastDot)
{
// Only allowed to have empty sections as trailing .
if (iNextDot != ascii.Length)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii));
// Last dot, stop
break;
}
// In either case it can't be bigger than segment size
if (iNextDot - iAfterLastDot > c_labelLimit)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii));
// See if this section's ASCII or ACE
if (ascii.Length < c_strAcePrefix.Length + iAfterLastDot ||
!ascii.Substring(iAfterLastDot,c_strAcePrefix.Length).Equals(c_strAcePrefix, StringComparison.OrdinalIgnoreCase))
{
// Its ASCII, copy it
output.Append(ascii.Substring(iAfterLastDot, iNextDot - iAfterLastDot));
}
else
{
// Not ASCII, bump up iAfterLastDot to be after ACE Prefix
iAfterLastDot += c_strAcePrefix.Length;
// Get number of basic code points (where delimiter is)
// numBasicCodePoints < 0 if there're no basic code points
int iTemp = ascii.LastIndexOf(c_delimiter, iNextDot - 1);
// Trailing - not allowed
if (iTemp == iNextDot - 1)
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
int numBasicCodePoints;
if (iTemp <= iAfterLastDot)
numBasicCodePoints = 0;
else
{
numBasicCodePoints = iTemp - iAfterLastDot;
// Copy all the basic code points, making sure they're all in the allowed range,
// and losing the casing for all of them.
for (int copyAscii = iAfterLastDot; copyAscii < iAfterLastDot + numBasicCodePoints; copyAscii++)
{
// Make sure we don't allow unicode in the ascii part
if (ascii[copyAscii] > 0x7f)
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
// When appending make sure they get lower cased
output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <='Z' ? ascii[copyAscii] - 'A' + 'a' : ascii[copyAscii]));
}
}
// Get ready for main loop. Start at beginning if we didn't have any
// basic code points, otherwise start after the -.
// asciiIndex will be next character to read from ascii
int asciiIndex = iAfterLastDot + (numBasicCodePoints > 0 ? numBasicCodePoints + 1 : 0);
// initialize our state
int n = c_initialN;
int bias = c_initialBias;
int i = 0;
int w, k;
// no Supplementary characters yet
int numSurrogatePairs = 0;
// Main loop, read rest of ascii
while (asciiIndex < iNextDot)
{
/* Decode a generalized variable-length integer into delta, */
/* which gets added to i. The overflow checking is easier */
/* if we increase i as we go, then subtract off its starting */
/* value at the end to obtain delta. */
int oldi = i;
for (w = 1, k = c_punycodeBase; ; k += c_punycodeBase)
{
// Check to make sure we aren't overrunning our ascii string
if (asciiIndex >= iNextDot)
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
// decode the digit from the next char
int digit = DecodeDigit(ascii[asciiIndex++]);
Debug.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0");
if (digit > (c_maxint - i) / w)
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
i += (int)(digit * w);
int t = k <= bias ? c_tmin : k >= bias + c_tmax ? c_tmax : k - bias;
if (digit < t)
break;
Debug.Assert(c_punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != c_punycodeBase (36)");
if (w > c_maxint / (c_punycodeBase - t))
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
w *= (c_punycodeBase - t);
}
bias = Adapt(i - oldi, (output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1, oldi == 0);
/* i was supposed to wrap around from output.Length to 0, */
/* incrementing n each time, so we'll fix that now: */
Debug.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0,
"[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment");
if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > c_maxint - n)
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
n += (int)(i / (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1));
i %= (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1);
// Make sure n is legal
if ((n < 0 || n > 0x10ffff) || (n >= 0xD800 && n <= 0xDFFF))
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
// insert n at position i of the output: Really tricky if we have surrogates
int iUseInsertLocation;
String strTemp = Char.ConvertFromUtf32(n);
// If we have supplimentary characters
if (numSurrogatePairs > 0)
{
// Hard way, we have supplimentary characters
int iCount;
for (iCount = i, iUseInsertLocation = iOutputAfterLastDot; iCount > 0; iCount--, iUseInsertLocation++)
{
// If its a surrogate, we have to go one more
if (iUseInsertLocation >= output.Length)
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
if (Char.IsSurrogate(output[iUseInsertLocation]))
iUseInsertLocation++;
}
}
else
{
// No Supplementary chars yet, just add i
iUseInsertLocation = iOutputAfterLastDot + i;
}
// Insert it
output.Insert(iUseInsertLocation, strTemp);
// If it was a surrogate increment our counter
if (IsSupplementary(n))
numSurrogatePairs++;
// Index gets updated
i++;
}
// Do BIDI testing
bool bRightToLeft = false;
// Check for RTL. If right-to-left, then 1st & last chars must be RTL
BidiCategory eBidi = CharUnicodeInfo.GetBidiCategory(output.ToString(), iOutputAfterLastDot);
if (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic)
{
// It has to be right to left.
bRightToLeft = true;
}
// Check the rest of them to make sure RTL/LTR is consistent
for (int iTest = iOutputAfterLastDot; iTest < output.Length; iTest++)
{
// This might happen if we run into a pair
if (Char.IsLowSurrogate(output.ToString(), iTest))
continue;
// Check to see if its LTR
eBidi = CharUnicodeInfo.GetBidiCategory(output.ToString(), iTest);
if ((bRightToLeft && eBidi == BidiCategory.LeftToRight) ||
(!bRightToLeft && (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic)))
throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(ascii));
}
// Its also a requirement that the last one be RTL if 1st is RTL
if (bRightToLeft && eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic)
{
// Oops, last wasn't RTL, last should be RTL if first is RTL
throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(ascii));
}
}
// See if this label was too long
if (iNextDot - iAfterLastDot > c_labelLimit)
throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii));
// Done with this segment, add dot if necessary
if (iNextDot != ascii.Length)
output.Append('.');
iAfterLastDot = iNextDot + 1;
iOutputAfterLastDot = output.Length;
}
// Throw if we're too long
if (output.Length > c_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1))
throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1)), nameof(ascii));
// Return our output string
return output.ToString();
}
// DecodeDigit(cp) returns the numeric value of a basic code */
// point (for use in representing integers) in the range 0 to */
// c_punycodeBase-1, or <0 if cp is does not represent a value. */
private static int DecodeDigit(char cp)
{
if (cp >= '0' && cp <= '9')
return cp - '0' + 26;
// Two flavors for case differences
if (cp >= 'a' && cp <= 'z')
return cp - 'a';
if (cp >= 'A' && cp <= 'Z')
return cp - 'A';
// Expected 0-9, A-Z or a-z, everything else is illegal
throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(cp));
}
private static int Adapt(int delta, int numpoints, bool firsttime)
{
uint k;
delta = firsttime ? delta / c_damp : delta / 2;
Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
delta += delta / numpoints;
for (k = 0; delta > ((c_punycodeBase - c_tmin) * c_tmax) / 2; k += c_punycodeBase)
{
delta /= c_punycodeBase - c_tmin;
}
Debug.Assert(delta + c_skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
return (int)(k + (c_punycodeBase - c_tmin + 1) * delta / (delta + c_skew));
}
/* EncodeBasic(bcp,flag) forces a basic code point to lowercase */
/* if flag is false, uppercase if flag is true, and returns */
/* the resulting code point. The code point is unchanged if it */
/* is caseless. The behavior is undefined if bcp is not a basic */
/* code point. */
static char EncodeBasic(char bcp)
{
if (HasUpperCaseFlag(bcp))
bcp += (char)('a' - 'A');
return bcp;
}
// Return whether a punycode code point is flagged as being upper case.
private static bool HasUpperCaseFlag(char punychar)
{
return (punychar >= 'A' && punychar <= 'Z');
}
/* EncodeDigit(d,flag) returns the basic code point whose value */
/* (when used for representing integers) is d, which needs to be in */
/* the range 0 to punycodeBase-1. The lowercase form is used unless flag is */
/* true, in which case the uppercase form is used. */
private static char EncodeDigit(int d)
{
Debug.Assert(d >= 0 && d < c_punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
// 26-35 map to ASCII 0-9
if (d > 25) return (char)(d - 26 + '0');
// 0-25 map to a-z or A-Z
return (char)(d + 'a');
}
}
}
| |
// 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: Convenient wrapper for an array, an offset, and
** a count. Ideally used in streams & collections.
** Net Classes will consume an array of these.
**
**
===========================================================*/
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System
{
// Note: users should make sure they copy the fields out of an ArraySegment onto their stack
// then validate that the fields describe valid bounds within the array. This must be done
// because assignments to value types are not atomic, and also because one thread reading
// three fields from an ArraySegment may not see the same ArraySegment from one call to another
// (ie, users could assign a new value to the old location).
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct ArraySegment<T> : IList<T>, IReadOnlyList<T>
{
// Do not replace the array allocation with Array.Empty. We don't want to have the overhead of
// instantiating another generic type in addition to ArraySegment<T> for new type parameters.
public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]);
private readonly T[] _array; // Do not rename (binary serialization)
private readonly int _offset; // Do not rename (binary serialization)
private readonly int _count; // Do not rename (binary serialization)
public ArraySegment(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
_array = array;
_offset = 0;
_count = array.Length;
}
public ArraySegment(T[] array, int offset, int count)
{
// Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path
// Negative values discovered though conversion to high values when converted to unsigned
// Failure should be rare and location determination and message is delegated to failure functions
if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset))
ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count);
_array = array;
_offset = offset;
_count = count;
}
public T[] Array => _array;
public int Offset => _offset;
public int Count => _count;
public T this[int index]
{
get
{
if ((uint)index >= (uint)_count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
return _array[_offset + index];
}
set
{
if ((uint)index >= (uint)_count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
_array[_offset + index] = value;
}
}
public Enumerator GetEnumerator()
{
ThrowInvalidOperationIfDefault();
return new Enumerator(this);
}
public override int GetHashCode()
{
if (_array == null)
{
return 0;
}
int hash = 5381;
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset);
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count);
// The array hash is expected to be an evenly-distributed mixture of bits,
// so rather than adding the cost of another rotation we just xor it.
hash ^= _array.GetHashCode();
return hash;
}
public void CopyTo(T[] destination) => CopyTo(destination, 0);
public void CopyTo(T[] destination, int destinationIndex)
{
ThrowInvalidOperationIfDefault();
System.Array.Copy(_array, _offset, destination, destinationIndex, _count);
}
public void CopyTo(ArraySegment<T> destination)
{
ThrowInvalidOperationIfDefault();
destination.ThrowInvalidOperationIfDefault();
if (_count > destination._count)
{
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
System.Array.Copy(_array, _offset, destination._array, destination._offset, _count);
}
public override bool Equals(Object obj)
{
if (obj is ArraySegment<T>)
return Equals((ArraySegment<T>)obj);
else
return false;
}
public bool Equals(ArraySegment<T> obj)
{
return obj._array == _array && obj._offset == _offset && obj._count == _count;
}
public ArraySegment<T> Slice(int index)
{
ThrowInvalidOperationIfDefault();
if ((uint)index > (uint)_count)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
return new ArraySegment<T>(_array, _offset + index, _count - index);
}
public ArraySegment<T> Slice(int index, int count)
{
ThrowInvalidOperationIfDefault();
if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
return new ArraySegment<T>(_array, _offset + index, count);
}
public T[] ToArray()
{
ThrowInvalidOperationIfDefault();
if (_count == 0)
{
return Empty._array;
}
var array = new T[_count];
System.Array.Copy(_array, _offset, array, 0, _count);
return array;
}
public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b)
{
return a.Equals(b);
}
public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b)
{
return !(a == b);
}
public static implicit operator ArraySegment<T>(T[] array) => new ArraySegment<T>(array);
#region IList<T>
T IList<T>.this[int index]
{
get
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
return _array[_offset + index];
}
set
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
_array[_offset + index] = value;
}
}
int IList<T>.IndexOf(T item)
{
ThrowInvalidOperationIfDefault();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0 ? index - _offset : -1;
}
void IList<T>.Insert(int index, T item)
{
ThrowHelper.ThrowNotSupportedException();
}
void IList<T>.RemoveAt(int index)
{
ThrowHelper.ThrowNotSupportedException();
}
#endregion
#region IReadOnlyList<T>
T IReadOnlyList<T>.this[int index]
{
get
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
return _array[_offset + index];
}
}
#endregion IReadOnlyList<T>
#region ICollection<T>
bool ICollection<T>.IsReadOnly
{
get
{
// the indexer setter does not throw an exception although IsReadOnly is true.
// This is to match the behavior of arrays.
return true;
}
}
void ICollection<T>.Add(T item)
{
ThrowHelper.ThrowNotSupportedException();
}
void ICollection<T>.Clear()
{
ThrowHelper.ThrowNotSupportedException();
}
bool ICollection<T>.Contains(T item)
{
ThrowInvalidOperationIfDefault();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0;
}
bool ICollection<T>.Remove(T item)
{
ThrowHelper.ThrowNotSupportedException();
return default(bool);
}
#endregion
#region IEnumerable<T>
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
private void ThrowInvalidOperationIfDefault()
{
if (_array == null)
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
}
}
public struct Enumerator : IEnumerator<T>
{
private readonly T[] _array;
private readonly int _start;
private readonly int _end; // cache Offset + Count, since it's a little slow
private int _current;
internal Enumerator(ArraySegment<T> arraySegment)
{
Debug.Assert(arraySegment.Array != null);
Debug.Assert(arraySegment.Offset >= 0);
Debug.Assert(arraySegment.Count >= 0);
Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length);
_array = arraySegment.Array;
_start = arraySegment.Offset;
_end = arraySegment.Offset + arraySegment.Count;
_current = arraySegment.Offset - 1;
}
public bool MoveNext()
{
if (_current < _end)
{
_current++;
return (_current < _end);
}
return false;
}
public T Current
{
get
{
if (_current < _start)
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
if (_current >= _end)
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return _array[_current];
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
_current = _start - 1;
}
public void Dispose()
{
}
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComUtils.MasterSetup.DS
{
public class MST_CCNDS
{
public MST_CCNDS()
{
}
private const string THIS = "PCSComUtils.MasterSetup.DS.MST_CCNDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to MST_CCN
/// </Description>
/// <Inputs>
/// MST_CCNVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
MST_CCNVO objObject = (MST_CCNVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO MST_CCN("
+ MST_CCNTable.CODE_FLD + ","
+ MST_CCNTable.DESCRIPTION_FLD + ","
+ MST_CCNTable.NAME_FLD + ","
+ MST_CCNTable.STATE_FLD + ","
+ MST_CCNTable.ZIPCODE_FLD + ","
+ MST_CCNTable.PHONE_FLD + ","
+ MST_CCNTable.FAX_FLD + ","
+ MST_CCNTable.WEBSITE_FLD + ","
+ MST_CCNTable.EMAIL_FLD + ","
+ MST_CCNTable.VAT_FLD + ","
+ MST_CCNTable.COUNTRYID_FLD + ","
+ MST_CCNTable.CITYID_FLD + ","
+ MST_CCNTable.HOMECURRENCYID_FLD + ","
+ MST_CCNTable.EXCHANGERATE_FLD + ","
+ MST_CCNTable.DEFAULTCURRENCYID_FLD + ","
+ MST_CCNTable.EXCHANGERATEOPERATOR_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.DESCRIPTION_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.NAME_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.NAME_FLD].Value = objObject.Name;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.STATE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.STATE_FLD].Value = objObject.State;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.ZIPCODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.ZIPCODE_FLD].Value = objObject.ZipCode;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.PHONE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.PHONE_FLD].Value = objObject.Phone;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.FAX_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.FAX_FLD].Value = objObject.Fax;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.WEBSITE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.WEBSITE_FLD].Value = objObject.WebSite;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.EMAIL_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.EMAIL_FLD].Value = objObject.Email;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.VAT_FLD, OleDbType.Boolean));
ocmdPCS.Parameters[MST_CCNTable.VAT_FLD].Value = objObject.VAT;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.COUNTRYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_CCNTable.COUNTRYID_FLD].Value = objObject.CountryID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.CITYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_CCNTable.CITYID_FLD].Value = objObject.CityID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.HOMECURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_CCNTable.HOMECURRENCYID_FLD].Value = objObject.HomeCurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.EXCHANGERATE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[MST_CCNTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.DEFAULTCURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_CCNTable.DEFAULTCURRENCYID_FLD].Value = objObject.DefaultCurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.EXCHANGERATEOPERATOR_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.EXCHANGERATEOPERATOR_FLD].Value = objObject.ExchangeRateOperator;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from MST_CCN
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + MST_CCNTable.TABLE_NAME + " WHERE " + "CCNID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from MST_CCN
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// MST_CCNVO
/// </Outputs>
/// <Returns>
/// MST_CCNVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_CCNTable.CCNID_FLD + ","
+ MST_CCNTable.CODE_FLD + ","
+ MST_CCNTable.DESCRIPTION_FLD + ","
+ MST_CCNTable.NAME_FLD + ","
+ MST_CCNTable.STATE_FLD + ","
+ MST_CCNTable.ZIPCODE_FLD + ","
+ MST_CCNTable.PHONE_FLD + ","
+ MST_CCNTable.FAX_FLD + ","
+ MST_CCNTable.WEBSITE_FLD + ","
+ MST_CCNTable.EMAIL_FLD + ","
+ MST_CCNTable.VAT_FLD + ","
+ MST_CCNTable.COUNTRYID_FLD + ","
+ MST_CCNTable.CITYID_FLD + ","
+ MST_CCNTable.HOMECURRENCYID_FLD + ","
+ MST_CCNTable.EXCHANGERATE_FLD + ","
+ MST_CCNTable.DEFAULTCURRENCYID_FLD + ","
+ MST_CCNTable.EXCHANGERATEOPERATOR_FLD
+ " FROM " + MST_CCNTable.TABLE_NAME
+" WHERE " + MST_CCNTable.CCNID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
MST_CCNVO objObject = new MST_CCNVO();
while (odrPCS.Read())
{
objObject.CCNID = int.Parse(odrPCS[MST_CCNTable.CCNID_FLD].ToString().Trim());
objObject.Code = odrPCS[MST_CCNTable.CODE_FLD].ToString().Trim();
objObject.Description = odrPCS[MST_CCNTable.DESCRIPTION_FLD].ToString().Trim();
objObject.Name = odrPCS[MST_CCNTable.NAME_FLD].ToString().Trim();
objObject.State = odrPCS[MST_CCNTable.STATE_FLD].ToString().Trim();
objObject.ZipCode = odrPCS[MST_CCNTable.ZIPCODE_FLD].ToString().Trim();
objObject.Phone = odrPCS[MST_CCNTable.PHONE_FLD].ToString().Trim();
objObject.Fax = odrPCS[MST_CCNTable.FAX_FLD].ToString().Trim();
objObject.WebSite = odrPCS[MST_CCNTable.WEBSITE_FLD].ToString().Trim();
objObject.Email = odrPCS[MST_CCNTable.EMAIL_FLD].ToString().Trim();
objObject.VAT = odrPCS[MST_CCNTable.VAT_FLD].ToString().Trim();
// HACK: dungla 10-28-2005
try
{
objObject.CountryID = int.Parse(odrPCS[MST_CCNTable.COUNTRYID_FLD].ToString().Trim());
}
catch{}
try
{
objObject.CityID = int.Parse(odrPCS[MST_CCNTable.CITYID_FLD].ToString().Trim());
}
catch{}
try
{
objObject.HomeCurrencyID = int.Parse(odrPCS[MST_CCNTable.HOMECURRENCYID_FLD].ToString().Trim());
}
catch{}
try
{
objObject.ExchangeRate = float.Parse(odrPCS[MST_CCNTable.EXCHANGERATE_FLD].ToString().Trim());
}
catch{}
try
{
objObject.DefaultCurrencyID = int.Parse(odrPCS[MST_CCNTable.DEFAULTCURRENCYID_FLD].ToString().Trim());
}
catch{}
// END: dungla 10-28-2005
objObject.ExchangeRateOperator = odrPCS[MST_CCNTable.EXCHANGERATEOPERATOR_FLD].ToString().Trim();
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from MST_CCN
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// MST_CCNVO
/// </Outputs>
/// <Returns>
/// MST_CCNVO
/// </Returns>
/// <Authors>
/// Sonht
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(string pstrUserName)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_CCNTable.TABLE_NAME + "." + MST_CCNTable.CCNID_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.CODE_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.DESCRIPTION_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.NAME_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.STATE_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.ZIPCODE_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.PHONE_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.FAX_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.WEBSITE_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.EMAIL_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.VAT_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.COUNTRYID_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.CITYID_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.HOMECURRENCYID_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.EXCHANGERATE_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.DEFAULTCURRENCYID_FLD + ","
+ MST_CCNTable.TABLE_NAME + "."+ MST_CCNTable.EXCHANGERATEOPERATOR_FLD
+ " FROM " + MST_CCNTable.TABLE_NAME
+ " INNER JOIN " + Sys_UserTable.TABLE_NAME + " ON "
+ MST_CCNTable.TABLE_NAME + "." + MST_CCNTable.CCNID_FLD + " = " + Sys_UserTable.TABLE_NAME + "." + Sys_UserTable.CCNID_FLD
+" WHERE " + Sys_UserTable.USERNAME_FLD + "='" + pstrUserName.Replace("'","''") + "'";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
MST_CCNVO objObject = new MST_CCNVO();
while (odrPCS.Read())
{
objObject.CCNID = int.Parse(odrPCS[MST_CCNTable.CCNID_FLD].ToString().Trim());
objObject.Code = odrPCS[MST_CCNTable.CODE_FLD].ToString().Trim();
objObject.Description = odrPCS[MST_CCNTable.DESCRIPTION_FLD].ToString().Trim();
objObject.Name = odrPCS[MST_CCNTable.NAME_FLD].ToString().Trim();
objObject.State = odrPCS[MST_CCNTable.STATE_FLD].ToString().Trim();
objObject.ZipCode = odrPCS[MST_CCNTable.ZIPCODE_FLD].ToString().Trim();
objObject.Phone = odrPCS[MST_CCNTable.PHONE_FLD].ToString().Trim();
objObject.Fax = odrPCS[MST_CCNTable.FAX_FLD].ToString().Trim();
objObject.WebSite = odrPCS[MST_CCNTable.WEBSITE_FLD].ToString().Trim();
objObject.Email = odrPCS[MST_CCNTable.EMAIL_FLD].ToString().Trim();
if(odrPCS[MST_CCNTable.VAT_FLD] != DBNull.Value)
objObject.VAT = odrPCS[MST_CCNTable.VAT_FLD].ToString().Trim();
if(odrPCS[MST_CCNTable.COUNTRYID_FLD] != DBNull.Value)
objObject.CountryID = int.Parse(odrPCS[MST_CCNTable.COUNTRYID_FLD].ToString().Trim());
if(odrPCS[MST_CCNTable.CITYID_FLD] != DBNull.Value)
objObject.CityID = int.Parse(odrPCS[MST_CCNTable.CITYID_FLD].ToString().Trim());
if(odrPCS[MST_CCNTable.HOMECURRENCYID_FLD] != DBNull.Value)
objObject.HomeCurrencyID = int.Parse(odrPCS[MST_CCNTable.HOMECURRENCYID_FLD].ToString().Trim());
if(odrPCS[MST_CCNTable.EXCHANGERATE_FLD] != DBNull.Value)
objObject.ExchangeRate = float.Parse(odrPCS[MST_CCNTable.EXCHANGERATE_FLD].ToString().Trim());
if(odrPCS[MST_CCNTable.DEFAULTCURRENCYID_FLD] != DBNull.Value)
objObject.DefaultCurrencyID = int.Parse(odrPCS[MST_CCNTable.DEFAULTCURRENCYID_FLD].ToString().Trim());
objObject.ExchangeRateOperator = odrPCS[MST_CCNTable.EXCHANGERATEOPERATOR_FLD].ToString().Trim();
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to MST_CCN
/// </Description>
/// <Inputs>
/// MST_CCNVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
MST_CCNVO objObject = (MST_CCNVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE MST_CCN SET "
+ MST_CCNTable.CODE_FLD + "= ?" + ","
+ MST_CCNTable.DESCRIPTION_FLD + "= ?" + ","
+ MST_CCNTable.NAME_FLD + "= ?" + ","
+ MST_CCNTable.STATE_FLD + "= ?" + ","
+ MST_CCNTable.ZIPCODE_FLD + "= ?" + ","
+ MST_CCNTable.PHONE_FLD + "= ?" + ","
+ MST_CCNTable.FAX_FLD + "= ?" + ","
+ MST_CCNTable.WEBSITE_FLD + "= ?" + ","
+ MST_CCNTable.EMAIL_FLD + "= ?" + ","
+ MST_CCNTable.VAT_FLD + "= ?" + ","
+ MST_CCNTable.COUNTRYID_FLD + "= ?" + ","
+ MST_CCNTable.CITYID_FLD + "= ?" + ","
+ MST_CCNTable.HOMECURRENCYID_FLD + "= ?" + ","
+ MST_CCNTable.EXCHANGERATE_FLD + "= ?" + ","
+ MST_CCNTable.DEFAULTCURRENCYID_FLD + "= ?" + ","
+ MST_CCNTable.EXCHANGERATEOPERATOR_FLD + "= ?"
+" WHERE " + MST_CCNTable.CCNID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.DESCRIPTION_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.NAME_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.NAME_FLD].Value = objObject.Name;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.STATE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.STATE_FLD].Value = objObject.State;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.ZIPCODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.ZIPCODE_FLD].Value = objObject.ZipCode;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.PHONE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.PHONE_FLD].Value = objObject.Phone;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.FAX_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.FAX_FLD].Value = objObject.Fax;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.WEBSITE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.WEBSITE_FLD].Value = objObject.WebSite;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.EMAIL_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.EMAIL_FLD].Value = objObject.Email;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.VAT_FLD, OleDbType.Boolean));
ocmdPCS.Parameters[MST_CCNTable.VAT_FLD].Value = objObject.VAT;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.COUNTRYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_CCNTable.COUNTRYID_FLD].Value = objObject.CountryID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.CITYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_CCNTable.CITYID_FLD].Value = objObject.CityID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.HOMECURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_CCNTable.HOMECURRENCYID_FLD].Value = objObject.HomeCurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.EXCHANGERATE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[MST_CCNTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.DEFAULTCURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_CCNTable.DEFAULTCURRENCYID_FLD].Value = objObject.DefaultCurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.EXCHANGERATEOPERATOR_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_CCNTable.EXCHANGERATEOPERATOR_FLD].Value = objObject.ExchangeRateOperator;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_CCNTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_CCNTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from MST_CCN
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_CCNTable.CCNID_FLD + ","
+ MST_CCNTable.CODE_FLD + ","
+ MST_CCNTable.DESCRIPTION_FLD + ","
+ MST_CCNTable.NAME_FLD + ","
+ MST_CCNTable.STATE_FLD + ","
+ MST_CCNTable.ZIPCODE_FLD + ","
+ MST_CCNTable.PHONE_FLD + ","
+ MST_CCNTable.FAX_FLD + ","
+ MST_CCNTable.WEBSITE_FLD + ","
+ MST_CCNTable.EMAIL_FLD + ","
+ MST_CCNTable.VAT_FLD + ","
+ MST_CCNTable.COUNTRYID_FLD + ","
+ MST_CCNTable.CITYID_FLD + ","
+ MST_CCNTable.HOMECURRENCYID_FLD + ","
+ MST_CCNTable.EXCHANGERATE_FLD + ","
+ MST_CCNTable.DEFAULTCURRENCYID_FLD + ","
+ MST_CCNTable.EXCHANGERATEOPERATOR_FLD
+ " FROM " + MST_CCNTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,MST_CCNTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from MST_CCN
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataTable ListAllCCN()
{
const string METHOD_NAME = THIS + ".ListAllCCN()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_CCNTable.CCNID_FLD + ","
+ MST_CCNTable.CODE_FLD
+ " FROM " + MST_CCNTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,MST_CCNTable.TABLE_NAME);
return dstPCS.Tables[0];
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from MST_CCN
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Thursday, January 06, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet ListCCNForCombo()
{
const string METHOD_NAME = THIS + ".ListCCNForCombo()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_CCNTable.CCNID_FLD + ","
+ MST_CCNTable.CODE_FLD + ","
+ MST_CCNTable.DESCRIPTION_FLD
+ " FROM " + MST_CCNTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,MST_CCNTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ MST_CCNTable.CCNID_FLD + ","
+ MST_CCNTable.CODE_FLD + ","
+ MST_CCNTable.DESCRIPTION_FLD + ","
+ MST_CCNTable.NAME_FLD + ","
+ MST_CCNTable.STATE_FLD + ","
+ MST_CCNTable.ZIPCODE_FLD + ","
+ MST_CCNTable.PHONE_FLD + ","
+ MST_CCNTable.FAX_FLD + ","
+ MST_CCNTable.WEBSITE_FLD + ","
+ MST_CCNTable.EMAIL_FLD + ","
+ MST_CCNTable.VAT_FLD + ","
+ MST_CCNTable.COUNTRYID_FLD + ","
+ MST_CCNTable.CITYID_FLD + ","
+ MST_CCNTable.HOMECURRENCYID_FLD + ","
+ MST_CCNTable.EXCHANGERATE_FLD + ","
+ MST_CCNTable.DEFAULTCURRENCYID_FLD + ","
+ MST_CCNTable.EXCHANGERATEOPERATOR_FLD
+ " FROM " + MST_CCNTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,MST_CCNTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get CCN Code from ID
/// </Description>
/// <Inputs>
/// int
/// </Inputs>
/// <Outputs>
/// string
/// </Outputs>
/// <Returns>
/// string
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 17-Feb-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public string GetCCNCodeFromID(int pintCCNID)
{
const string METHOD_NAME = THIS + ".GetCCNCodeFromID()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_CCNTable.CODE_FLD
+ " FROM " + MST_CCNTable.TABLE_NAME
+ " WHERE " + MST_CCNTable.CCNID_FLD + "=" + pintCCNID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
DataSet dstData = new DataSet();
odadPCS.Fill(dstData, MST_CCNTable.TABLE_NAME);
string strCCNCode = string.Empty;
if (dstData.Tables.Count > 0)
{
if (dstData.Tables[0].Rows.Count > 0)
{
strCCNCode = dstData.Tables[0].Rows[0][0].ToString().Trim();
}
}
return strCCNCode;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using SuperSimple.Auth;
using MongoDB.Bson;
using MtgDb.Info.Driver;
using System.Configuration;
using System.Linq;
namespace MtgDb.Info
{
public class MongoRepository : IRepository
{
private string Connection { get; set; }
private MongoDatabase database;
private MongoClient client;
private MongoServer server;
private SuperSimpleAuth ssa;
public Db magicdb;
public MongoRepository (string connection)
{
ssa = new SuperSimpleAuth (
ConfigurationManager.AppSettings.Get("domain"),
ConfigurationManager.AppSettings.Get("domain_key"));
magicdb = new Db (ConfigurationManager.AppSettings.Get("api"));
Connection = connection;
client = new MongoClient(connection);
server = client.GetServer();
database = server.GetDatabase("mtgdb_info");
CreateUserCardIndexes ();
}
public MongoRepository (string connection, Db mtgdb, SuperSimpleAuth auth)
{
Connection = connection;
magicdb = mtgdb;
//magicdb = new Db (ConfigurationManager.AppSettings.Get("api"));
client = new MongoClient(connection);
server = client.GetServer();
database = server.GetDatabase("mtgdb_info");
ssa = auth;
CreateUserCardIndexes ();
}
public CardChange[] GetChangeRequests(string status = null)
{
MongoCollection<CardChange> collection =
database.GetCollection<CardChange> ("card_changes");
List<CardChange> changes = new List<CardChange>();
IOrderedEnumerable<CardChange> mongoResults;
if(status == null)
{
mongoResults = collection.FindAll()
.OrderByDescending(x => x.CreatedAt);
}
else
{
var query = Query<CardChange>.EQ (e => e.Status, status);
mongoResults = collection.Find(query)
.OrderByDescending(x => x.CreatedAt);
}
foreach(CardChange c in mongoResults)
{
c.User = GetProfile(c.UserId);
changes.Add(c);
}
return changes.ToArray();
}
public CardChange UpdateCardChangeStatus(Guid id,
string status, string field = null)
{
MongoCollection<CardChange> collection =
database.GetCollection<CardChange> ("card_changes");
var query = Query<CardChange>.EQ (e => e.Id, id);
CardChange change = collection.FindOne(query);
change.Status = status;
change.ModifiedAt = DateTime.Now;
List<string> committed = new List<string>();
if(field != null)
{
if(change.ChangesCommitted == null)
{
committed.Add(field);
}
else
{
committed = change.ChangesCommitted.ToList();
committed.Add(field);
}
change.ChangesCommitted = committed.ToArray();
}
collection.Save(change);
return change;
}
public CardChange GetCardChangeRequest(Guid id)
{
MongoCollection<CardChange> collection =
database.GetCollection<CardChange> ("card_changes");
var query = Query.And(Query<CardChange>.EQ (e => e.Id, id ));
CardChange change = collection.FindOne(query);
change.User = GetProfile(change.UserId);
return change;
}
public CardChange[] GetCardChangeRequests(int mvid)
{
MongoCollection<CardChange> collection =
database.GetCollection<CardChange> ("card_changes");
List<CardChange> changes = new List<CardChange>();
var query = Query.And(Query<CardChange>.EQ (e => e.Mvid, mvid ));
var mongoResults = collection.Find(query);
foreach(CardChange c in mongoResults)
{
c.User = GetProfile(c.UserId);
changes.Add(c);
}
return changes.ToArray();
}
public Guid AddCardChangeRequest(CardChange change)
{
MongoCollection<CardChange> collection =
database.GetCollection<CardChange> ("card_changes");
List<CardChange> changes = new List<CardChange>();
Card card = magicdb.GetCard(change.Mvid);
var query = Query.And(Query<CardChange>.EQ (e => e.Mvid, change.Mvid ));
var mongoResults = collection.Find(query);
foreach(CardChange c in mongoResults)
{
changes.Add(c);
}
if(changes.Count == 0)
{
CardChange original = CardChange.MapCard(card);
original.Comment = "Original card info";
original.Id = Guid.NewGuid();
original.Version = 0;
original.CreatedAt = DateTime.Now;
collection.Save(original);
}
change.Id = Guid.NewGuid();
change.Version = changes.Count == 0 ? 1 : changes.Count;
change.CreatedAt = DateTime.Now;
change.ModifiedAt = DateTime.Now;
change.FieldsUpdated = CardChange.FieldsChanged(card, change);
change.Status = "Pending";
//change.ReleasedAt = change.ReleasedAt.ToShortDateString();
if(change.FieldsUpdated == null ||
change.FieldsUpdated.Length == 0)
{
throw new ArgumentException("No fields have been updated.");
}
try
{
collection.Save(change);
}
catch(Exception e)
{
change.Id = Guid.Empty;
throw e;
}
return change.Id;
}
public Dictionary<string, int> GetSetCardCounts(Guid walkerId)
{
Dictionary<string, int> userSets = new Dictionary<string, int> ();
CardSet[] sets = magicdb.GetSets();
UserCard[] users = null;
foreach(CardSet s in sets)
{
users = GetUserCards (walkerId, s.CardIds);
if(users != null && users.Length > 0)
{
userSets.Add (s.Id, users.Length);
}
}
return userSets;
}
public UserCard[] GetUserCards(Guid walkerId)
{
var collection = database.GetCollection<UserCard>("user_cards");
List<UserCard> userCards = new List<UserCard> ();
var query = Query.And(
Query<UserCard>.EQ(c => c.PlaneswalkerId, walkerId),
Query<UserCard>.GT(c => c.Amount, 0));
var cards = collection.Find (query);
foreach(UserCard c in cards)
{
userCards.Add (c);
}
return userCards.ToArray ();
}
public UserCard[] GetUserCards(Guid walkerId, int[] multiverseIds)
{
var collection = database.GetCollection<UserCard>("user_cards");
List<UserCard> userCards = new List<UserCard> ();
var query = Query.And(Query.In ("MultiverseId", new BsonArray(multiverseIds)),
Query<UserCard>.EQ(c => c.PlaneswalkerId, walkerId),
Query<UserCard>.GT(c => c.Amount, 0));
var cards = collection.Find (query);
foreach(UserCard c in cards)
{
userCards.Add (c);
}
return userCards.ToArray ();
}
public UserCard[] GetUserCards(Guid walkerId, string setId)
{
var collection = database.GetCollection<UserCard>("user_cards");
List<UserCard> userCards = new List<UserCard> ();
var query = Query.And(Query<UserCard>.EQ(c => c.SetId, setId.ToUpper()),
Query<UserCard>.EQ(c => c.PlaneswalkerId, walkerId),
Query<UserCard>.GT(c => c.Amount, 0));
var cards = collection.Find (query);
foreach(UserCard c in cards)
{
userCards.Add (c);
}
return userCards.ToArray ();
}
public UserCard AddUserCard(Guid walkerId, int multiverseId, int amount)
{
MongoCollection<UserCard> cards = database.GetCollection<UserCard> ("user_cards");
var query = Query.And(Query<UserCard>.EQ (e => e.MultiverseId, multiverseId),
Query<UserCard>.EQ (e => e.PlaneswalkerId, walkerId));
UserCard card = cards.FindOne(query);
if(card == null)
{
UserCard newCard = new UserCard ();
newCard.Id = Guid.NewGuid ();
newCard.Amount = amount;
newCard.MultiverseId = multiverseId;
newCard.PlaneswalkerId = walkerId;
newCard.SetId = magicdb.GetCard (multiverseId).CardSetId;
cards.Insert (newCard);
card = newCard;
}
else
{
card.Amount = amount;
cards.Save (card);
}
return card;
}
public Guid AddPlaneswalker(string userName, string password, string email)
{
var collection = database.GetCollection<Profile>("profiles");
User user = ssa.CreateUser (userName, password, email);
Profile profile = new Profile ();
profile.Id = user.Id;
profile.CreatedAt = DateTime.Now;
profile.Email = user.Email;
profile.Name = user.UserName;
WriteConcernResult result = collection.Insert(profile);
return user.Id;
}
public void RemovePlaneswalker(Guid id)
{
var collection = database.GetCollection<Profile> ("profiles");
Dictionary<string, object> query = new Dictionary<string, object> ();
query.Add ("_id", id);
MongoCollection<UserCard> cards = database.GetCollection<UserCard> ("user_cards");
var rmCards = Query<UserCard>.EQ (e => e.PlaneswalkerId, id);
collection.Remove(new QueryDocument(query));
cards.Remove (rmCards);
}
public Profile GetProfile(Guid id)
{
var collection = database.GetCollection<Profile> ("profiles");
var query = Query<Profile>.EQ (e => e.Id, id);
Profile p = collection.FindOne (query);
if (p != null)
return p;
return null;
}
public Profile GetProfile(string name)
{
var collection = database.GetCollection<Profile> ("profiles");
var query = Query<Profile>.EQ (e => e.Name, name);
Profile p = collection.FindOne (query);
if (p != null)
return p;
return null;
}
public Planeswalker UpdatePlaneswalker(Planeswalker planeswalker)
{
MongoCollection<Profile> walkers = database.GetCollection<Profile> ("profiles");
var query = Query<Profile>.EQ (e => e.Id, planeswalker.Id);
Profile updateWalker = walkers.FindOne(query);
Planeswalker user = null;
if (updateWalker != null)
{
if(updateWalker.Email.ToLower() != planeswalker.Profile.Email.ToLower())
{
ssa.ChangeEmail (planeswalker.AuthToken, planeswalker.Profile.Email);
}
if(updateWalker.Name.ToLower() != planeswalker.Profile.Name.ToLower())
{
ssa.ChangeUserName (planeswalker.AuthToken, planeswalker.Profile.Name);
}
updateWalker.Email = planeswalker.Profile.Email;
updateWalker.ModifiedAt = DateTime.Now;
updateWalker.Name = planeswalker.Profile.Name;
walkers.Save(updateWalker);
User ssaUser = ssa.Validate (planeswalker.AuthToken);
user = new Planeswalker
{
UserName = ssaUser.UserName,
AuthToken = ssaUser.AuthToken,
Email = ssaUser.Email,
Id = ssaUser.Id,
Claims = ssaUser.Claims,
Roles = ssaUser.Roles,
Profile = GetProfile(ssaUser.Id)
};
}
return user;
}
private void CreateChangeRequestIndexes()
{
var keys = new IndexKeysBuilder();
keys.Ascending("Id");
var options = new IndexOptionsBuilder();
options.SetSparse(true);
options.SetUnique(true);
var collection = database.GetCollection<CardChange>("card_changes");
collection.EnsureIndex(keys, options);
}
private void CreateUserCardIndexes()
{
var keys = new IndexKeysBuilder();
keys.Ascending("PlaneswalkerId","MultiverseId");
var options = new IndexOptionsBuilder();
options.SetSparse(true);
options.SetUnique(true);
var collection = database.GetCollection<UserCard>("user_cards");
collection.EnsureIndex(keys, options);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="MobileAppCategoryConstantServiceClient"/> instances.</summary>
public sealed partial class MobileAppCategoryConstantServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="MobileAppCategoryConstantServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="MobileAppCategoryConstantServiceSettings"/>.</returns>
public static MobileAppCategoryConstantServiceSettings GetDefault() => new MobileAppCategoryConstantServiceSettings();
/// <summary>
/// Constructs a new <see cref="MobileAppCategoryConstantServiceSettings"/> object with default settings.
/// </summary>
public MobileAppCategoryConstantServiceSettings()
{
}
private MobileAppCategoryConstantServiceSettings(MobileAppCategoryConstantServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetMobileAppCategoryConstantSettings = existing.GetMobileAppCategoryConstantSettings;
OnCopy(existing);
}
partial void OnCopy(MobileAppCategoryConstantServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>MobileAppCategoryConstantServiceClient.GetMobileAppCategoryConstant</c> and
/// <c>MobileAppCategoryConstantServiceClient.GetMobileAppCategoryConstantAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetMobileAppCategoryConstantSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="MobileAppCategoryConstantServiceSettings"/> object.</returns>
public MobileAppCategoryConstantServiceSettings Clone() => new MobileAppCategoryConstantServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="MobileAppCategoryConstantServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class MobileAppCategoryConstantServiceClientBuilder : gaxgrpc::ClientBuilderBase<MobileAppCategoryConstantServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public MobileAppCategoryConstantServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public MobileAppCategoryConstantServiceClientBuilder()
{
UseJwtAccessWithScopes = MobileAppCategoryConstantServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref MobileAppCategoryConstantServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<MobileAppCategoryConstantServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override MobileAppCategoryConstantServiceClient Build()
{
MobileAppCategoryConstantServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<MobileAppCategoryConstantServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<MobileAppCategoryConstantServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private MobileAppCategoryConstantServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return MobileAppCategoryConstantServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<MobileAppCategoryConstantServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return MobileAppCategoryConstantServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => MobileAppCategoryConstantServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
MobileAppCategoryConstantServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => MobileAppCategoryConstantServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>MobileAppCategoryConstantService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch mobile app category constants.
/// </remarks>
public abstract partial class MobileAppCategoryConstantServiceClient
{
/// <summary>
/// The default endpoint for the MobileAppCategoryConstantService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default MobileAppCategoryConstantService scopes.</summary>
/// <remarks>
/// The default MobileAppCategoryConstantService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="MobileAppCategoryConstantServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="MobileAppCategoryConstantServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="MobileAppCategoryConstantServiceClient"/>.</returns>
public static stt::Task<MobileAppCategoryConstantServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new MobileAppCategoryConstantServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="MobileAppCategoryConstantServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="MobileAppCategoryConstantServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="MobileAppCategoryConstantServiceClient"/>.</returns>
public static MobileAppCategoryConstantServiceClient Create() =>
new MobileAppCategoryConstantServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="MobileAppCategoryConstantServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="MobileAppCategoryConstantServiceSettings"/>.</param>
/// <returns>The created <see cref="MobileAppCategoryConstantServiceClient"/>.</returns>
internal static MobileAppCategoryConstantServiceClient Create(grpccore::CallInvoker callInvoker, MobileAppCategoryConstantServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient grpcClient = new MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient(callInvoker);
return new MobileAppCategoryConstantServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC MobileAppCategoryConstantService client</summary>
public virtual MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::MobileAppCategoryConstant GetMobileAppCategoryConstant(GetMobileAppCategoryConstantRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(GetMobileAppCategoryConstantRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(GetMobileAppCategoryConstantRequest request, st::CancellationToken cancellationToken) =>
GetMobileAppCategoryConstantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::MobileAppCategoryConstant GetMobileAppCategoryConstant(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetMobileAppCategoryConstant(new GetMobileAppCategoryConstantRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetMobileAppCategoryConstantAsync(new GetMobileAppCategoryConstantRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetMobileAppCategoryConstantAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::MobileAppCategoryConstant GetMobileAppCategoryConstant(gagvr::MobileAppCategoryConstantName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetMobileAppCategoryConstant(new GetMobileAppCategoryConstantRequest
{
ResourceNameAsMobileAppCategoryConstantName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(gagvr::MobileAppCategoryConstantName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetMobileAppCategoryConstantAsync(new GetMobileAppCategoryConstantRequest
{
ResourceNameAsMobileAppCategoryConstantName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(gagvr::MobileAppCategoryConstantName resourceName, st::CancellationToken cancellationToken) =>
GetMobileAppCategoryConstantAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>MobileAppCategoryConstantService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch mobile app category constants.
/// </remarks>
public sealed partial class MobileAppCategoryConstantServiceClientImpl : MobileAppCategoryConstantServiceClient
{
private readonly gaxgrpc::ApiCall<GetMobileAppCategoryConstantRequest, gagvr::MobileAppCategoryConstant> _callGetMobileAppCategoryConstant;
/// <summary>
/// Constructs a client wrapper for the MobileAppCategoryConstantService service, with the specified gRPC client
/// and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="MobileAppCategoryConstantServiceSettings"/> used within this client.
/// </param>
public MobileAppCategoryConstantServiceClientImpl(MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient grpcClient, MobileAppCategoryConstantServiceSettings settings)
{
GrpcClient = grpcClient;
MobileAppCategoryConstantServiceSettings effectiveSettings = settings ?? MobileAppCategoryConstantServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetMobileAppCategoryConstant = clientHelper.BuildApiCall<GetMobileAppCategoryConstantRequest, gagvr::MobileAppCategoryConstant>(grpcClient.GetMobileAppCategoryConstantAsync, grpcClient.GetMobileAppCategoryConstant, effectiveSettings.GetMobileAppCategoryConstantSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetMobileAppCategoryConstant);
Modify_GetMobileAppCategoryConstantApiCall(ref _callGetMobileAppCategoryConstant);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetMobileAppCategoryConstantApiCall(ref gaxgrpc::ApiCall<GetMobileAppCategoryConstantRequest, gagvr::MobileAppCategoryConstant> call);
partial void OnConstruction(MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient grpcClient, MobileAppCategoryConstantServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC MobileAppCategoryConstantService client</summary>
public override MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient GrpcClient { get; }
partial void Modify_GetMobileAppCategoryConstantRequest(ref GetMobileAppCategoryConstantRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::MobileAppCategoryConstant GetMobileAppCategoryConstant(GetMobileAppCategoryConstantRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetMobileAppCategoryConstantRequest(ref request, ref callSettings);
return _callGetMobileAppCategoryConstant.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(GetMobileAppCategoryConstantRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetMobileAppCategoryConstantRequest(ref request, ref callSettings);
return _callGetMobileAppCategoryConstant.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using Umbraco.Extensions;
using Umbraco.Cms.Infrastructure.PublishedCache.DataSource;
using Umbraco.Cms.Tests.Common.Builders.Extensions;
using Umbraco.Cms.Tests.Common.Builders.Interfaces;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Core.PropertyEditors;
using Moq;
using Umbraco.Cms.Infrastructure.Serialization;
using System.Linq;
namespace Umbraco.Cms.Tests.Common.Builders
{
public class ContentDataBuilder : BuilderBase<ContentData>, IWithNameBuilder
{
private string _name;
private DateTime? _now;
private string _segment;
private int? _versionId;
private int? _writerId;
private int? _templateId;
private bool? _published;
private Dictionary<string, PropertyData[]> _properties;
private Dictionary<string, CultureVariation> _cultureInfos;
string IWithNameBuilder.Name
{
get => _name;
set => _name = value;
}
public ContentDataBuilder WithVersionDate(DateTime now)
{
_now = now;
return this;
}
public ContentDataBuilder WithUrlSegment(string segment)
{
_segment = segment;
return this;
}
public ContentDataBuilder WithVersionId(int versionId)
{
_versionId = versionId;
return this;
}
public ContentDataBuilder WithWriterId(int writerId)
{
_writerId = writerId;
return this;
}
public ContentDataBuilder WithTemplateId(int templateId)
{
_templateId = templateId;
return this;
}
public ContentDataBuilder WithPublished(bool published)
{
_published = published;
return this;
}
public ContentDataBuilder WithProperties(Dictionary<string, PropertyData[]> properties)
{
_properties = properties;
return this;
}
public ContentDataBuilder WithCultureInfos(Dictionary<string, CultureVariation> cultureInfos)
{
_cultureInfos = cultureInfos;
return this;
}
/// <summary>
/// Build and dynamically update an existing content type
/// </summary>
/// <typeparam name="TContentType"></typeparam>
/// <param name="shortStringHelper"></param>
/// <param name="propertyDataTypes"></param>
/// <param name="contentType"></param>
/// <param name="contentTypeAlias">
/// Will configure the content type with this alias/name if supplied when it's not already set on the content type.
/// </param>
/// <param name="autoCreateCultureNames"></param>
/// <returns></returns>
public ContentData Build<TContentType>(
IShortStringHelper shortStringHelper,
Dictionary<string, IDataType> propertyDataTypes,
TContentType contentType,
string contentTypeAlias = null,
bool autoCreateCultureNames = false) where TContentType : class, IContentTypeComposition
{
if (_name.IsNullOrWhiteSpace())
{
throw new InvalidOperationException("Cannot build without a name");
}
_segment ??= _name.ToLower().ReplaceNonAlphanumericChars('-');
// create or copy the current culture infos for the content
Dictionary<string, CultureVariation> contentCultureInfos = _cultureInfos == null
? new Dictionary<string, CultureVariation>()
: new Dictionary<string, CultureVariation>(_cultureInfos);
contentType.Alias ??= contentTypeAlias;
contentType.Name ??= contentTypeAlias;
contentType.Key = contentType.Key == default ? Guid.NewGuid() : contentType.Key;
contentType.Id = contentType.Id == default ? Math.Abs(contentTypeAlias.GetHashCode()) : contentType.Id;
if (_properties == null)
{
_properties = new Dictionary<string, PropertyData[]>();
}
foreach (KeyValuePair<string, PropertyData[]> prop in _properties)
{
//var dataType = new DataType(new VoidEditor("Label", Mock.Of<IDataValueEditorFactory>()), new ConfigurationEditorJsonSerializer())
//{
// Id = 4
//};
if (!propertyDataTypes.TryGetValue(prop.Key, out IDataType dataType))
{
dataType = propertyDataTypes.First().Value;
}
var propertyType = new PropertyType(shortStringHelper, dataType, prop.Key);
// check each property for culture and set variations accordingly,
// this will also ensure that we have the correct culture name on the content
// set for each culture too.
foreach (PropertyData cultureValue in prop.Value.Where(x => !x.Culture.IsNullOrWhiteSpace()))
{
// set the property type to vary based on the values
propertyType.Variations |= ContentVariation.Culture;
// if there isn't already a culture, then add one with the default name
if (autoCreateCultureNames && !contentCultureInfos.TryGetValue(cultureValue.Culture, out CultureVariation cultureVariation))
{
cultureVariation = new CultureVariation
{
Date = DateTime.Now,
IsDraft = true,
Name = _name,
UrlSegment = _segment
};
contentCultureInfos[cultureValue.Culture] = cultureVariation;
}
}
// set variations for segments if there is any
if (prop.Value.Any(x => !x.Segment.IsNullOrWhiteSpace()))
{
propertyType.Variations |= ContentVariation.Segment;
contentType.Variations |= ContentVariation.Segment;
}
if (!contentType.PropertyTypeExists(propertyType.Alias))
{
contentType.AddPropertyType(propertyType);
}
}
if (contentCultureInfos.Count > 0)
{
contentType.Variations |= ContentVariation.Culture;
WithCultureInfos(contentCultureInfos);
}
var result = Build();
return result;
}
public override ContentData Build()
{
var now = _now ?? DateTime.Now;
var versionId = _versionId ?? 1;
var writerId = _writerId ?? -1;
var templateId = _templateId ?? 0;
var published = _published ?? true;
var properties = _properties ?? new Dictionary<string, PropertyData[]>();
var cultureInfos = _cultureInfos ?? new Dictionary<string, CultureVariation>();
var segment = _segment ?? _name.ToLower().ReplaceNonAlphanumericChars('-');
var contentData = new ContentData(
_name,
segment,
versionId,
now,
writerId,
templateId,
published,
properties,
cultureInfos);
return contentData;
}
public static ContentData CreateBasic(string name, DateTime? versionDate = null)
=> new ContentDataBuilder()
.WithName(name)
.WithVersionDate(versionDate ?? DateTime.Now)
.Build();
public static ContentData CreateVariant(string name, Dictionary<string, CultureVariation> cultureInfos, DateTime? versionDate = null, bool published = true)
=> new ContentDataBuilder()
.WithName(name)
.WithVersionDate(versionDate ?? DateTime.Now)
.WithCultureInfos(cultureInfos)
.WithPublished(published)
.Build();
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;
using Bloom.ToPalaso;
using L10NSharp;
using SIL.Reporting;
using SIL.Xml;
namespace Bloom.Book
{
/// <summary>
/// Most editable elements in Bloom are multilingual. They have a wrapping <div> and then inner divs which are visible or not,
/// depending on various settings. This class manages creating those inner divs, and marking them with classes that turn on
/// visibility or move the element around the page, depending on the stylesheet in use.
///
/// Also, page <div/>s are marked with one of these classes: bloom-monolingual, bloom-bilingual, and bloom-trilingual
///
/// <div class="bloom-translationGroup" data-default-langauges='V, N1'>
/// <div class="bloom-editable" contenteditable="true" lang="en">The Mother said...</div>
/// <div class="bloom-editable" contenteditable="true" lang="tpi">Mama i tok:</div>
/// <div class="bloom-editable contenteditable="true" lang="xyz">abada fakwan</div>
/// </div>
/// </summary>
public static class TranslationGroupManager
{
/// <summary>
/// For each group of editable elements in the div which have lang attributes (normally, a .bloom-translationGroup div),
/// make sure we have child elements with the lang codes we need (most often, a .bloom-editable in the vernacular
/// is added).
/// Also enable/disable editing as warranted (e.g. in shell mode or not)
/// </summary>
public static void PrepareElementsInPageOrDocument(XmlNode pageOrDocumentNode, BookData bookData)
{
GenerateEditableDivsWithPreTranslatedContent(pageOrDocumentNode);
foreach (var code in bookData.GetBasicBookLanguageCodes())
PrepareElementsOnPageOneLanguage(pageOrDocumentNode, code);
// I'm not sure exactly why, but GetBasicBookLanguageCodes() returns
// the languages identified as L1 (and possibly, if turned on, L2 and L3)
// and M1. I'm nervous about changing that. But it's now possible for
// a group to specify (using N2 in data-default-languages) that it should
// have an M2 block, and M2 may not be any of the GetBasicBookLanguageCodes()
// languages (unless we're in trilingual mode). So we need another method
// to handle any special languages this block needs that are not considered
// 'basic' for this book.
PrepareSpecialLanguageGroups(pageOrDocumentNode, bookData);
FixGroupStyleSettings(pageOrDocumentNode);
}
static void PrepareSpecialLanguageGroups(XmlNode pageDiv, BookData bookData)
{
foreach (
XmlElement groupElement in
pageDiv.SafeSelectNodes("descendant-or-self::*[contains(@class,'bloom-translationGroup')]"))
{
var dataDefaultLangs = groupElement.Attributes["data-default-languages"]?.Value;
if (dataDefaultLangs != null && dataDefaultLangs.Contains("N2"))
{
MakeElementWithLanguageForOneGroup(groupElement, bookData.MetadataLanguage2IsoCode);
}
}
}
/// <summary>
/// Normally, the connection between bloom-translationGroups and the dataDiv is that each bloom-editable child
/// (which has an @lang) pulls the corresponding string from the dataDiv. This happens in BookData.
///
/// That works except in the case of xmatter which a) start empty and b) only normally get filled with
/// .bloom-editable's for the current languages. Then, when bloom would normally show a source bubble listing
/// the string in other languages, well there's nothing to show (the bubble can't pull from dataDiv).
/// So our solution here is to pre-pack the translationGroup with bloom-editable's for each of the languages
/// in the data-div.
/// The original (an possibly only) instance of this is with book titles. See bl-1210.
/// </summary>
public static void PrepareDataBookTranslationGroups(XmlNode pageOrDocumentNode, IEnumerable<string> languageCodes)
{
//At first, I set out to select all translationGroups that have child .bloomEditables that have data-book attributes
//however this has implications on other fields, noticeably the acknowledgments. So in order to get this fixed
//and not open another can of worms, I've reduce the scope of this
//fix to just the bookTitle, so I'm going with findOnlyBookTitleFields for now
//var findAllDataBookFields = "descendant-or-self::*[contains(@class,'bloom-translationGroup') and descendant::div[@data-book and contains(@class,'bloom-editable')]]";
var findOnlyBookTitleFields = "descendant-or-self::*[contains(@class,'bloom-translationGroup') and descendant::div[@data-book='bookTitle' and contains(@class,'bloom-editable')]]";
foreach (XmlElement groupElement in
pageOrDocumentNode.SafeSelectNodes(findOnlyBookTitleFields))
{
foreach (var lang in languageCodes)
{
MakeElementWithLanguageForOneGroup(groupElement, lang);
}
}
}
/// <summary>
/// Returns the sequence of bloom-editable divs that would normally be created as the content of an empty bloom-translationGroup,
/// given the current collection and book settings, with the classes that would normally be set on them prior to editing to make the right ones visible etc.
/// </summary>
public static string GetDefaultTranslationGroupContent(XmlNode pageOrDocumentNode, Book currentBook)
{
// First get a XMLDocument so that we can start creating elements using it.
XmlDocument ownerDocument = pageOrDocumentNode?.OwnerDocument;
if (ownerDocument == null) // the OwnerDocument child can be null if pageOrDocumentNode is a document itself
{
if (pageOrDocumentNode is XmlDocument)
{
ownerDocument = pageOrDocumentNode as XmlDocument;
}
else
{
return "";
}
}
// We want to use the usual routines that insert the required bloom-editables and classes into existing translation groups.
// To make this work we make a temporary translation group
// Since one of the routines expects the TG to be a descendant of the element passed to it, we make another layer of temporary wrapper around the translation group as well
var containerElement = ownerDocument.CreateElement("div");
containerElement.SetAttribute("class", "bloom-translationGroup");
var wrapper = ownerDocument.CreateElement("div");
wrapper.AppendChild(containerElement);
PrepareElementsInPageOrDocument(containerElement, currentBook.BookData);
TranslationGroupManager.UpdateContentLanguageClasses(wrapper, currentBook.BookData, currentBook.Language1IsoCode,
currentBook.Language2IsoCode, currentBook.Language3IsoCode);
return containerElement.InnerXml;
}
private static void GenerateEditableDivsWithPreTranslatedContent(XmlNode elementOrDom)
{
foreach (XmlElement editableDiv in elementOrDom.SafeSelectNodes(".//*[contains(@class,'bloom-editable') and @data-generate-translations and @data-i18n]"))
{
var englishText = editableDiv.InnerText;
var l10nId = editableDiv.Attributes["data-i18n"].Value;
if (String.IsNullOrWhiteSpace(l10nId))
continue;
foreach (var uiLanguage in LocalizationManager.GetAvailableLocalizedLanguages())
{
var translation = LocalizationManager.GetDynamicStringOrEnglish("Bloom", l10nId, englishText, null, uiLanguage);
if (translation == englishText)
continue;
var newEditableDiv = elementOrDom.OwnerDocument.CreateElement("div");
newEditableDiv.SetAttribute("class", "bloom-editable");
newEditableDiv.SetAttribute("lang", LanguageLookupModelExtensions.GetGeneralCode(uiLanguage));
newEditableDiv.InnerText = translation;
editableDiv.ParentNode.AppendChild(newEditableDiv);
}
editableDiv.RemoveAttribute("data-generate-translations");
editableDiv.RemoveAttribute("data-i18n");
}
}
/// <summary>
/// This is used when a book is first created from a source; without it, if the shell maker left the book as trilingual when working on it,
/// then every time someone created a new book based on it, it too would be trilingual.
/// </summary>
/// <remarks>
/// This method explicitly used the CollectionSettings languages in creating a new book.
/// </remarks>
public static void SetInitialMultilingualSetting(BookData bookData, int oneTwoOrThreeContentLanguages)
{
//var multilingualClass = new string[]{"bloom-monolingual", "bloom-bilingual","bloom-trilingual"}[oneTwoOrThreeContentLanguages-1];
if (oneTwoOrThreeContentLanguages < 3)
bookData.RemoveAllForms("contentLanguage3");
if (oneTwoOrThreeContentLanguages < 2)
bookData.RemoveAllForms("contentLanguage2");
var language1 = bookData.CollectionSettings.Language1;
bookData.Set("contentLanguage1", XmlString.FromUnencoded(language1.Iso639Code), false);
bookData.Set("contentLanguage1Rtl", XmlString.FromUnencoded(language1.IsRightToLeft.ToString()), false);
if (oneTwoOrThreeContentLanguages > 1)
{
var language2 = bookData.CollectionSettings.Language2;
bookData.Set("contentLanguage2", XmlString.FromUnencoded(language2.Iso639Code), false);
bookData.Set("contentLanguage2Rtl", XmlString.FromUnencoded(language2.IsRightToLeft.ToString()), false);
}
var language3 = bookData.CollectionSettings.Language3;
if (oneTwoOrThreeContentLanguages > 2 && !String.IsNullOrEmpty(language3.Iso639Code))
{
bookData.Set("contentLanguage3", XmlString.FromUnencoded(language3.Iso639Code), false);
bookData.Set("contentLanguage3Rtl", XmlString.FromUnencoded(language3.IsRightToLeft.ToString()), false);
}
}
/// <summary>
/// We stick various classes on editable things to control order and visibility
/// </summary>
public static void UpdateContentLanguageClasses(XmlNode elementOrDom, BookData bookData,
string language1IsoCode, string language2IsoCode, string language3IsoCode)
{
var multilingualClass = "bloom-monolingual";
var contentLanguages = new Dictionary<string, string>();
contentLanguages.Add(language1IsoCode, "bloom-content1");
if (!String.IsNullOrEmpty(language2IsoCode) && language1IsoCode != language2IsoCode)
{
multilingualClass = "bloom-bilingual";
contentLanguages.Add(language2IsoCode, "bloom-content2");
}
if (!String.IsNullOrEmpty(language3IsoCode) && language1IsoCode != language3IsoCode &&
language2IsoCode != language3IsoCode)
{
multilingualClass = "bloom-trilingual";
contentLanguages.Add(language3IsoCode, "bloom-content3");
Debug.Assert(!String.IsNullOrEmpty(language2IsoCode), "shouldn't have a content3 lang with no content2 lang");
}
//Stick a class in the page div telling the stylesheet how many languages we are displaying (only makes sense for content pages, in Jan 2012).
foreach (
XmlElement pageDiv in
elementOrDom.SafeSelectNodes(
"descendant-or-self::div[contains(@class,'bloom-page') and not(contains(@class,'bloom-frontMatter')) and not(contains(@class,'bloom-backMatter'))]")
)
{
HtmlDom.RemoveClassesBeginingWith(pageDiv, "bloom-monolingual");
HtmlDom.RemoveClassesBeginingWith(pageDiv, "bloom-bilingual");
HtmlDom.RemoveClassesBeginingWith(pageDiv, "bloom-trilingual");
HtmlDom.AddClassIfMissing(pageDiv, multilingualClass);
}
// This is the "code" part of the visibility system: https://goo.gl/EgnSJo
foreach (XmlElement group in GetTranslationGroups(elementOrDom))
{
var dataDefaultLanguages = HtmlDom.GetAttributeValue(@group, "data-default-languages").Split(new char[] { ',', ' ' },
StringSplitOptions.RemoveEmptyEntries);
//nb: we don't necessarily care that a div is editable or not
foreach (XmlElement e in @group.SafeSelectNodes(".//textarea | .//div"))
{
UpdateContentLanguageClassesOnElement(e, contentLanguages, bookData, language2IsoCode, language3IsoCode, dataDefaultLanguages);
}
}
// Also correct bloom-contentX fields in the bloomDataDiv, which are not listed under translation groups
foreach (XmlElement coverImageDescription in elementOrDom.SafeSelectNodes(".//*[@id='bloomDataDiv']/*[@data-book='coverImageDescription']"))
{
string[] dataDefaultLanguages = new string[] { " auto" }; // bloomDataDiv contents don't have dataDefaultLanguages on them, so just go with "auto"
//nb: we don't necessarily care that a div is editable or not
foreach (XmlElement e in coverImageDescription.SafeSelectNodes(".//textarea | .//div"))
{
UpdateContentLanguageClassesOnElement(e, contentLanguages, bookData, language2IsoCode, language3IsoCode, dataDefaultLanguages);
}
}
}
public static XmlElement[] GetTranslationGroups(XmlNode elementOrDom, bool omitBoxHeaders = true)
{
var groups = elementOrDom
.SafeSelectNodes(".//div[contains(@class, 'bloom-translationGroup')]")
.Cast<XmlElement>();
if (omitBoxHeaders)
{
groups = groups.Where(g => !g.Attributes["class"].Value.Contains("box-header-off"));
}
return groups.ToArray();
}
private static void UpdateContentLanguageClassesOnElement(XmlElement e, Dictionary<string, string> contentLanguages, BookData bookData, string contentLanguageIso2, string contentLanguageIso3, string[] dataDefaultLanguages)
{
HtmlDom.RemoveClassesBeginingWith(e, "bloom-content");
var lang = e.GetAttribute("lang");
//These bloom-content* classes are used by some stylesheet rules, primarily to boost the font-size of some languages.
//Enhance: this is too complex; the semantics of these overlap with each other and with bloom-visibility-code-on, and with data-language-order.
//It would be better to have non-overlapping things; 1 for order, 1 for visibility, one for the lang's role in this collection.
string orderClass;
if (contentLanguages.TryGetValue(lang, out orderClass))
{
HtmlDom.AddClass(e, orderClass); //bloom-content1, bloom-content2, bloom-content3
}
//Enhance: it's even more likely that we can get rid of these by replacing them with bloom-content2, bloom-content3
if (lang == bookData.MetadataLanguage1IsoCode)
{
HtmlDom.AddClass(e, "bloom-contentNational1");
}
// It's not clear that this class should be applied to blocks where lang == bookData.Language3IsoCode.
// I (JohnT) added lang == bookData.MetadataLanguage2IsoCode while dealing with BL-10893
// but am reluctant to remove the old code as something might depend on it. I believe it is (nearly?)
// always true that if we have Language3IsoCode at all, it will be equal to MetadataLanguage2IsoCode,
// so at least for now it probably makes no difference. In our next major reworking of language codes,
// hopefully we can make this distinction clearer and remove Language3IsoCode here.
if (lang == bookData.Language3IsoCode || lang == bookData.MetadataLanguage2IsoCode)
{
HtmlDom.AddClass(e, "bloom-contentNational2");
}
HtmlDom.RemoveClassesBeginingWith(e, "bloom-visibility-code");
if (ShouldNormallyShowEditable(lang, dataDefaultLanguages, contentLanguageIso2, contentLanguageIso3, bookData))
{
HtmlDom.AddClass(e, "bloom-visibility-code-on");
}
UpdateRightToLeftSetting(bookData, e, lang);
}
private static void UpdateRightToLeftSetting(BookData bookData, XmlElement e, string lang)
{
HtmlDom.RemoveRtlDir(e);
if((lang == bookData.Language1IsoCode && bookData.Language1.IsRightToLeft) ||
(lang == bookData.Language2IsoCode && bookData.Language2.IsRightToLeft) ||
(lang == bookData.Language3IsoCode && bookData.Language3.IsRightToLeft) ||
(lang == bookData.MetadataLanguage1IsoCode && bookData.MetadataLanguage1.IsRightToLeft))
{
HtmlDom.AddRtlDir(e);
}
}
/// <summary>
/// Here, "normally" means unless the user overrides via a .bloom-visibility-user-on/off
/// </summary>
internal static bool ShouldNormallyShowEditable(string lang, string[] dataDefaultLanguages,
string contentLanguageIso2, string contentLanguageIso3, // these are effected by the multilingual settings for this book
BookData bookData) // use to get the collection's current N1 and N2 in xmatter or other template pages that specify default languages
{
// Note: There is code in bloom-player that is modeled after this code.
// If this function changes, you should check in bloom-player's bloom-player-core.tsx file, function shouldNormallyShowEditable().
// It may benefit from being updated too.
if (dataDefaultLanguages == null || dataDefaultLanguages.Length == 0
|| String.IsNullOrWhiteSpace(dataDefaultLanguages[0])
|| dataDefaultLanguages[0].Equals("auto",StringComparison.InvariantCultureIgnoreCase))
{
return lang == bookData.Language1.Iso639Code || lang == contentLanguageIso2 || lang == contentLanguageIso3;
}
else
{
// Note there are (perhaps unfortunately) two different labeling systems, but they have a more-or-less 1-to-1 correspondence:
// The V/N1/N2 system feels natural in vernacular book contexts
// The L1/L2/L3 system is more natural in source book contexts.
// But, the new model makes L2 and L3 mean the second and third checked languages, while N1 and N2 are the
// second and third metadata languages, currently locked to the collection L2 and L3.
// V and L1 both mean the first checked language.
// Changes here should result in consistent ones in Book.IsLanguageWanted and BookData.GatherDataItemsFromXElement
// and RuntimeInformationInjector.AddUIDictionaryToDom and I18ApiHandleI18nRequest
return (lang == bookData.Language1.Iso639Code && dataDefaultLanguages.Contains("V")) ||
(lang == bookData.Language1.Iso639Code && dataDefaultLanguages.Contains("L1")) ||
(lang == bookData.MetadataLanguage1IsoCode && dataDefaultLanguages.Contains("N1")) ||
(lang == bookData.Language2IsoCode && dataDefaultLanguages.Contains("L2")) ||
(lang == bookData.MetadataLanguage2IsoCode && dataDefaultLanguages.Contains("N2")) ||
(lang == bookData.Language3IsoCode && dataDefaultLanguages.Contains("L3")) ||
dataDefaultLanguages.Contains(lang); // a literal language id, e.g. "en" (used by template starter)
}
}
private static int GetOrderOfThisLanguageInTheTextBlock(string editableIso, string vernacularIso, string contentLanguageIso2, string contentLanguageIso3)
{
if (editableIso == vernacularIso)
return 1;
if (editableIso == contentLanguageIso2)
return 2;
if (editableIso == contentLanguageIso3)
return 3;
return -1;
}
private static void PrepareElementsOnPageOneLanguage(XmlNode pageDiv, string isoCode)
{
foreach (
XmlElement groupElement in
pageDiv.SafeSelectNodes("descendant-or-self::*[contains(@class,'bloom-translationGroup')]"))
{
MakeElementWithLanguageForOneGroup(groupElement, isoCode);
//remove any elements in the translationgroup which don't have a lang (but ignore any label elements, which we're using for annotating groups)
foreach (
XmlElement elementWithoutLanguage in
groupElement.SafeSelectNodes("textarea[not(@lang)] | div[not(@lang) and not(self::label)]"))
{
elementWithoutLanguage.ParentNode.RemoveChild(elementWithoutLanguage);
}
}
//any editable areas which still don't have a language, set them to the vernacular (this is used for simple templates (non-shell pages))
foreach (
XmlElement element in
pageDiv.SafeSelectNodes( //NB: the jscript will take items with bloom-editable and set the contentEdtable to true.
"descendant-or-self::textarea[not(@lang)] | descendant-or-self::*[(contains(@class, 'bloom-editable') or @contentEditable='true' or @contenteditable='true') and not(@lang)]")
)
{
element.SetAttribute("lang", isoCode);
}
foreach (XmlElement e in pageDiv.SafeSelectNodes("descendant-or-self::*[starts-with(text(),'{')]"))
{
foreach (var node in e.ChildNodes)
{
XmlText t = node as XmlText;
if (t != null && t.Value.StartsWith("{"))
t.Value = "";
//otherwise html tidy will throw away spans (at least) that are empty, so we never get a chance to fill in the values.
}
}
}
/// <summary>
/// If the group element contains more than one child div in the given language, remove or
/// merge the duplicates.
/// </summary>
/// <remarks>
/// We've had at least one user end up with duplicate vernacular divs in a shell book. (She
/// was using Bloom 4.3 to translate a shell book created with Bloom 3.7.) I haven't been
/// able to reproduce the effect or isolate the cause, but this fixes things.
/// See https://issues.bloomlibrary.org/youtrack/issue/BL-6923.
/// </remarks>
internal static void FixDuplicateLanguageDivs(XmlElement groupElement, string isoCode)
{
XmlNodeList list = groupElement.SafeSelectNodes("./div[@lang='" + isoCode + "']");
if (list.Count > 1)
{
var count = list.Count;
foreach (XmlNode div in list)
{
var innerText = div.InnerText.Trim();
if (String.IsNullOrEmpty(innerText))
{
Logger.WriteEvent($"An empty duplicate div for {isoCode} has been removed from a translation group.");
groupElement.RemoveChild(div);
--count;
if (count == 1)
break;
}
}
if (count > 1)
{
Logger.WriteEvent($"Duplicate divs for {isoCode} have been merged in a translation group.");
list = groupElement.SafeSelectNodes("./div[@lang='" + isoCode + "']");
XmlNode first = list[0];
for (int i = 1; i < list.Count; ++i)
{
var newline = groupElement.OwnerDocument.CreateTextNode(Environment.NewLine);
first.AppendChild(newline);
foreach (XmlNode node in list[i].ChildNodes)
first.AppendChild(node);
groupElement.RemoveChild(list[i]);
}
}
}
}
/// <summary>
/// Shift any translationGroup level style setting to child editable divs that lack a style.
/// This is motivated by the fact HTML/CSS underlining cannot be turned off in child nodes.
/// So if underlining is enabled for Normal, everything everywhere would be underlined
/// regardless of style or immediate character formatting. If a style sets underlining
/// on, then immediate character formatting cannot turn it off anywhere in a text box that
/// uses that style. See https://silbloom.myjetbrains.com/youtrack/issue/BL-6282.
/// </summary>
private static void FixGroupStyleSettings(XmlNode pageDiv)
{
foreach (
XmlElement groupElement in
pageDiv.SafeSelectNodes("descendant-or-self::*[contains(@class,'bloom-translationGroup')]"))
{
var groupStyle = HtmlDom.GetStyle(groupElement);
if (String.IsNullOrEmpty(groupStyle))
continue;
// Copy the group's style setting to any child div with the bloom-editable class that lacks one.
// Then remove the group style if it does have any child divs with the bloom-editable class.
bool hasInternalEditableDiv = false;
foreach (XmlElement element in groupElement.SafeSelectNodes("child::div[contains(@class, 'bloom-editable')]"))
{
var divStyle = HtmlDom.GetStyle(element);
if (String.IsNullOrEmpty(divStyle))
HtmlDom.AddClass(element, groupStyle);
hasInternalEditableDiv = true;
}
if (hasInternalEditableDiv)
HtmlDom.RemoveClass(groupElement, groupStyle);
}
}
/// <summary>
/// For each group (meaning they have a common parent) of editable items, we
/// need to make sure there are the correct set of copies, with appropriate @lang attributes
/// </summary>
public static XmlElement MakeElementWithLanguageForOneGroup(XmlElement groupElement, string isoCode)
{
if (groupElement.GetAttribute("class").Contains("STOP"))
{
Console.Write("stop");
}
XmlNodeList editableChildrenOfTheGroup =
groupElement.SafeSelectNodes("*[self::textarea or contains(@class,'bloom-editable')]");
var elementsAlreadyInThisLanguage = from XmlElement x in editableChildrenOfTheGroup
where x.GetAttribute("lang") == isoCode
select x;
if (elementsAlreadyInThisLanguage.Any())
//don't mess with this set, it already has a vernacular (this will happen when we're editing a shellbook, not just using it to make a vernacular edition)
return elementsAlreadyInThisLanguage.First();
if (groupElement.SafeSelectNodes("ancestor-or-self::*[contains(@class,'bloom-translationGroup')]").Count == 0)
return null;
var prototype = editableChildrenOfTheGroup[0] as XmlElement;
XmlElement newElementInThisLanguage;
if (prototype == null) //this was an empty translation-group (unusual, but we can cope)
{
newElementInThisLanguage = groupElement.OwnerDocument.CreateElement("div");
newElementInThisLanguage.SetAttribute("class", "bloom-editable");
newElementInThisLanguage.SetAttribute("contenteditable", "true");
if (groupElement.HasAttribute("data-placeholder"))
{
newElementInThisLanguage.SetAttribute("data-placeholder", groupElement.GetAttribute("data-placeholder"));
}
groupElement.AppendChild(newElementInThisLanguage);
}
else //this is the normal situation, where we're just copying the first element
{
//what we want to do is copy everything in the element, except that which is specific to a language.
//so classes on the element, non-text children (like images), etc. should be copied
newElementInThisLanguage = (XmlElement) prototype.ParentNode.InsertAfter(prototype.Clone(), prototype);
//if there is an id, get rid of it, because we don't want 2 elements with the same id
newElementInThisLanguage.RemoveAttribute("id");
// Since we change the ID, the corresponding mp3 will change, which means the duration is no longer valid
newElementInThisLanguage.RemoveAttribute("data-duration");
// No need to copy over the audio-sentence markup
// Various code expects elements with class audio-sentence to have an ID.
// Both will be added when and if we do audio recording (in whole-text-box mode) on the new div.
// Until then it makes things more consistent if we make sure elements without ids
// don't have this class.
// Also, if audio recording markup is done using one audio-sentence span per sentence, we won't copy it. (Because we strip all out the text underneath this node)
// So, it's more consistent to treat all scenarios the same way (don't copy the audio-sentence markup)
HtmlDom.RemoveClass(newElementInThisLanguage, "audio-sentence");
// Nor any need to copy over other audio markup
// We want to clear up all the audio markup so it's not left in an inconsistent state
// where the Talking Book JS code thinks it's been initialized already, but actually all the audio-sentence markup has been stripped out :(
// See BL-8215
newElementInThisLanguage.RemoveAttribute("data-audiorecordingmode");
newElementInThisLanguage.RemoveAttribute("data-audiorecordingendtimes");
HtmlDom.RemoveClass(newElementInThisLanguage, "bloom-postAudioSplit");
//OK, now any text in there will belong to the prototype language, so remove it, while retaining everything else
StripOutText(newElementInThisLanguage);
}
newElementInThisLanguage.SetAttribute("lang", isoCode);
return newElementInThisLanguage;
}
/// <summary>
/// Remove nodes that are either pure text or exist only to contain text, including BR and P
/// Elements with a "bloom-cloneToOtherLanguages" class are preserved
/// </summary>
/// <param name="element"></param>
private static void StripOutText(XmlNode element)
{
var listToRemove = new List<XmlNode>();
foreach (XmlNode node in element.SelectNodes("descendant-or-self::*[(self::p or self::br or self::u or self::b or self::i) and not(contains(@class,'bloom-cloneToOtherLanguages'))]"))
{
listToRemove.Add(node);
}
// clean up any remaining texts that weren't enclosed
foreach (XmlNode node in element.SelectNodes("descendant-or-self::*[not(contains(@class,'bloom-cloneToOtherLanguages'))]/text()"))
{
listToRemove.Add(node);
}
RemoveXmlChildren(listToRemove);
}
private static void RemoveXmlChildren(List<XmlNode> removalList)
{
foreach (var node in removalList)
{
if(node.ParentNode != null)
node.ParentNode.RemoveChild(node);
}
}
/// <summary>
/// Sort the list of translation groups into the order their audio should be spoken,
/// which is also the order used for Spreadsheet import/export. Ones that have tabindex are
/// sorted by that. Ones that don't sort after ones that do, in the order
/// they occur in the input list (that is, the sort is stable, typically preserving
/// document order if that is how the input list was generated).
/// </summary>
/// <param name="groups"></param>
/// <returns></returns>
public static List<XmlElement> SortTranslationGroups(IEnumerable<XmlElement> groups)
{
// This is better than making the list and then using List's Sort method,
// because it is guaranteed to be a stable sort, keeping things with the same
// (or no) tabindex in the original, typically document, order.
return groups.OrderBy(GetTabIndex).ToList();
}
private static int GetTabIndex(XmlElement x)
{
if (Int32.TryParse(x.Attributes["tabindex"]?.Value ?? "x", out int val))
return val;
return Int32.MaxValue;
}
/// <summary>
/// bloom-translationGroup elements on the page in audio-reading order.
/// </summary>
public static List<XmlElement> SortedGroupsOnPage(XmlElement page, bool omitBoxHeaders = false)
{
return TranslationGroupManager.SortTranslationGroups(GetTranslationGroups(page, omitBoxHeaders));
}
}
}
| |
// ==++==
//
// Copyright(c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
namespace System.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Metadata;
#endif //FEATURE_REMOTING
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using MemberListType = System.RuntimeType.MemberListType;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
using System.Runtime.CompilerServices;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_MethodInfo))]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MethodInfo : MethodBase, _MethodInfo
{
#region Constructor
protected MethodInfo() { }
#endregion
#if !FEATURE_CORECLR
public static bool operator ==(MethodInfo left, MethodInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimeMethodInfo || right is RuntimeMethodInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(MethodInfo left, MethodInfo right)
{
return !(left == right);
}
#endif // !FEATURE_CORECLR
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Method; } }
#endregion
#region Public Abstract\Virtual Members
public virtual Type ReturnType { get { throw new NotImplementedException(); } }
public virtual ParameterInfo ReturnParameter { get { throw new NotImplementedException(); } }
public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get; }
public abstract MethodInfo GetBaseDefinition();
[System.Runtime.InteropServices.ComVisible(true)]
public override Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
[System.Runtime.InteropServices.ComVisible(true)]
public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
#endregion
#if !FEATURE_CORECLR
Type _MethodInfo.GetType()
{
return base.GetType();
}
void _MethodInfo.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _MethodInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _MethodInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
// If you implement this method, make sure to include _MethodInfo.Invoke in VM\DangerousAPIs.h and
// include _MethodInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
void _MethodInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
[Serializable]
internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo
{
#region Private Data Members
private IntPtr m_handle;
private RuntimeTypeCache m_reflectedTypeCache;
private string m_name;
private string m_toString;
private ParameterInfo[] m_parameters;
private ParameterInfo m_returnParameter;
private BindingFlags m_bindingFlags;
private MethodAttributes m_methodAttributes;
private Signature m_signature;
private RuntimeType m_declaringType;
private object m_keepalive;
private INVOCATION_FLAGS m_invocationFlags;
#if FEATURE_APPX
private bool IsNonW8PFrameworkAPI()
{
if (m_declaringType.IsArray && IsPublic && !IsStatic)
return false;
RuntimeAssembly rtAssembly = GetRuntimeAssembly();
if (rtAssembly.IsFrameworkAssembly())
{
int ctorToken = rtAssembly.InvocableAttributeCtorToken;
if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
!CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
return true;
}
if (GetRuntimeType().IsNonW8PFrameworkAPI())
return true;
if (IsGenericMethod && !IsGenericMethodDefinition)
{
foreach (Type t in GetGenericArguments())
{
if (((RuntimeType)t).IsNonW8PFrameworkAPI())
return true;
}
}
return false;
}
internal override bool IsDynamicallyInvokable
{
get
{
return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI();
}
}
#endif
internal INVOCATION_FLAGS InvocationFlags
{
[System.Security.SecuritySafeCritical]
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN;
Type declaringType = DeclaringType;
//
// first take care of all the NO_INVOKE cases.
if (ContainsGenericParameters ||
ReturnType.IsByRef ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) ||
((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject))
{
// We don't need other flags if this method cannot be invoked
invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
else
{
// this should be an invocable method, determine the other flags that participate in invocation
invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this);
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0)
{
if ( (Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
(declaringType != null && declaringType.NeedsReflectionSecurityCheck) )
{
// If method is non-public, or declaring type is not visible
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
}
else if (IsGenericMethod)
{
Type[] genericArguments = GetGenericArguments();
for (int i = 0; i < genericArguments.Length; i++)
{
if (genericArguments[i].NeedsReflectionSecurityCheck)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
break;
}
}
}
}
}
#if FEATURE_APPX
if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
#endif // FEATURE_APPX
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
#region Constructor
[System.Security.SecurityCritical] // auto-generated
internal RuntimeMethodInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType,
RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive)
{
Contract.Ensures(!m_handle.IsNull());
Contract.Assert(!handle.IsNullHandle());
Contract.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
m_keepalive = keepalive;
m_handle = handle.Value;
m_reflectedTypeCache = reflectedTypeCache;
m_methodAttributes = methodAttributes;
}
#endregion
#if FEATURE_REMOTING
#region Legacy Remoting Cache
// The size of CachedData is accounted for by BaseObjectWithCachedData in object.h.
// This member is currently being used by Remoting for caching remoting data. If you
// need to cache data here, talk to the Remoting team to work out a mechanism, so that
// both caching systems can happily work together.
private RemotingMethodCachedData m_cachedData;
internal RemotingMethodCachedData RemotingCache
{
get
{
// This grabs an internal copy of m_cachedData and uses
// that instead of looking at m_cachedData directly because
// the cache may get cleared asynchronously. This prevents
// us from having to take a lock.
RemotingMethodCachedData cache = m_cachedData;
if (cache == null)
{
cache = new RemotingMethodCachedData(this);
RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null);
if (ret != null)
cache = ret;
}
return cache;
}
}
#endregion
#endif //FEATURE_REMOTING
#region Private Methods
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
[System.Security.SecuritySafeCritical]
get
{
return new RuntimeMethodHandleInternal(m_handle);
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
[System.Security.SecurityCritical] // auto-generated
private ParameterInfo[] FetchNonReturnParameters()
{
if (m_parameters == null)
m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature);
return m_parameters;
}
[System.Security.SecurityCritical] // auto-generated
private ParameterInfo FetchReturnParameter()
{
if (m_returnParameter == null)
m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature);
return m_returnParameter;
}
#endregion
#region Internal Members
internal override string FormatNameAndSig(bool serialization)
{
// Serialization uses ToString to resolve MethodInfo overloads.
StringBuilder sbName = new StringBuilder(Name);
// serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads.
// serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString().
TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic;
if (IsGenericMethod)
sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format));
sbName.Append("(");
sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization));
sbName.Append(")");
return sbName.ToString();
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimeMethodInfo m = o as RuntimeMethodInfo;
if ((object)m == null)
return false;
return m.m_handle == m_handle;
}
internal Signature Signature
{
get
{
if (m_signature == null)
m_signature = new Signature(this, m_declaringType);
return m_signature;
}
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
// Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types
internal RuntimeMethodHandle GetMethodHandle()
{
return new RuntimeMethodHandle(this);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal RuntimeMethodInfo GetParentDefinition()
{
if (!IsVirtual || m_declaringType.IsInterface)
return null;
RuntimeType parent = (RuntimeType)m_declaringType.BaseType;
if (parent == null)
return null;
int slot = RuntimeMethodHandle.GetSlot(this);
if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot)
return null;
return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot));
}
// Unlike DeclaringType, this will return a valid type even for global methods
internal RuntimeType GetDeclaringTypeInternal()
{
return m_declaringType;
}
#endregion
#region Object Overrides
public override String ToString()
{
if (m_toString == null)
m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig();
return m_toString;
}
public override int GetHashCode()
{
// See RuntimeMethodInfo.Equals() below.
if (IsGenericMethod)
return ValueType.GetHashCodeOfPtr(m_handle);
else
return base.GetHashCode();
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(object obj)
{
if (!IsGenericMethod)
return obj == (object)this;
// We cannot do simple object identity comparisons for generic methods.
// Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo()
// retrive items from and insert items into s_methodInstantiations which is a CerHashtable.
//
RuntimeMethodInfo mi = obj as RuntimeMethodInfo;
if (mi == null || !mi.IsGenericMethod)
return false;
// now we know that both operands are generic methods
IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this);
IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi);
if (handle1.Value.Value != handle2.Value.Value)
return false;
Type[] lhs = GetGenericArguments();
Type[] rhs = mi.GetGenericArguments();
if (lhs.Length != rhs.Length)
return false;
for (int i = 0; i < lhs.Length; i++)
{
if (lhs[i] != rhs[i])
return false;
}
if (DeclaringType != mi.DeclaringType)
return false;
if (ReflectedType != mi.ReflectedType)
return false;
return true;
}
#endregion
#region ICustomAttributeProvider
[System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
m_name = RuntimeMethodHandle.GetName(this);
return m_name;
}
}
public override Type DeclaringType
{
get
{
if (m_reflectedTypeCache.IsGlobal)
return null;
return m_declaringType;
}
}
public override Type ReflectedType
{
get
{
if (m_reflectedTypeCache.IsGlobal)
return null;
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override MemberTypes MemberType { get { return MemberTypes.Method; } }
public override int MetadataToken
{
[System.Security.SecuritySafeCritical] // auto-generated
get { return RuntimeMethodHandle.GetMethodDef(this); }
}
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }
public override bool IsSecurityCritical
{
get { return RuntimeMethodHandle.IsSecurityCritical(this); }
}
public override bool IsSecuritySafeCritical
{
get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); }
}
public override bool IsSecurityTransparent
{
get { return RuntimeMethodHandle.IsSecurityTransparent(this); }
}
#endregion
#region MethodBase Overrides
[System.Security.SecuritySafeCritical] // auto-generated
internal override ParameterInfo[] GetParametersNoCopy()
{
FetchNonReturnParameters();
return m_parameters;
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Diagnostics.Contracts.Pure]
public override ParameterInfo[] GetParameters()
{
FetchNonReturnParameters();
if (m_parameters.Length == 0)
return m_parameters;
ParameterInfo[] ret = new ParameterInfo[m_parameters.Length];
Array.Copy(m_parameters, ret, m_parameters.Length);
return ret;
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return RuntimeMethodHandle.GetImplAttributes(this);
}
internal bool IsOverloaded
{
get
{
return m_reflectedTypeCache.GetMethodList(MemberListType.CaseSensitive, Name).Length > 1;
}
}
public override RuntimeMethodHandle MethodHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
return new RuntimeMethodHandle(this);
}
}
public override MethodAttributes Attributes { get { return m_methodAttributes; } }
public override CallingConventions CallingConvention
{
get
{
return Signature.CallingConvention;
}
}
[System.Security.SecuritySafeCritical] // overrides SafeCritical member
#if !FEATURE_CORECLR
#pragma warning disable 618
[ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)]
#pragma warning restore 618
#endif
public override MethodBody GetMethodBody()
{
MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
if (mb != null)
mb.m_methodBase = this;
return mb;
}
#endregion
#region Invocation Logic(On MemberBase)
private void CheckConsistency(Object target)
{
// only test instance methods
if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg"));
else
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch"));
}
}
}
[System.Security.SecuritySafeCritical]
private void ThrowNoInvokeException()
{
// method is ReflectionOnly
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
{
throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke"));
}
// method is on a class that contains stack pointers
else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0)
{
throw new NotSupportedException();
}
// method is vararg
else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
{
throw new NotSupportedException();
}
// method is generic or on a generic class
else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters)
{
throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam"));
}
// method is abstract class
else if (IsAbstract)
{
throw new MemberAccessException();
}
// ByRef return are not allowed in reflection
else if (ReturnType.IsByRef)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn"));
}
throw new TargetException();
}
[System.Security.SecuritySafeCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
#region Security Check
INVOCATION_FLAGS invocationFlags = InvocationFlags;
#if FEATURE_APPX
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
if (caller != null && !caller.IsSafeForReflection())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
{
#if !FEATURE_CORECLR
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0)
CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess);
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
#endif // !FEATURE_CORECLR
RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags);
}
#endregion
return UnsafeInvokeInternal(obj, parameters, arguments);
}
[System.Security.SecurityCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
return UnsafeInvokeInternal(obj, parameters, arguments);
}
[System.Security.SecurityCritical]
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
{
if (arguments == null || arguments.Length == 0)
return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false);
else
{
Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
Signature sig = Signature;
// get the signature
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
INVOCATION_FLAGS invocationFlags = InvocationFlags;
// INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type)
// contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot
// be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects.
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0)
ThrowNoInvokeException();
// check basic method consistency. This call will throw if there are problems in the target/method relationship
CheckConsistency(obj);
if (formalCount != actualCount)
throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
if (actualCount != 0)
return CheckArguments(parameters, binder, invokeAttr, culture, sig);
else
return null;
}
#endregion
#region MethodInfo Overrides
public override Type ReturnType
{
get { return Signature.ReturnType; }
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
get { return ReturnParameter; }
}
public override ParameterInfo ReturnParameter
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
Contract.Ensures(m_returnParameter != null);
FetchReturnParameter();
return m_returnParameter as ParameterInfo;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override MethodInfo GetBaseDefinition()
{
if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface)
return this;
int slot = RuntimeMethodHandle.GetSlot(this);
RuntimeType declaringType = (RuntimeType)DeclaringType;
RuntimeType baseDeclaringType = declaringType;
RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal();
do {
int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType);
if (cVtblSlots <= slot)
break;
baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot);
baseDeclaringType = declaringType;
declaringType = (RuntimeType)declaringType.BaseType;
} while (declaringType != null);
return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
}
[System.Security.SecuritySafeCritical]
public override Delegate CreateDelegate(Type delegateType)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
// open delegates only for backwards compatibility. But we'll allow
// relaxed signature checking and open static delegates because
// there's no ambiguity there (the caller would have to explicitly
// pass us a static method or a method with a non-exact signature
// and the only change in behavior from v1.1 there is that we won't
// fail the call).
return CreateDelegateInternal(
delegateType,
null,
DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature,
ref stackMark);
}
[System.Security.SecuritySafeCritical]
public override Delegate CreateDelegate(Type delegateType, Object target)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
// instance methods with relaxed signature checking). The delegate
// can also be closed over null. There's no ambiguity with all these
// options since the caller is providing us a specific MethodInfo.
return CreateDelegateInternal(
delegateType,
target,
DelegateBindingFlags.RelaxedSignature,
ref stackMark);
}
[System.Security.SecurityCritical]
private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark)
{
// Validate the parameters.
if (delegateType == null)
throw new ArgumentNullException("delegateType");
Contract.EndContractBlock();
RuntimeType rtType = delegateType as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "delegateType");
if (!rtType.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "delegateType");
Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark);
if (d == null)
{
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
}
return d;
}
#endregion
#region Generics
[System.Security.SecuritySafeCritical] // auto-generated
public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
{
if (methodInstantiation == null)
throw new ArgumentNullException("methodInstantiation");
Contract.EndContractBlock();
RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length];
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(
Environment.GetResourceString("Arg_NotGenericMethodDefinition", this));
for (int i = 0; i < methodInstantiation.Length; i++)
{
Type methodInstantiationElem = methodInstantiation[i];
if (methodInstantiationElem == null)
throw new ArgumentNullException();
RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType;
if (rtMethodInstantiationElem == null)
{
Type[] methodInstantiationCopy = new Type[methodInstantiation.Length];
for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++)
methodInstantiationCopy[iCopy] = methodInstantiation[iCopy];
methodInstantiation = methodInstantiationCopy;
return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation);
}
methodInstantionRuntimeType[i] = rtMethodInstantiationElem;
}
RuntimeType[] genericParameters = GetGenericArgumentsInternal();
RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters);
MethodInfo ret = null;
try
{
ret = RuntimeType.GetMethodBase(ReflectedTypeInternal,
RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(this.m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo;
}
catch (VerificationException e)
{
RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e);
throw;
}
return ret;
}
internal RuntimeType[] GetGenericArgumentsInternal()
{
return RuntimeMethodHandle.GetMethodInstantiationInternal(this);
}
public override Type[] GetGenericArguments()
{
Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this);
if (types == null)
{
types = EmptyArray<Type>.Value;
}
return types;
}
public override MethodInfo GetGenericMethodDefinition()
{
if (!IsGenericMethod)
throw new InvalidOperationException();
Contract.EndContractBlock();
return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo;
}
public override bool IsGenericMethod
{
get { return RuntimeMethodHandle.HasMethodInstantiation(this); }
}
public override bool IsGenericMethodDefinition
{
get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); }
}
public override bool ContainsGenericParameters
{
get
{
if (DeclaringType != null && DeclaringType.ContainsGenericParameters)
return true;
if (!IsGenericMethod)
return false;
Type[] pis = GetGenericArguments();
for (int i = 0; i < pis.Length; i++)
{
if (pis[i].ContainsGenericParameters)
return true;
}
return false;
}
}
#endregion
#region ISerializable Implementation
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
if (m_reflectedTypeCache.IsGlobal)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
SerializationToString(),
MemberTypes.Method,
IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null);
}
internal string SerializationToString()
{
return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true);
}
#endregion
#region Legacy Internal
internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark)
{
IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark);
if (method == null)
return null;
return RuntimeType.GetMethodBase(method);
}
#endregion
}
}
| |
/* ****************************************************************************
*
* 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
* [email protected]. 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 Microsoft.Scripting.Runtime;
using IronPython.Modules;
using IronPython.Runtime.Exceptions;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
using Complex = Microsoft.Scripting.Math.Complex64;
#endif
namespace IronPython.Runtime.Types {
public static class TypeCache {
#region Generated TypeCache Storage
// *** BEGIN GENERATED CODE ***
// generated by function: gen_typecache_storage from: generate_typecache.py
private static PythonType array;
private static PythonType builtinfunction;
private static PythonType pythondictionary;
private static PythonType frozensetcollection;
private static PythonType pythonfunction;
private static PythonType builtin;
private static PythonType obj;
private static PythonType setcollection;
private static PythonType pythontype;
private static PythonType str;
private static PythonType pythontuple;
private static PythonType weakreference;
private static PythonType list;
private static PythonType pythonfile;
private static PythonType pythonmodule;
private static PythonType method;
private static PythonType enumerate;
private static PythonType intType;
private static PythonType singleType;
private static PythonType doubleType;
private static PythonType biginteger;
private static PythonType complex;
private static PythonType super;
private static PythonType nullType;
private static PythonType boolType;
private static PythonType baseException;
// *** END GENERATED CODE ***
#endregion
#region Generated TypeCache Entries
// *** BEGIN GENERATED CODE ***
// generated by function: gen_typecache from: generate_typecache.py
public static PythonType Array {
get {
if (array == null) array = DynamicHelpers.GetPythonTypeFromType(typeof(Array));
return array;
}
}
public static PythonType BuiltinFunction {
get {
if (builtinfunction == null) builtinfunction = DynamicHelpers.GetPythonTypeFromType(typeof(BuiltinFunction));
return builtinfunction;
}
}
public static PythonType Dict {
get {
if (pythondictionary == null) pythondictionary = DynamicHelpers.GetPythonTypeFromType(typeof(PythonDictionary));
return pythondictionary;
}
}
public static PythonType FrozenSet {
get {
if (frozensetcollection == null) frozensetcollection = DynamicHelpers.GetPythonTypeFromType(typeof(FrozenSetCollection));
return frozensetcollection;
}
}
public static PythonType Function {
get {
if (pythonfunction == null) pythonfunction = DynamicHelpers.GetPythonTypeFromType(typeof(PythonFunction));
return pythonfunction;
}
}
public static PythonType Builtin {
get {
if (builtin == null) builtin = DynamicHelpers.GetPythonTypeFromType(typeof(Builtin));
return builtin;
}
}
public static PythonType Object {
get {
if (obj == null) obj = DynamicHelpers.GetPythonTypeFromType(typeof(Object));
return obj;
}
}
public static PythonType Set {
get {
if (setcollection == null) setcollection = DynamicHelpers.GetPythonTypeFromType(typeof(SetCollection));
return setcollection;
}
}
public static PythonType PythonType {
get {
if (pythontype == null) pythontype = DynamicHelpers.GetPythonTypeFromType(typeof(PythonType));
return pythontype;
}
}
public static PythonType String {
get {
if (str == null) str = DynamicHelpers.GetPythonTypeFromType(typeof(String));
return str;
}
}
public static PythonType PythonTuple {
get {
if (pythontuple == null) pythontuple = DynamicHelpers.GetPythonTypeFromType(typeof(PythonTuple));
return pythontuple;
}
}
public static PythonType WeakReference {
get {
if (weakreference == null) weakreference = DynamicHelpers.GetPythonTypeFromType(typeof(WeakReference));
return weakreference;
}
}
public static PythonType List {
get {
if (list == null) list = DynamicHelpers.GetPythonTypeFromType(typeof(List));
return list;
}
}
public static PythonType PythonFile {
get {
if (pythonfile == null) pythonfile = DynamicHelpers.GetPythonTypeFromType(typeof(PythonFile));
return pythonfile;
}
}
public static PythonType Module {
get {
if (pythonmodule == null) pythonmodule = DynamicHelpers.GetPythonTypeFromType(typeof(PythonModule));
return pythonmodule;
}
}
public static PythonType Method {
get {
if (method == null) method = DynamicHelpers.GetPythonTypeFromType(typeof(Method));
return method;
}
}
public static PythonType Enumerate {
get {
if (enumerate == null) enumerate = DynamicHelpers.GetPythonTypeFromType(typeof(Enumerate));
return enumerate;
}
}
public static PythonType Int32 {
get {
if (intType == null) intType = DynamicHelpers.GetPythonTypeFromType(typeof(Int32));
return intType;
}
}
public static PythonType Single {
get {
if (singleType == null) singleType = DynamicHelpers.GetPythonTypeFromType(typeof(Single));
return singleType;
}
}
public static PythonType Double {
get {
if (doubleType == null) doubleType = DynamicHelpers.GetPythonTypeFromType(typeof(Double));
return doubleType;
}
}
public static PythonType BigInteger {
get {
if (biginteger == null) biginteger = DynamicHelpers.GetPythonTypeFromType(typeof(BigInteger));
return biginteger;
}
}
public static PythonType Complex {
get {
if (complex == null) complex = DynamicHelpers.GetPythonTypeFromType(typeof(Complex));
return complex;
}
}
public static PythonType Super {
get {
if (super == null) super = DynamicHelpers.GetPythonTypeFromType(typeof(Super));
return super;
}
}
public static PythonType Null {
get {
if (nullType == null) nullType = DynamicHelpers.GetPythonTypeFromType(typeof(DynamicNull));
return nullType;
}
}
public static PythonType Boolean {
get {
if (boolType == null) boolType = DynamicHelpers.GetPythonTypeFromType(typeof(Boolean));
return boolType;
}
}
public static PythonType BaseException {
get {
if (baseException == null) baseException = DynamicHelpers.GetPythonTypeFromType(typeof(PythonExceptions.BaseException));
return baseException;
}
}
// *** END GENERATED CODE ***
#endregion
[Obsolete("use Complex instead")]
public static PythonType Complex64 {
get {
return Complex;
}
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Encog.Engine.Network.Activation;
using Encog.ML;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.ML.Data.Temporal;
using Encog.ML.Train;
using Encog.ML.Train.Strategy;
using Encog.Neural.Networks;
using Encog.Neural.Networks.Training;
using Encog.Neural.Networks.Training.Anneal;
using Encog.Neural.Networks.Training.Propagation.Back;
using Encog.Neural.Pattern;
using Encog.Util;
using Encog.Util.NetworkUtil;
using Encog.Util.Simple;
namespace Encog.Examples.Analyzer
{
public static class CreateEval
{
#region create an evaluation set from a file and train it
// ReSharper disable UnusedMember.Local
private static void CreateEvaluationSet(string @fileName)
// ReSharper restore UnusedMember.Local
{
List<double> Opens = QuickCSVUtils.QuickParseCSV(fileName, "Open", 1200, 1200);
List<double> High = QuickCSVUtils.QuickParseCSV(fileName, "High", 1200, 1200);
List<double> Low = QuickCSVUtils.QuickParseCSV(fileName, "Low", 1200, 1200);
List<double> Close = QuickCSVUtils.QuickParseCSV(fileName, "Close", 1200, 1200);
List<double> Volume = QuickCSVUtils.QuickParseCSV(fileName, 5, 1200, 1200);
double[] Ranges = NetworkUtility.CalculateRanges(Opens.ToArray(), Close.ToArray());
TemporalMLDataSet superTemportal = TrainerHelper.GenerateTrainingWithPercentChangeOnSerie(100, 1, Opens.ToArray(),
Close.ToArray(), High.ToArray(), Low.ToArray(), Volume.ToArray());
IMLDataPair aPairInput = TrainerHelper.ProcessPairs(NetworkUtility.CalculatePercents(Opens.ToArray()), NetworkUtility.CalculatePercents(Opens.ToArray()), 100, 1);
IMLDataPair aPairInput3 = TrainerHelper.ProcessPairs(NetworkUtility.CalculatePercents(Close.ToArray()), NetworkUtility.CalculatePercents(Close.ToArray()), 100, 1);
IMLDataPair aPairInput2 = TrainerHelper.ProcessPairs(NetworkUtility.CalculatePercents(High.ToArray()), NetworkUtility.CalculatePercents(High.ToArray()), 100, 1);
IMLDataPair aPairInput4 = TrainerHelper.ProcessPairs(NetworkUtility.CalculatePercents(Volume.ToArray()), NetworkUtility.CalculatePercents(Volume.ToArray()), 100, 1);
IMLDataPair aPairInput5 = TrainerHelper.ProcessPairs(NetworkUtility.CalculatePercents(Ranges.ToArray()), NetworkUtility.CalculatePercents(Ranges.ToArray()), 100, 1);
List<IMLDataPair> listData = new List<IMLDataPair>();
listData.Add(aPairInput);
listData.Add(aPairInput2);
listData.Add(aPairInput3);
listData.Add(aPairInput4);
listData.Add((aPairInput5));
var minitrainning = new BasicMLDataSet(listData);
var network = (BasicNetwork)CreateElmanNetwork(100, 1);
double normalCorrectRate = EvaluateNetworks(network, minitrainning);
double temporalErrorRate = EvaluateNetworks(network, superTemportal);
Console.WriteLine(@"Percent Correct with normal Data Set:" + normalCorrectRate + @" Percent Correct with temporal Dataset:" +
temporalErrorRate);
Console.WriteLine(@"Paused , Press a key to continue to evaluation");
Console.ReadKey();
}
public static double EvaluateNetworks(BasicNetwork network, BasicMLDataSet set)
{
int count = 0;
int correct = 0;
foreach (IMLDataPair pair in set)
{
IMLData input = pair.Input;
IMLData actualData = pair.Ideal;
IMLData predictData = network.Compute(input);
double actual = actualData[0];
double predict = predictData[0];
double diff = Math.Abs(predict - actual);
Direction actualDirection = DetermineDirection(actual);
Direction predictDirection = DetermineDirection(predict);
if (actualDirection == predictDirection)
correct++;
count++;
Console.WriteLine(@"Number" + @"count" + @": actual=" + Format.FormatDouble(actual, 4) + @"(" + actualDirection + @")"
+ @",predict=" + Format.FormatDouble(predict, 4) + @"(" + predictDirection + @")" + @",diff=" + diff);
}
double percent = correct / (double)count;
Console.WriteLine(@"Direction correct:" + correct + @"/" + count);
Console.WriteLine(@"Directional Accuracy:"
+ Format.FormatPercent(percent));
return percent;
}
#endregion
#region Direction enum
public enum Direction
{
Up,
Down
} ;
public static Direction DetermineDirection(double d)
{
return d < 0 ? Direction.Down : Direction.Up;
}
#endregion
public static double TrainNetworks(BasicNetwork network, IMLDataSet minis)
{
Backpropagation trainMain = new Backpropagation(network, minis,0.0001,0.6);
//set the number of threads below.
trainMain.ThreadCount = 0;
// train the neural network
ICalculateScore score = new TrainingSetScore(minis);
IMLTrain trainAlt = new NeuralSimulatedAnnealing(network, score, 10, 2, 100);
// IMLTrain trainMain = new Backpropagation(network, minis, 0.0001, 0.01);
StopTrainingStrategy stop = new StopTrainingStrategy(0.0001, 200);
trainMain.AddStrategy(new Greedy());
trainMain.AddStrategy(new HybridStrategy(trainAlt));
trainMain.AddStrategy(stop);
//prune strategy not in GIT!...Removing it.
//PruneStrategy strategypruning = new PruneStrategy(0.91d, 0.001d, 10, network,minis, 0, 20);
//trainMain.AddStrategy(strategypruning);
EncogUtility.TrainConsole(trainMain,network,minis, 15.2);
var sw = new Stopwatch();
sw.Start();
while (!stop.ShouldStop())
{
trainMain.Iteration();
Console.WriteLine(@"Iteration #:" + trainMain.IterationNumber + @" Error:" + trainMain.Error + @" Genetic Iteration:" + trainAlt.IterationNumber);
}
sw.Stop();
Console.WriteLine(@"Total elapsed time in seconds:" + TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds).Seconds);
return trainMain.Error;
}
public static BasicMLDataSet CreateEvaluationSetAndLoad(string @fileName, int startLine, int HowMany, int WindowSize, int outputsize)
{
List<double> Opens = QuickCSVUtils.QuickParseCSV(fileName, "Open", startLine, HowMany);
List<double> High = QuickCSVUtils.QuickParseCSV(fileName, "High", startLine, HowMany);
// List<double> Low = QuickCSVUtils.QuickParseCSV(fileName, "Low", startLine, HowMany);
List<double> Close = QuickCSVUtils.QuickParseCSV(fileName, "Close", startLine, HowMany);
List<double> Volume = QuickCSVUtils.QuickParseCSV(fileName, 5, startLine, HowMany);
double[] Ranges = NetworkUtility.CalculateRanges(Opens.ToArray(), Close.ToArray());
IMLDataPair aPairInput = TrainerHelper.ProcessPairs(NetworkUtility.CalculatePercents(Opens.ToArray()), NetworkUtility.CalculatePercents(Opens.ToArray()), WindowSize, outputsize);
IMLDataPair aPairInput3 = TrainerHelper.ProcessPairs(NetworkUtility.CalculatePercents(Close.ToArray()), NetworkUtility.CalculatePercents(Close.ToArray()), WindowSize, outputsize);
IMLDataPair aPairInput2 = TrainerHelper.ProcessPairs(NetworkUtility.CalculatePercents(High.ToArray()), NetworkUtility.CalculatePercents(High.ToArray()), WindowSize, outputsize);
IMLDataPair aPairInput4 = TrainerHelper.ProcessPairs(NetworkUtility.CalculatePercents(Volume.ToArray()), NetworkUtility.CalculatePercents(Volume.ToArray()), WindowSize, outputsize);
IMLDataPair aPairInput5 = TrainerHelper.ProcessPairs(NetworkUtility.CalculatePercents(Ranges.ToArray()), NetworkUtility.CalculatePercents(Ranges.ToArray()), WindowSize, outputsize);
List<IMLDataPair> listData = new List<IMLDataPair>();
listData.Add(aPairInput);
listData.Add(aPairInput2);
listData.Add(aPairInput3);
listData.Add(aPairInput4);
listData.Add((aPairInput5));
var minitrainning = new BasicMLDataSet(listData);
return minitrainning;
}
public static TemporalMLDataSet GenerateATemporalSet(string @fileName, int startLine, int HowMany, int WindowSize, int outputsize)
{
List<double> Opens = QuickCSVUtils.QuickParseCSV(fileName, "Open", startLine, HowMany);
List<double> High = QuickCSVUtils.QuickParseCSV(fileName, "High", startLine, HowMany);
List<double> Low = QuickCSVUtils.QuickParseCSV(fileName, "Low", startLine, HowMany);
List<double> Close = QuickCSVUtils.QuickParseCSV(fileName, "Close", startLine, HowMany);
List<double> Volume = QuickCSVUtils.QuickParseCSV(fileName, 5, startLine, HowMany);
return TrainerHelper.GenerateTrainingWithPercentChangeOnSerie(WindowSize, outputsize, Opens.ToArray(), Close.ToArray(), High.ToArray(), Low.ToArray(), Volume.ToArray());
}
public static IMLMethod CreateElmanNetwork(int inputsize, int outputsize)
{
// construct an Elman type network
ElmanPattern pattern = new ElmanPattern();
pattern.ActivationFunction = new ActivationTANH();
pattern.InputNeurons = inputsize;
pattern.AddHiddenLayer(0);
pattern.OutputNeurons = outputsize;
return pattern.Generate();
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Interceptors;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
internal interface IServerCallHandler
{
Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq);
}
internal class UnaryServerCallHandler<TRequest, TResponse> : IServerCallHandler
where TRequest : class
where TResponse : class
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<UnaryServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method;
readonly UnaryServerMethod<TRequest, TResponse> handler;
public UnaryServerCallHandler(Method<TRequest, TResponse> method, UnaryServerMethod<TRequest, TResponse> handler)
{
this.method = method;
this.handler = handler;
}
public async Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq)
{
var asyncCall = new AsyncCallServer<TRequest, TResponse>(
method.ResponseMarshaller.ContextualSerializer,
method.RequestMarshaller.ContextualDeserializer,
newRpc.Server);
asyncCall.Initialize(newRpc.Call, cq);
var finishedTask = asyncCall.ServerSideCallAsync();
var requestStream = new ServerRequestStream<TRequest, TResponse>(asyncCall);
var responseStream = new ServerResponseStream<TRequest, TResponse>(asyncCall);
Status status;
AsyncCallServer<TRequest,TResponse>.ResponseWithFlags? responseWithFlags = null;
var context = HandlerUtils.NewContext(newRpc, responseStream, asyncCall.CancellationToken);
try
{
GrpcPreconditions.CheckArgument(await requestStream.MoveNext().ConfigureAwait(false));
var request = requestStream.Current;
var response = await handler(request, context).ConfigureAwait(false);
status = context.Status;
responseWithFlags = new AsyncCallServer<TRequest, TResponse>.ResponseWithFlags(response, HandlerUtils.GetWriteFlags(context.WriteOptions));
}
catch (Exception e)
{
if (!(e is RpcException))
{
Logger.Warning(e, "Exception occurred in the handler or an interceptor.");
}
status = HandlerUtils.GetStatusFromExceptionAndMergeTrailers(e, context.ResponseTrailers);
}
try
{
await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, responseWithFlags).ConfigureAwait(false);
}
catch (Exception)
{
asyncCall.Cancel();
throw;
}
await finishedTask.ConfigureAwait(false);
}
}
internal class ServerStreamingServerCallHandler<TRequest, TResponse> : IServerCallHandler
where TRequest : class
where TResponse : class
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ServerStreamingServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method;
readonly ServerStreamingServerMethod<TRequest, TResponse> handler;
public ServerStreamingServerCallHandler(Method<TRequest, TResponse> method, ServerStreamingServerMethod<TRequest, TResponse> handler)
{
this.method = method;
this.handler = handler;
}
public async Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq)
{
var asyncCall = new AsyncCallServer<TRequest, TResponse>(
method.ResponseMarshaller.ContextualSerializer,
method.RequestMarshaller.ContextualDeserializer,
newRpc.Server);
asyncCall.Initialize(newRpc.Call, cq);
var finishedTask = asyncCall.ServerSideCallAsync();
var requestStream = new ServerRequestStream<TRequest, TResponse>(asyncCall);
var responseStream = new ServerResponseStream<TRequest, TResponse>(asyncCall);
Status status;
var context = HandlerUtils.NewContext(newRpc, responseStream, asyncCall.CancellationToken);
try
{
GrpcPreconditions.CheckArgument(await requestStream.MoveNext().ConfigureAwait(false));
var request = requestStream.Current;
await handler(request, responseStream, context).ConfigureAwait(false);
status = context.Status;
}
catch (Exception e)
{
if (!(e is RpcException))
{
Logger.Warning(e, "Exception occurred in the handler or an interceptor.");
}
status = HandlerUtils.GetStatusFromExceptionAndMergeTrailers(e, context.ResponseTrailers);
}
try
{
await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, null).ConfigureAwait(false);
}
catch (Exception)
{
asyncCall.Cancel();
throw;
}
await finishedTask.ConfigureAwait(false);
}
}
internal class ClientStreamingServerCallHandler<TRequest, TResponse> : IServerCallHandler
where TRequest : class
where TResponse : class
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ClientStreamingServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method;
readonly ClientStreamingServerMethod<TRequest, TResponse> handler;
public ClientStreamingServerCallHandler(Method<TRequest, TResponse> method, ClientStreamingServerMethod<TRequest, TResponse> handler)
{
this.method = method;
this.handler = handler;
}
public async Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq)
{
var asyncCall = new AsyncCallServer<TRequest, TResponse>(
method.ResponseMarshaller.ContextualSerializer,
method.RequestMarshaller.ContextualDeserializer,
newRpc.Server);
asyncCall.Initialize(newRpc.Call, cq);
var finishedTask = asyncCall.ServerSideCallAsync();
var requestStream = new ServerRequestStream<TRequest, TResponse>(asyncCall);
var responseStream = new ServerResponseStream<TRequest, TResponse>(asyncCall);
Status status;
AsyncCallServer<TRequest, TResponse>.ResponseWithFlags? responseWithFlags = null;
var context = HandlerUtils.NewContext(newRpc, responseStream, asyncCall.CancellationToken);
try
{
var response = await handler(requestStream, context).ConfigureAwait(false);
status = context.Status;
responseWithFlags = new AsyncCallServer<TRequest, TResponse>.ResponseWithFlags(response, HandlerUtils.GetWriteFlags(context.WriteOptions));
}
catch (Exception e)
{
if (!(e is RpcException))
{
Logger.Warning(e, "Exception occurred in the handler or an interceptor.");
}
status = HandlerUtils.GetStatusFromExceptionAndMergeTrailers(e, context.ResponseTrailers);
}
try
{
await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, responseWithFlags).ConfigureAwait(false);
}
catch (Exception)
{
asyncCall.Cancel();
throw;
}
await finishedTask.ConfigureAwait(false);
}
}
internal class DuplexStreamingServerCallHandler<TRequest, TResponse> : IServerCallHandler
where TRequest : class
where TResponse : class
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<DuplexStreamingServerCallHandler<TRequest, TResponse>>();
readonly Method<TRequest, TResponse> method;
readonly DuplexStreamingServerMethod<TRequest, TResponse> handler;
public DuplexStreamingServerCallHandler(Method<TRequest, TResponse> method, DuplexStreamingServerMethod<TRequest, TResponse> handler)
{
this.method = method;
this.handler = handler;
}
public async Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq)
{
var asyncCall = new AsyncCallServer<TRequest, TResponse>(
method.ResponseMarshaller.ContextualSerializer,
method.RequestMarshaller.ContextualDeserializer,
newRpc.Server);
asyncCall.Initialize(newRpc.Call, cq);
var finishedTask = asyncCall.ServerSideCallAsync();
var requestStream = new ServerRequestStream<TRequest, TResponse>(asyncCall);
var responseStream = new ServerResponseStream<TRequest, TResponse>(asyncCall);
Status status;
var context = HandlerUtils.NewContext(newRpc, responseStream, asyncCall.CancellationToken);
try
{
await handler(requestStream, responseStream, context).ConfigureAwait(false);
status = context.Status;
}
catch (Exception e)
{
if (!(e is RpcException))
{
Logger.Warning(e, "Exception occurred in the handler or an interceptor.");
}
status = HandlerUtils.GetStatusFromExceptionAndMergeTrailers(e, context.ResponseTrailers);
}
try
{
await asyncCall.SendStatusFromServerAsync(status, context.ResponseTrailers, null).ConfigureAwait(false);
}
catch (Exception)
{
asyncCall.Cancel();
throw;
}
await finishedTask.ConfigureAwait(false);
}
}
internal class UnimplementedMethodCallHandler : IServerCallHandler
{
public static readonly UnimplementedMethodCallHandler Instance = new UnimplementedMethodCallHandler();
DuplexStreamingServerCallHandler<byte[], byte[]> callHandlerImpl;
public UnimplementedMethodCallHandler()
{
var marshaller = new Marshaller<byte[]>((payload) => payload, (payload) => payload);
var method = new Method<byte[], byte[]>(MethodType.DuplexStreaming, "", "", marshaller, marshaller);
this.callHandlerImpl = new DuplexStreamingServerCallHandler<byte[], byte[]>(method, new DuplexStreamingServerMethod<byte[], byte[]>(UnimplementedMethod));
}
/// <summary>
/// Handler used for unimplemented method.
/// </summary>
private Task UnimplementedMethod(IAsyncStreamReader<byte[]> requestStream, IServerStreamWriter<byte[]> responseStream, ServerCallContext ctx)
{
ctx.Status = new Status(StatusCode.Unimplemented, "");
return TaskUtils.CompletedTask;
}
public Task HandleCall(ServerRpcNew newRpc, CompletionQueueSafeHandle cq)
{
return callHandlerImpl.HandleCall(newRpc, cq);
}
}
internal static class HandlerUtils
{
public static Status GetStatusFromExceptionAndMergeTrailers(Exception e, Metadata callContextResponseTrailers)
{
var rpcException = e as RpcException;
if (rpcException != null)
{
// There are two sources of metadata entries on the server-side:
// 1. serverCallContext.ResponseTrailers
// 2. trailers in RpcException thrown by user code in server side handler.
// As metadata allows duplicate keys, the logical thing to do is
// to just merge trailers from RpcException into serverCallContext.ResponseTrailers.
foreach (var entry in rpcException.Trailers)
{
callContextResponseTrailers.Add(entry);
}
// use the status thrown by handler.
return rpcException.Status;
}
return new Status(StatusCode.Unknown, "Exception was thrown by handler.");
}
public static WriteFlags GetWriteFlags(WriteOptions writeOptions)
{
return writeOptions != null ? writeOptions.Flags : default(WriteFlags);
}
public static ServerCallContext NewContext(ServerRpcNew newRpc, IServerResponseStream serverResponseStream, CancellationToken cancellationToken)
{
DateTime realtimeDeadline = newRpc.Deadline.ToClockType(ClockType.Realtime).ToDateTime();
return new DefaultServerCallContext(newRpc.Call, newRpc.Method, newRpc.Host, realtimeDeadline, newRpc.RequestMetadata, cancellationToken, serverResponseStream);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Diagnostics;
using System.Globalization;
using System.Management.Automation;
using Microsoft.Management.Infrastructure.Options;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
#region class ErrorToErrorRecord
/// <summary>
/// <para>
/// Convert error or exception to <see cref="System.Management.Automation.ErrorRecord"/>
/// </para>
/// </summary>
internal sealed class ErrorToErrorRecord
{
/// <summary>
/// <para>
/// Convert ErrorRecord from exception object, <see cref="Exception"/>
/// can be either <see cref="CimException"/> or general <see cref="Exception"/>.
/// </para>
/// </summary>
/// <param name="inner"></param>
/// <param name="context">The context starting the operation, which generated the error.</param>
/// <param name="cimResultContext">The CimResultContext used to provide ErrorSource, etc. info.</param>
/// <returns></returns>
internal static ErrorRecord ErrorRecordFromAnyException(
InvocationContext context,
Exception inner,
CimResultContext cimResultContext)
{
Debug.Assert(inner != null, "Caller should verify inner != null");
CimException cimException = inner as CimException;
if (cimException != null)
{
return CreateFromCimException(context, cimException, cimResultContext);
}
var containsErrorRecord = inner as IContainsErrorRecord;
if (containsErrorRecord != null)
{
return InitializeErrorRecord(context,
exception : inner,
errorId: "CimCmdlet_" + containsErrorRecord.ErrorRecord.FullyQualifiedErrorId,
errorCategory: containsErrorRecord.ErrorRecord.CategoryInfo.Category,
cimResultContext: cimResultContext);
}
else
{
return InitializeErrorRecord(context,
exception :inner,
errorId: "CimCmdlet_" + inner.GetType().Name,
errorCategory: ErrorCategory.NotSpecified,
cimResultContext: cimResultContext);
}
}
#region Helper functions
/// <summary>
/// Create <see cref="ErrorRecord"/> from <see cref="CimException"/> object.
/// </summary>
/// <param name="context"></param>
/// <param name="cimException"></param>
/// <param name="cimResultContext">The CimResultContext used to provide ErrorSource, etc. info.</param>
/// <returns></returns>
internal static ErrorRecord CreateFromCimException(
InvocationContext context,
CimException cimException,
CimResultContext cimResultContext)
{
Debug.Assert(cimException != null, "Caller should verify cimException != null");
return InitializeErrorRecord(context, cimException, cimResultContext);
}
/// <summary>
/// Create <see cref="ErrorRecord"/> from <see cref="Exception"/> object.
/// </summary>
/// <param name="context"></param>
/// <param name="exception"></param>
/// <param name="errorId"></param>
/// <param name="errorCategory"></param>
/// <param name="cimResultContext">The CimResultContext used to provide ErrorSource, etc. info.</param>
/// <returns></returns>
internal static ErrorRecord InitializeErrorRecord(
InvocationContext context,
Exception exception,
string errorId,
ErrorCategory errorCategory,
CimResultContext cimResultContext)
{
return InitializeErrorRecordCore(
context,
exception: exception,
errorId: errorId,
errorCategory: errorCategory,
cimResultContext: cimResultContext);
}
/// <summary>
/// Create <see cref="ErrorRecord"/> from <see cref="CimException"/> object.
/// </summary>
/// <param name="context"></param>
/// <param name="cimException"></param>
/// <param name="cimResultContext">The CimResultContext used to provide ErrorSource, etc. info.</param>
/// <returns></returns>
internal static ErrorRecord InitializeErrorRecord(
InvocationContext context,
CimException cimException,
CimResultContext cimResultContext)
{
ErrorRecord errorRecord = InitializeErrorRecordCore(
context,
exception: cimException,
errorId: cimException.MessageId ?? "MiClientApiError_" + cimException.NativeErrorCode,
errorCategory: ConvertCimExceptionToErrorCategory(cimException),
cimResultContext: cimResultContext);
if (cimException.ErrorData != null)
{
errorRecord.CategoryInfo.TargetName = cimException.ErrorSource;
}
return errorRecord;
}
/// <summary>
/// Create <see cref="ErrorRecord"/> from <see cref="Exception"/> object.
/// </summary>
/// <param name="context"></param>
/// <param name="exception"></param>
/// <param name="errorId"></param>
/// <param name="errorCategory"></param>
/// <param name="cimResultContext">The CimResultContext used to provide ErrorSource, etc. info.</param>
/// <returns></returns>
internal static ErrorRecord InitializeErrorRecordCore(
InvocationContext context,
Exception exception,
string errorId,
ErrorCategory errorCategory,
CimResultContext cimResultContext)
{
object theTargetObject = null;
if (cimResultContext != null)
{
theTargetObject = cimResultContext.ErrorSource;
}
if (theTargetObject == null)
{
if (context != null)
{
if (context.TargetCimInstance != null)
{
theTargetObject = context.TargetCimInstance;
}
}
}
ErrorRecord coreErrorRecord = new ErrorRecord(
exception: exception,
errorId: errorId,
errorCategory: errorCategory,
targetObject: theTargetObject);
if (context == null)
{
return coreErrorRecord;
}
System.Management.Automation.Remoting.OriginInfo originInfo = new System.Management.Automation.Remoting.OriginInfo(
context.ComputerName,
Guid.Empty);
ErrorRecord errorRecord = new System.Management.Automation.Runspaces.RemotingErrorRecord(
coreErrorRecord,
originInfo);
DebugHelper.WriteLogEx("Created RemotingErrorRecord.", 0);
return errorRecord;
}
/// <summary>
/// Convert <see cref="CimException"/> to <see cref="ErrorCategory"/>.
/// </summary>
/// <param name="cimException"></param>
/// <returns></returns>
internal static ErrorCategory ConvertCimExceptionToErrorCategory(CimException cimException)
{
ErrorCategory result = ErrorCategory.NotSpecified;
if (cimException.ErrorData != null)
{
result = ConvertCimErrorToErrorCategory(cimException.ErrorData);
}
if (result == ErrorCategory.NotSpecified)
{
result = ConvertCimNativeErrorCodeToErrorCategory(cimException.NativeErrorCode);
}
return result;
}
/// <summary>
/// Convert <see cref="NativeErrorCode"/> to <see cref="ErrorCategory"/>.
/// </summary>
/// <param name="nativeErrorCode"></param>
/// <returns></returns>
internal static ErrorCategory ConvertCimNativeErrorCodeToErrorCategory(NativeErrorCode nativeErrorCode)
{
switch (nativeErrorCode)
{
case NativeErrorCode.Failed:
return ErrorCategory.NotSpecified;
case NativeErrorCode.AccessDenied:
return ErrorCategory.PermissionDenied;
case NativeErrorCode.InvalidNamespace:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidParameter:
return ErrorCategory.InvalidArgument;
case NativeErrorCode.InvalidClass:
return ErrorCategory.MetadataError;
case NativeErrorCode.NotFound:
return ErrorCategory.ObjectNotFound;
case NativeErrorCode.NotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.ClassHasChildren:
return ErrorCategory.MetadataError;
case NativeErrorCode.ClassHasInstances:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidSuperClass:
return ErrorCategory.MetadataError;
case NativeErrorCode.AlreadyExists:
return ErrorCategory.ResourceExists;
case NativeErrorCode.NoSuchProperty:
return ErrorCategory.MetadataError;
case NativeErrorCode.TypeMismatch:
return ErrorCategory.InvalidType;
case NativeErrorCode.QueryLanguageNotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.InvalidQuery:
return ErrorCategory.InvalidArgument;
case NativeErrorCode.MethodNotAvailable:
return ErrorCategory.MetadataError;
case NativeErrorCode.MethodNotFound:
return ErrorCategory.MetadataError;
case NativeErrorCode.NamespaceNotEmpty:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidEnumerationContext:
return ErrorCategory.MetadataError;
case NativeErrorCode.InvalidOperationTimeout:
return ErrorCategory.InvalidArgument;
case NativeErrorCode.PullHasBeenAbandoned:
return ErrorCategory.OperationStopped;
case NativeErrorCode.PullCannotBeAbandoned:
return ErrorCategory.CloseError;
case NativeErrorCode.FilteredEnumerationNotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.ContinuationOnErrorNotSupported:
return ErrorCategory.NotImplemented;
case NativeErrorCode.ServerLimitsExceeded:
return ErrorCategory.ResourceBusy;
case NativeErrorCode.ServerIsShuttingDown:
return ErrorCategory.ResourceUnavailable;
default:
return ErrorCategory.NotSpecified;
}
}
/// <summary>
/// Convert <see cref="cimError"/> to <see cref="ErrorCategory"/>.
/// </summary>
/// <param name="cimError"></param>
/// <returns></returns>
internal static ErrorCategory ConvertCimErrorToErrorCategory(CimInstance cimError)
{
if (cimError == null)
{
return ErrorCategory.NotSpecified;
}
CimProperty errorCategoryProperty = cimError.CimInstanceProperties[@"Error_Category"];
if (errorCategoryProperty == null)
{
return ErrorCategory.NotSpecified;
}
ErrorCategory errorCategoryValue;
if (!LanguagePrimitives.TryConvertTo<ErrorCategory>(errorCategoryProperty.Value, CultureInfo.InvariantCulture, out errorCategoryValue))
{
return ErrorCategory.NotSpecified;
}
return errorCategoryValue;
}
#endregion
}
#endregion
/// <summary>
/// <para>
/// Write error to pipeline
/// </para>
/// </summary>
internal sealed class CimWriteError : CimSyncAction
{
/// <summary>
/// Constructor with an <see cref="CimInstance"/> error.
/// </summary>
/// <param name="error"></param>
public CimWriteError(CimInstance error, InvocationContext context)
{
this.error = error;
this.invocationContext = context;
}
/// <summary>
/// Construct with an exception object.
/// </summary>
/// <param name="exception"></param>
public CimWriteError(Exception exception, InvocationContext context, CimResultContext cimResultContext)
{
this.exception = exception;
this.invocationContext = context;
this.cimResultContext = cimResultContext;
}
/// <summary>
/// <para>
/// Write error to pipeline
/// </para>
/// </summary>
/// <param name="cmdlet"></param>
public override void Execute(CmdletOperationBase cmdlet)
{
Debug.Assert(cmdlet != null, "Caller should verify that cmdlet != null");
try
{
Exception errorException = (error != null) ? new CimException(error) : this.Exception;
// PS engine takes care of handling error action
cmdlet.WriteError(ErrorToErrorRecord.ErrorRecordFromAnyException(this.invocationContext, errorException, this.cimResultContext));
// if user wants to continue, we will get here
this.responseType = CimResponseType.Yes;
}
catch
{
this.responseType = CimResponseType.NoToAll;
throw;
}
finally
{
// unblocking the waiting thread
this.OnComplete();
}
}
#region members
/// <summary>
/// <para>
/// Error instance
/// </para>
/// </summary>
private CimInstance error;
internal CimInstance Error
{
get
{
return error;
}
}
/// <summary>
/// <para>
/// Exception object
/// </para>
/// </summary>
internal Exception Exception
{
get
{
return exception;
}
}
private Exception exception;
/// <summary>
/// <para>
/// <see cref="InvocationContext"/> object that contains
/// the information while issuing the current operation
/// </para>
/// </summary>
private InvocationContext invocationContext;
internal InvocationContext CimInvocationContext
{
get
{
return invocationContext;
}
}
/// <summary>
/// <see cref="CimResultConte"/>
/// </summary>
private CimResultContext cimResultContext;
internal CimResultContext ResultContext
{
get
{
return cimResultContext;
}
}
#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;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
using System.Text;
// This HttpHandlerDiagnosticListener class is applicable only for .NET 4.6, and not for .NET core.
namespace System.Diagnostics
{
/// <summary>
/// A HttpHandlerDiagnosticListener is a DiagnosticListener for .NET 4.6 and above where
/// HttpClient doesn't have a DiagnosticListener built in. This class is not used for .NET Core
/// because HttpClient in .NET Core already emits DiagnosticSource events. This class compensates for
/// that in .NET 4.6 and above. HttpHandlerDiagnosticListener has no public constructor. To use this,
/// the application just needs to call <see cref="DiagnosticListener.AllListeners" /> and
/// <see cref="DiagnosticListener.AllListenerObservable.Subscribe(IObserver{DiagnosticListener})"/>,
/// then in the <see cref="IObserver{DiagnosticListener}.OnNext(DiagnosticListener)"/> method,
/// when it sees the System.Net.Http.Desktop source, subscribe to it. This will trigger the
/// initialization of this DiagnosticListener.
/// </summary>
internal sealed class HttpHandlerDiagnosticListener : DiagnosticListener
{
/// <summary>
/// Overriding base class implementation just to give us a chance to initialize.
/// </summary>
public override IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled)
{
IDisposable result = base.Subscribe(observer, isEnabled);
Initialize();
return result;
}
/// <summary>
/// Overriding base class implementation just to give us a chance to initialize.
/// </summary>
public override IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Func<string, object, object, bool> isEnabled)
{
IDisposable result = base.Subscribe(observer, isEnabled);
Initialize();
return result;
}
/// <summary>
/// Overriding base class implementation just to give us a chance to initialize.
/// </summary>
public override IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer)
{
IDisposable result = base.Subscribe(observer);
Initialize();
return result;
}
/// <summary>
/// Initializes all the reflection objects it will ever need. Reflection is costly, but it's better to take
/// this one time performance hit than to get it multiple times later, or do it lazily and have to worry about
/// threading issues. If Initialize has been called before, it will not doing anything.
/// </summary>
private void Initialize()
{
lock (this)
{
if (!this.initialized)
{
try
{
// This flag makes sure we only do this once. Even if we failed to initialize in an
// earlier time, we should not retry because this initialization is not cheap and
// the likelihood it will succeed the second time is very small.
this.initialized = true;
PrepareReflectionObjects();
PerformInjection();
}
catch (Exception ex)
{
// If anything went wrong, just no-op. Write an event so at least we can find out.
this.Write(InitializationFailed, new { Exception = ex });
}
}
}
}
#region private helper classes
private class HashtableWrapper : Hashtable, IEnumerable
{
protected Hashtable _table;
public override int Count
{
get
{
return this._table.Count;
}
}
public override bool IsReadOnly
{
get
{
return this._table.IsReadOnly;
}
}
public override bool IsFixedSize
{
get
{
return this._table.IsFixedSize;
}
}
public override bool IsSynchronized
{
get
{
return this._table.IsSynchronized;
}
}
public override object this[object key]
{
get
{
return this._table[key];
}
set
{
this._table[key] = value;
}
}
public override object SyncRoot
{
get
{
return this._table.SyncRoot;
}
}
public override ICollection Keys
{
get
{
return this._table.Keys;
}
}
public override ICollection Values
{
get
{
return this._table.Values;
}
}
internal HashtableWrapper(Hashtable table) : base()
{
this._table = table;
}
public override void Add(object key, object value)
{
this._table.Add(key, value);
}
public override void Clear()
{
this._table.Clear();
}
public override bool Contains(object key)
{
return this._table.Contains(key);
}
public override bool ContainsKey(object key)
{
return this._table.ContainsKey(key);
}
public override bool ContainsValue(object key)
{
return this._table.ContainsValue(key);
}
public override void CopyTo(Array array, int arrayIndex)
{
this._table.CopyTo(array, arrayIndex);
}
public override object Clone()
{
return new HashtableWrapper((Hashtable)this._table.Clone());
}
IEnumerator IEnumerable.GetEnumerator()
{
return this._table.GetEnumerator();
}
public override IDictionaryEnumerator GetEnumerator()
{
return this._table.GetEnumerator();
}
public override void Remove(object key)
{
this._table.Remove(key);
}
}
/// <summary>
/// Helper class used for ServicePointManager.s_ServicePointTable. The goal here is to
/// intercept each new ServicePoint object being added to ServicePointManager.s_ServicePointTable
/// and replace its ConnectionGroupList hashtable field.
/// </summary>
private sealed class ServicePointHashtable : HashtableWrapper
{
public ServicePointHashtable(Hashtable table) : base(table)
{
}
public override object this[object key]
{
get
{
return base[key];
}
set
{
WeakReference weakRef = value as WeakReference;
if (weakRef != null && weakRef.IsAlive)
{
ServicePoint servicePoint = weakRef.Target as ServicePoint;
if (servicePoint != null)
{
// Replace the ConnectionGroup hashtable inside this ServicePoint object,
// which allows us to intercept each new ConnectionGroup object added under
// this ServicePoint.
Hashtable originalTable = s_connectionGroupListField.GetValue(servicePoint) as Hashtable;
ConnectionGroupHashtable newTable = new ConnectionGroupHashtable(originalTable ?? new Hashtable());
s_connectionGroupListField.SetValue(servicePoint, newTable);
}
}
base[key] = value;
}
}
}
/// <summary>
/// Helper class used for ServicePoint.m_ConnectionGroupList. The goal here is to
/// intercept each new ConnectionGroup object being added to ServicePoint.m_ConnectionGroupList
/// and replace its m_ConnectionList arraylist field.
/// </summary>
private sealed class ConnectionGroupHashtable : HashtableWrapper
{
public ConnectionGroupHashtable(Hashtable table) : base(table)
{
}
public override object this[object key]
{
get
{
return base[key];
}
set
{
if (s_connectionGroupType.IsInstanceOfType(value))
{
// Replace the Connection arraylist inside this ConnectionGroup object,
// which allows us to intercept each new Connection object added under
// this ConnectionGroup.
ArrayList originalArrayList = s_connectionListField.GetValue(value) as ArrayList;
ConnectionArrayList newArrayList = new ConnectionArrayList(originalArrayList ?? new ArrayList());
s_connectionListField.SetValue(value, newArrayList);
}
base[key] = value;
}
}
}
/// <summary>
/// Helper class used to wrap the array list object. This class itself doesn't actually
/// have the array elements, but rather access another array list that's given at
/// construction time.
/// </summary>
private class ArrayListWrapper : ArrayList
{
private ArrayList _list;
public override int Capacity
{
get
{
return this._list.Capacity;
}
set
{
this._list.Capacity = value;
}
}
public override int Count
{
get
{
return this._list.Count;
}
}
public override bool IsReadOnly
{
get
{
return this._list.IsReadOnly;
}
}
public override bool IsFixedSize
{
get
{
return this._list.IsFixedSize;
}
}
public override bool IsSynchronized
{
get
{
return this._list.IsSynchronized;
}
}
public override object this[int index]
{
get
{
return this._list[index];
}
set
{
this._list[index] = value;
}
}
public override object SyncRoot
{
get
{
return this._list.SyncRoot;
}
}
internal ArrayListWrapper(ArrayList list) : base()
{
this._list = list;
}
public override int Add(object value)
{
return this._list.Add(value);
}
public override void AddRange(ICollection c)
{
this._list.AddRange(c);
}
public override int BinarySearch(object value)
{
return this._list.BinarySearch(value);
}
public override int BinarySearch(object value, IComparer comparer)
{
return this._list.BinarySearch(value, comparer);
}
public override int BinarySearch(int index, int count, object value, IComparer comparer)
{
return this._list.BinarySearch(index, count, value, comparer);
}
public override void Clear()
{
this._list.Clear();
}
public override object Clone()
{
return new ArrayListWrapper((ArrayList)this._list.Clone());
}
public override bool Contains(object item)
{
return this._list.Contains(item);
}
public override void CopyTo(Array array)
{
this._list.CopyTo(array);
}
public override void CopyTo(Array array, int index)
{
this._list.CopyTo(array, index);
}
public override void CopyTo(int index, Array array, int arrayIndex, int count)
{
this._list.CopyTo(index, array, arrayIndex, count);
}
public override IEnumerator GetEnumerator()
{
return this._list.GetEnumerator();
}
public override IEnumerator GetEnumerator(int index, int count)
{
return this._list.GetEnumerator(index, count);
}
public override int IndexOf(object value)
{
return this._list.IndexOf(value);
}
public override int IndexOf(object value, int startIndex)
{
return this._list.IndexOf(value, startIndex);
}
public override int IndexOf(object value, int startIndex, int count)
{
return this._list.IndexOf(value, startIndex, count);
}
public override void Insert(int index, object value)
{
this._list.Insert(index, value);
}
public override void InsertRange(int index, ICollection c)
{
this._list.InsertRange(index, c);
}
public override int LastIndexOf(object value)
{
return this._list.LastIndexOf(value);
}
public override int LastIndexOf(object value, int startIndex)
{
return this._list.LastIndexOf(value, startIndex);
}
public override int LastIndexOf(object value, int startIndex, int count)
{
return this._list.LastIndexOf(value, startIndex, count);
}
public override void Remove(object value)
{
this._list.Remove(value);
}
public override void RemoveAt(int index)
{
this._list.RemoveAt(index);
}
public override void RemoveRange(int index, int count)
{
this._list.RemoveRange(index, count);
}
public override void Reverse(int index, int count)
{
this._list.Reverse(index, count);
}
public override void SetRange(int index, ICollection c)
{
this._list.SetRange(index, c);
}
public override ArrayList GetRange(int index, int count)
{
return this._list.GetRange(index, count);
}
public override void Sort()
{
this._list.Sort();
}
public override void Sort(IComparer comparer)
{
this._list.Sort(comparer);
}
public override void Sort(int index, int count, IComparer comparer)
{
this._list.Sort(index, count, comparer);
}
public override object[] ToArray()
{
return this._list.ToArray();
}
public override Array ToArray(Type type)
{
return this._list.ToArray(type);
}
public override void TrimToSize()
{
this._list.TrimToSize();
}
}
/// <summary>
/// Helper class used for ConnectionGroup.m_ConnectionList. The goal here is to
/// intercept each new Connection object being added to ConnectionGroup.m_ConnectionList
/// and replace its m_WriteList arraylist field.
/// </summary>
private sealed class ConnectionArrayList : ArrayListWrapper
{
public ConnectionArrayList(ArrayList list) : base(list)
{
}
public override int Add(object value)
{
if (s_connectionType.IsInstanceOfType(value))
{
// Replace the HttpWebRequest arraylist inside this Connection object,
// which allows us to intercept each new HttpWebRequest object added under
// this Connection.
ArrayList originalArrayList = s_writeListField.GetValue(value) as ArrayList;
HttpWebRequestArrayList newArrayList = new HttpWebRequestArrayList(originalArrayList ?? new ArrayList());
s_writeListField.SetValue(value, newArrayList);
}
return base.Add(value);
}
}
/// <summary>
/// Helper class used for Connection.m_WriteList. The goal here is to
/// intercept all new HttpWebRequest objects being added to Connection.m_WriteList
/// and notify the listener about the HttpWebRequest that's about to send a request.
/// It also intercepts all HttpWebRequest objects that are about to get removed from
/// Connection.m_WriteList as they have completed the request.
/// </summary>
private sealed class HttpWebRequestArrayList : ArrayListWrapper
{
public HttpWebRequestArrayList(ArrayList list) : base(list)
{
}
public override int Add(object value)
{
HttpWebRequest request = value as HttpWebRequest;
if (request != null)
{
s_instance.RaiseRequestEvent(request);
}
return base.Add(value);
}
public override void RemoveAt(int index)
{
HttpWebRequest request = base[index] as HttpWebRequest;
if (request != null)
{
HttpWebResponse response = s_httpResponseAccessor(request);
if (response != null)
{
s_instance.RaiseResponseEvent(request, response);
}
else
{
// In case reponse content length is 0 and request is async,
// we won't have a HttpWebResponse set on request object when this method is called
// http://referencesource.microsoft.com/#System/net/System/Net/HttpWebResponse.cs,525
// But we there will be CoreResponseData object that is either exception
// or the internal HTTP reponse representation having status, content and headers
var coreResponse = s_coreResponseAccessor(request);
if (coreResponse != null && s_coreResponseDataType.IsInstanceOfType(coreResponse))
{
HttpStatusCode status = s_coreStatusCodeAccessor(coreResponse);
WebHeaderCollection headers = s_coreHeadersAccessor(coreResponse);
// Manual creation of HttpWebResponse here is not possible as this method is eventually called from the
// HttpWebResponse ctor. So we will send Stop event with the Status and Headers payload
// to notify listeners about response;
// We use two different names for Stop events since one event with payload type that varies creates
// complications for efficient payload parsing and is not supported by DiagnosicSource helper
// libraries (e.g. Microsoft.Extensions.DiagnosticAdapter)
s_instance.RaiseResponseEvent(request, status, headers);
}
}
}
base.RemoveAt(index);
}
}
#endregion
#region private methods
/// <summary>
/// Private constructor. This class implements a singleton pattern and only this class is allowed to create an instance.
/// </summary>
private HttpHandlerDiagnosticListener() : base(DiagnosticListenerName)
{
}
private void RaiseRequestEvent(HttpWebRequest request)
{
if (request.Headers.Get(RequestIdHeaderName) != null)
{
// this request was instrumented by previous RaiseRequestEvent
return;
}
if (this.IsEnabled(ActivityName, request))
{
var activity = new Activity(ActivityName);
// Only send start event to users who subscribed for it, but start activity anyway
if (this.IsEnabled(RequestStartName))
{
this.StartActivity(activity, new { Request = request });
}
else
{
activity.Start();
}
request.Headers.Add(RequestIdHeaderName, activity.Id);
// we expect baggage to be empty or contain a few items
using (IEnumerator<KeyValuePair<string, string>> e = activity.Baggage.GetEnumerator())
{
if (e.MoveNext())
{
StringBuilder baggage = new StringBuilder();
do
{
KeyValuePair<string, string> item = e.Current;
baggage.Append(item.Key).Append('=').Append(item.Value).Append(',');
}
while (e.MoveNext());
baggage.Remove(baggage.Length - 1, 1);
request.Headers.Add(CorrelationContextHeaderName, baggage.ToString());
}
}
// There is no gurantee that Activity.Current will flow to the Response, so let's stop it here
activity.Stop();
}
}
private void RaiseResponseEvent(HttpWebRequest request, HttpWebResponse response)
{
// Response event could be received several times for the same request in case it was redirected
// IsLastResponse checks if response is the last one (no more redirects will happen)
// based on response StatusCode and number or redirects done so far
if (request.Headers[RequestIdHeaderName] != null && IsLastResponse(request, response.StatusCode))
{
// only send Stop if request was instrumented
this.Write(RequestStopName, new { Request = request, Response = response });
}
}
private void RaiseResponseEvent(HttpWebRequest request, HttpStatusCode statusCode, WebHeaderCollection headers)
{
// Response event could be received several times for the same request in case it was redirected
// IsLastResponse checks if response is the last one (no more redirects will happen)
// based on response StatusCode and number or redirects done so far
if (request.Headers[RequestIdHeaderName] != null && IsLastResponse(request, statusCode))
{
this.Write(RequestStopExName, new { Request = request, StatusCode = statusCode, Headers = headers });
}
}
private bool IsLastResponse(HttpWebRequest request, HttpStatusCode statusCode)
{
if (request.AllowAutoRedirect)
{
if (statusCode == HttpStatusCode.Ambiguous || // 300
statusCode == HttpStatusCode.Moved || // 301
statusCode == HttpStatusCode.Redirect || // 302
statusCode == HttpStatusCode.RedirectMethod || // 303
statusCode == HttpStatusCode.RedirectKeepVerb) // 307
{
return s_autoRedirectsAccessor(request) >= request.MaximumAutomaticRedirections;
}
}
return true;
}
private static void PrepareReflectionObjects()
{
// At any point, if the operation failed, it should just throw. The caller should catch all exceptions and swallow.
// First step: Get all the reflection objects we will ever need.
Assembly systemNetHttpAssembly = typeof(ServicePoint).Assembly;
s_connectionGroupListField = typeof(ServicePoint).GetField("m_ConnectionGroupList", BindingFlags.Instance | BindingFlags.NonPublic);
s_connectionGroupType = systemNetHttpAssembly?.GetType("System.Net.ConnectionGroup");
s_connectionListField = s_connectionGroupType?.GetField("m_ConnectionList", BindingFlags.Instance | BindingFlags.NonPublic);
s_connectionType = systemNetHttpAssembly?.GetType("System.Net.Connection");
s_writeListField = s_connectionType?.GetField("m_WriteList", BindingFlags.Instance | BindingFlags.NonPublic);
s_httpResponseAccessor = CreateFieldGetter<HttpWebRequest, HttpWebResponse>("_HttpResponse", BindingFlags.NonPublic | BindingFlags.Instance);
s_autoRedirectsAccessor = CreateFieldGetter<HttpWebRequest, int>("_AutoRedirects", BindingFlags.NonPublic | BindingFlags.Instance);
s_coreResponseAccessor = CreateFieldGetter<HttpWebRequest, object>("_CoreResponse", BindingFlags.NonPublic | BindingFlags.Instance);
s_coreResponseDataType = systemNetHttpAssembly?.GetType("System.Net.CoreResponseData");
if (s_coreResponseDataType != null)
{
s_coreStatusCodeAccessor = CreateFieldGetter<HttpStatusCode>(s_coreResponseDataType, "m_StatusCode", BindingFlags.Public | BindingFlags.Instance);
s_coreHeadersAccessor = CreateFieldGetter<WebHeaderCollection>(s_coreResponseDataType, "m_ResponseHeaders", BindingFlags.Public | BindingFlags.Instance);
}
// Double checking to make sure we have all the pieces initialized
if (s_connectionGroupListField == null ||
s_connectionGroupType == null ||
s_connectionListField == null ||
s_connectionType == null ||
s_writeListField == null ||
s_httpResponseAccessor == null ||
s_autoRedirectsAccessor == null ||
s_coreResponseDataType == null ||
s_coreStatusCodeAccessor == null ||
s_coreHeadersAccessor == null)
{
// If anything went wrong here, just return false. There is nothing we can do.
throw new InvalidOperationException("Unable to initialize all required reflection objects");
}
}
private static void PerformInjection()
{
FieldInfo servicePointTableField = typeof(ServicePointManager).GetField("s_ServicePointTable", BindingFlags.Static | BindingFlags.NonPublic);
if (servicePointTableField == null)
{
// If anything went wrong here, just return false. There is nothing we can do.
throw new InvalidOperationException("Unable to access the ServicePointTable field");
}
Hashtable originalTable = servicePointTableField.GetValue(null) as Hashtable;
ServicePointHashtable newTable = new ServicePointHashtable(originalTable ?? new Hashtable());
servicePointTableField.SetValue(null, newTable);
}
private static Func<TClass, TField> CreateFieldGetter<TClass, TField>(string fieldName, BindingFlags flags) where TClass : class
{
FieldInfo field = typeof(TClass).GetField(fieldName, flags);
if (field != null)
{
string methodName = field.ReflectedType.FullName + ".get_" + field.Name;
DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new [] { typeof(TClass) }, true);
ILGenerator generator = getterMethod.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldfld, field);
generator.Emit(OpCodes.Ret);
return (Func<TClass, TField>)getterMethod.CreateDelegate(typeof(Func<TClass, TField>));
}
return null;
}
/// <summary>
/// Creates getter for a field defined in private or internal type
/// repesented with classType variable
/// </summary>
private static Func<object, TField> CreateFieldGetter<TField>(Type classType, string fieldName, BindingFlags flags)
{
FieldInfo field = classType.GetField(fieldName, flags);
if (field != null)
{
string methodName = classType.FullName + ".get_" + field.Name;
DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new [] { typeof(object) }, true);
ILGenerator generator = getterMethod.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, classType);
generator.Emit(OpCodes.Ldfld, field);
generator.Emit(OpCodes.Ret);
return (Func<object, TField>)getterMethod.CreateDelegate(typeof(Func<object, TField>));
}
return null;
}
#endregion
internal static HttpHandlerDiagnosticListener s_instance = new HttpHandlerDiagnosticListener();
#region private fields
private const string DiagnosticListenerName = "System.Net.Http.Desktop";
private const string ActivityName = "System.Net.Http.Desktop.HttpRequestOut";
private const string RequestStartName = "System.Net.Http.Desktop.HttpRequestOut.Start";
private const string RequestStopName = "System.Net.Http.Desktop.HttpRequestOut.Stop";
private const string RequestStopExName = "System.Net.Http.Desktop.HttpRequestOut.Ex.Stop";
private const string InitializationFailed = "System.Net.Http.InitializationFailed";
private const string RequestIdHeaderName = "Request-Id";
private const string CorrelationContextHeaderName = "Correlation-Context";
// Fields for controlling initialization of the HttpHandlerDiagnosticListener singleton
private bool initialized = false;
// Fields for reflection
private static FieldInfo s_connectionGroupListField;
private static Type s_connectionGroupType;
private static FieldInfo s_connectionListField;
private static Type s_connectionType;
private static FieldInfo s_writeListField;
private static Func<HttpWebRequest, HttpWebResponse> s_httpResponseAccessor;
private static Func<HttpWebRequest, int> s_autoRedirectsAccessor;
private static Func<HttpWebRequest, object> s_coreResponseAccessor;
private static Func<object, HttpStatusCode> s_coreStatusCodeAccessor;
private static Func<object, WebHeaderCollection> s_coreHeadersAccessor;
private static Type s_coreResponseDataType;
#endregion
}
}
| |
using Orleans.Serialization.Invocation;
using Orleans.Serialization.UnitTests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public interface IHasNoNamespace : IMyInvokableBaseType
{
}
namespace Orleans.Serialization.UnitTests
{
[DefaultInvokableBaseType(typeof(ValueTask<>), typeof(UnitTestRequest<>))]
[DefaultInvokableBaseType(typeof(ValueTask), typeof(UnitTestRequest))]
[DefaultInvokableBaseType(typeof(Task<>), typeof(UnitTestTaskRequest<>))]
[DefaultInvokableBaseType(typeof(Task), typeof(UnitTestTaskRequest))]
[DefaultInvokableBaseType(typeof(void), typeof(UnitTestVoidRequest))]
public abstract class MyInvokableProxyBase
{
protected void SendRequest(IResponseCompletionSource callback, IInvokable body)
{
}
protected TInvokable GetInvokable<TInvokable>() where TInvokable : class, IInvokable, new() => InvokablePool.Get<TInvokable>();
protected ValueTask<T> InvokeAsync<T>(IInvokable body) => default;
protected ValueTask InvokeAsync(IInvokable body) => default;
}
[DefaultInvokableBaseType(typeof(ValueTask<>), typeof(UnitTestRequest<>))]
[DefaultInvokableBaseType(typeof(ValueTask), typeof(UnitTestRequest))]
[DefaultInvokableBaseType(typeof(Task<>), typeof(UnitTestTaskRequest<>))]
[DefaultInvokableBaseType(typeof(Task), typeof(UnitTestTaskRequest))]
[DefaultInvokableBaseType(typeof(void), typeof(UnitTestVoidRequest))]
public abstract class AltInvokableProxyBase
{
protected void InvokeVoid(IInvokable body)
{
}
protected TInvokable GetInvokable<TInvokable>() where TInvokable : class, IInvokable, new() => InvokablePool.Get<TInvokable>();
protected ValueTask<T> InvokeAsync<T>(IInvokable body) => default;
protected ValueTask InvokeAsync(IInvokable body) => default;
}
[GenerateMethodSerializers(typeof(MyInvokableProxyBase))]
public interface IMyInvokableBaseType { }
public interface IG2<T1, T2> : IMyInvokableBaseType
{ }
public class HalfOpenGrain1<T> : IG2<T, int>
{ }
public class HalfOpenGrain2<T> : IG2<int, T>
{ }
public class OpenGeneric<T2, T1> : IG2<T2, T1>
{ }
public class ClosedGeneric : IG2<Dummy1, Dummy2>
{ }
public class ClosedGenericWithManyInterfaces : IG2<Dummy1, Dummy2>, IG2<Dummy2, Dummy1>
{ }
public class Dummy1 { }
public class Dummy2 { }
public interface IG<T> : IMyInvokableBaseType
{
}
public class G1<T1, T2, T3, T4> : Root<T1>.IA<T2, T3, T4>
{
}
public class Root<TRoot>
{
public interface IA<T1, T2, T3> : IMyInvokableBaseType
{
}
public class G<T1, T2, T3> : IG<IA<T1, T2, T3>>
{
}
}
public interface IGrainWithGenericMethods : IMyInvokableBaseType
{
Task<Type[]> GetTypesExplicit<T, U, V>();
Task<Type[]> GetTypesInferred<T, U, V>(T t, U u, V v);
Task<Type[]> GetTypesInferred<T, U>(T t, U u, int v);
Task<T> RoundTrip<T>(T val);
Task<int> RoundTrip(int val);
Task<T> Default<T>();
Task<string> Default();
Task<TGrain> Constraints<TGrain>(TGrain grain) where TGrain : IMyInvokableBaseType;
ValueTask<int> ValueTaskMethod(bool useCache);
}
public class GrainWithGenericMethods : IGrainWithGenericMethods
{
private object state;
public Task<Type[]> GetTypesExplicit<T, U, V>()
{
return Task.FromResult(new[] {typeof(T), typeof(U), typeof(V)});
}
public Task<Type[]> GetTypesInferred<T, U, V>(T t, U u, V v)
{
return Task.FromResult(new[] { typeof(T), typeof(U), typeof(V) });
}
public Task<Type[]> GetTypesInferred<T, U>(T t, U u, int v)
{
return Task.FromResult(new[] { typeof(T), typeof(U) });
}
public Task<T> RoundTrip<T>(T val)
{
return Task.FromResult(val);
}
public Task<int> RoundTrip(int val)
{
return Task.FromResult(-val);
}
public Task<T> Default<T>()
{
return Task.FromResult(default(T));
}
public Task<string> Default()
{
return Task.FromResult("default string");
}
public Task<TGrain> Constraints<TGrain>(TGrain grain) where TGrain : IMyInvokableBaseType
{
return Task.FromResult(grain);
}
public void SetValue<T>(T value)
{
this.state = value;
}
public Task<T> GetValue<T>() => Task.FromResult((T) this.state);
public ValueTask<int> ValueTaskMethod(bool useCache)
{
if (useCache)
{
return new ValueTask<int>(1);
}
return new ValueTask<int>(Task.FromResult(2));
}
}
public interface IGenericGrainWithGenericMethods<T> : IMyInvokableBaseType
{
Task<T> Method(T value);
#pragma warning disable 693
Task<T> Method<T>(T value);
#pragma warning restore 693
}
public interface IRuntimeCodeGenGrain<T> : IMyInvokableBaseType
{
/// <summary>
/// Sets and returns the grain's state.
/// </summary>
/// <param name="value">The new state.</param>
/// <returns>The current state.</returns>
Task<T> SetState(T value);
/// <summary>
/// Tests that code generation correctly handles methods with reserved keyword identifiers.
/// </summary>
/// <returns>The current state's event.</returns>
Task<@event> @static();
}
[Serializable]
[GenerateSerializer]
public class GenericGrainState<T>
{
[Id(1)]
public T @event { get; set; }
}
/// <summary>
/// A class designed to test that code generation correctly handles reserved keywords.
/// </summary>
[GenerateSerializer]
public class @event : IEquatable<@event>
{
private static readonly IEqualityComparer<@event> EventComparerInstance = new EventEqualityComparer();
public enum @enum
{
@async,
@int,
}
/// <summary>
/// A public field.
/// </summary>
[Id(0)]
public Guid Id;
/// <summary>
/// A private field.
/// </summary>
[Id(1)]
private Guid privateId;
/// <summary>
/// A property with a reserved keyword type and identifier.
/// </summary>
[Id(2)]
public @event @public { get; set; }
/// <summary>
/// Gets or sets the enum.
/// </summary>
[Id(3)]
public @enum Enum { get; set; }
/// <summary>
/// A property with a reserved keyword generic type and identifier.
/// </summary>
[Id(4)]
public List<@event> @if { get; set; }
public static IEqualityComparer<@event> EventComparer
{
get
{
return EventComparerInstance;
}
}
/// <summary>
/// Gets or sets the private id.
/// </summary>
// ReSharper disable once ConvertToAutoProperty
public Guid PrivateId
{
get
{
return this.privateId;
}
set
{
this.privateId = value;
}
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return this.Equals((@event)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (this.@if != null ? [email protected]() : 0);
hashCode = (hashCode * 397) ^ (this.@public != null ? [email protected]() : 0);
hashCode = (hashCode * 397) ^ this.privateId.GetHashCode();
hashCode = (hashCode * 397) ^ this.Id.GetHashCode();
return hashCode;
}
}
public bool Equals(@event other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (this.@if != other.@if)
{
if (this.@if != null && [email protected](other.@if, EventComparer))
{
return false;
}
}
if (!Equals(this.@public, other.@public))
{
if (this.@public != null && [email protected](other.@public))
{
return false;
}
}
return this.privateId.Equals(other.privateId) && this.Id.Equals(other.Id) && this.Enum == other.Enum;
}
private sealed class EventEqualityComparer : IEqualityComparer<@event>
{
public bool Equals(@event x, @event y)
{
return x.Equals(y);
}
public int GetHashCode(@event obj)
{
return obj.GetHashCode();
}
}
}
[GenerateSerializer]
public class NestedGeneric<T>
{
[Id(0)]
public Nested Payload { get; set; }
[GenerateSerializer]
public class Nested
{
[Id(0)]
public T Value { get; set; }
}
}
[GenerateSerializer]
public class NestedConstructedGeneric
{
[Id(0)]
public Nested<int> Payload { get; set; }
[GenerateSerializer]
public class Nested<T>
{
[Id(0)]
public T Value { get; set; }
}
}
public interface INestedGenericGrain : IMyInvokableBaseType
{
Task<int> Do(NestedGeneric<int> value);
Task<int> Do(NestedConstructedGeneric value);
}
/// <summary>
/// Tests that nested classes do not fail code generation.
/// </summary>
public class NestedGenericGrain : INestedGenericGrain
{
public Task<int> Do(NestedGeneric<int> value)
{
return Task.FromResult(value.Payload.Value);
}
public Task<int> Do(NestedConstructedGeneric value)
{
return Task.FromResult(value.Payload.Value);
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace ToolBelt
{
/// <summary>
/// Equivalent of System.BitConverter, but with either endianness.
/// </summary>
public abstract class EndianBitConverter
{
#region Endianness of this converter
/// <summary>
/// Indicates the byte order ("endianess") in which data is converted using this class.
/// </summary>
/// <remarks>
/// Different computer architectures store data using different byte orders. "Big-endian"
/// means the most significant byte is on the left end of a word. "Little-endian" means the
/// most significant byte is on the right end of a word.
/// </remarks>
/// <returns>true if this converter is little-endian, false otherwise.</returns>
public abstract bool IsLittleEndian();
/// <summary>
/// Indicates the byte order ("endianess") in which data is converted using this class.
/// </summary>
public abstract Endianness Endianness { get; }
#endregion
#region Factory properties
static LittleEndianBitConverter little = new LittleEndianBitConverter();
/// <summary>
/// Returns a little-endian bit converter instance. The same instance is
/// always returned.
/// </summary>
public static LittleEndianBitConverter Little
{
get { return little; }
}
static BigEndianBitConverter big = new BigEndianBitConverter();
/// <summary>
/// Returns a big-endian bit converter instance. The same instance is
/// always returned.
/// </summary>
public static BigEndianBitConverter Big
{
get { return big; }
}
#endregion
#region Double/primitive conversions
/// <summary>
/// Converts the specified double-precision floating point number to a
/// 64-bit signed integer. Note: the endianness of this converter does not
/// affect the returned value.
/// </summary>
/// <param name="value">The number to convert. </param>
/// <returns>A 64-bit signed integer whose value is equivalent to value.</returns>
public long DoubleToInt64Bits(double value)
{
return BitConverter.DoubleToInt64Bits(value);
}
/// <summary>
/// Converts the specified 64-bit signed integer to a double-precision
/// floating point number. Note: the endianness of this converter does not
/// affect the returned value.
/// </summary>
/// <param name="value">The number to convert. </param>
/// <returns>A double-precision floating point number whose value is equivalent to value.</returns>
public double Int64BitsToDouble(long value)
{
return BitConverter.Int64BitsToDouble(value);
}
/// <summary>
/// Converts the specified single-precision floating point number to a
/// 32-bit signed integer. Note: the endianness of this converter does not
/// affect the returned value.
/// </summary>
/// <param name="value">The number to convert. </param>
/// <returns>A 32-bit signed integer whose value is equivalent to value.</returns>
public int SingleToInt32Bits(float value)
{
return new Int32SingleUnion(value).AsInt32;
}
/// <summary>
/// Converts the specified 32-bit signed integer to a single-precision floating point
/// number. Note: the endianness of this converter does not
/// affect the returned value.
/// </summary>
/// <param name="value">The number to convert. </param>
/// <returns>A single-precision floating point number whose value is equivalent to value.</returns>
public float Int32BitsToSingle(int value)
{
return new Int32SingleUnion(value).AsSingle;
}
#endregion
#region To(PrimitiveType) conversions
/// <summary>
/// Returns a Boolean value converted from one byte at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>true if the byte at startIndex in value is nonzero; otherwise, false.</returns>
public bool ToBoolean(byte[] value, int startIndex)
{
CheckByteArgument(value, startIndex, 1);
return BitConverter.ToBoolean(value, startIndex);
}
/// <summary>
/// Returns a Unicode character converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A character formed by two bytes beginning at startIndex.</returns>
public char ToChar(byte[] value, int startIndex)
{
return unchecked((char)(CheckedFromBytes(value, startIndex, 2)));
}
/// <summary>
/// Returns a double-precision floating point number converted from eight bytes
/// at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A double precision floating point number formed by eight bytes beginning at startIndex.</returns>
public double ToDouble(byte[] value, int startIndex)
{
return Int64BitsToDouble(ToInt64(value, startIndex));
}
/// <summary>
/// Returns a single-precision floating point number converted from four bytes
/// at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A single precision floating point number formed by four bytes beginning at startIndex.</returns>
public float ToSingle(byte[] value, int startIndex)
{
return Int32BitsToSingle(ToInt32(value, startIndex));
}
/// <summary>
/// Returns a 16-bit signed integer converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 16-bit signed integer formed by two bytes beginning at startIndex.</returns>
public short ToInt16(byte[] value, int startIndex)
{
return unchecked((short)(CheckedFromBytes(value, startIndex, 2)));
}
/// <summary>
/// Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 32-bit signed integer formed by four bytes beginning at startIndex.</returns>
public int ToInt32(byte[] value, int startIndex)
{
return unchecked((int)(CheckedFromBytes(value, startIndex, 4)));
}
/// <summary>
/// Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 64-bit signed integer formed by eight bytes beginning at startIndex.</returns>
public long ToInt64(byte[] value, int startIndex)
{
return CheckedFromBytes(value, startIndex, 8);
}
/// <summary>
/// Returns a 16-bit unsigned integer converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 16-bit unsigned integer formed by two bytes beginning at startIndex.</returns>
public ushort ToUInt16(byte[] value, int startIndex)
{
return unchecked((ushort)(CheckedFromBytes(value, startIndex, 2)));
}
/// <summary>
/// Returns a 32-bit unsigned integer converted from four bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 32-bit unsigned integer formed by four bytes beginning at startIndex.</returns>
public uint ToUInt32(byte[] value, int startIndex)
{
return unchecked((uint)(CheckedFromBytes(value, startIndex, 4)));
}
/// <summary>
/// Returns a 64-bit unsigned integer converted from eight bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 64-bit unsigned integer formed by eight bytes beginning at startIndex.</returns>
public ulong ToUInt64(byte[] value, int startIndex)
{
return unchecked((ulong)(CheckedFromBytes(value, startIndex, 8)));
}
/// <summary>
/// Checks the given argument for validity.
/// </summary>
/// <param name="value">The byte array passed in</param>
/// <param name="startIndex">The start index passed in</param>
/// <param name="bytesRequired">The number of bytes required</param>
/// <exception cref="ArgumentNullException">value is a null reference</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// startIndex is less than zero or greater than the length of value minus bytesRequired.
/// </exception>
static void CheckByteArgument(byte[] value, int startIndex, int bytesRequired)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (startIndex < 0 || startIndex > value.Length - bytesRequired)
{
throw new ArgumentOutOfRangeException("startIndex");
}
}
/// <summary>
/// Checks the arguments for validity before calling FromBytes
/// (which can therefore assume the arguments are valid).
/// </summary>
/// <param name="value">The bytes to convert after checking</param>
/// <param name="startIndex">The index of the first byte to convert</param>
/// <param name="bytesToConvert">The number of bytes to convert</param>
/// <returns></returns>
long CheckedFromBytes(byte[] value, int startIndex, int bytesToConvert)
{
CheckByteArgument(value, startIndex, bytesToConvert);
return FromBytes(value, startIndex, bytesToConvert);
}
/// <summary>
/// Convert the given number of bytes from the given array, from the given start
/// position, into a long, using the bytes as the least significant part of the long.
/// By the time this is called, the arguments have been checked for validity.
/// </summary>
/// <param name="value">The bytes to convert</param>
/// <param name="startIndex">The index of the first byte to convert</param>
/// <param name="bytesToConvert">The number of bytes to use in the conversion</param>
/// <returns>The converted number</returns>
protected abstract long FromBytes(byte[] value, int startIndex, int bytesToConvert);
#endregion
#region ToString conversions
/// <summary>
/// Returns a String converted from the elements of a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <remarks>All the elements of value are converted.</remarks>
/// <returns>
/// A String of hexadecimal pairs separated by hyphens, where each pair
/// represents the corresponding element in value; for example, "7F-2C-4A".
/// </returns>
public static string ToString(byte[] value)
{
return BitConverter.ToString(value);
}
/// <summary>
/// Returns a String converted from the elements of a byte array starting at a specified array position.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <remarks>The elements from array position startIndex to the end of the array are converted.</remarks>
/// <returns>
/// A String of hexadecimal pairs separated by hyphens, where each pair
/// represents the corresponding element in value; for example, "7F-2C-4A".
/// </returns>
public static string ToString(byte[] value, int startIndex)
{
return BitConverter.ToString(value, startIndex);
}
/// <summary>
/// Returns a String converted from a specified number of bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <param name="length">The number of bytes to convert.</param>
/// <remarks>The length elements from array position startIndex are converted.</remarks>
/// <returns>
/// A String of hexadecimal pairs separated by hyphens, where each pair
/// represents the corresponding element in value; for example, "7F-2C-4A".
/// </returns>
public static string ToString(byte[] value, int startIndex, int length)
{
return BitConverter.ToString(value, startIndex, length);
}
#endregion
#region Decimal conversions
/// <summary>
/// Returns a decimal value converted from sixteen bytes
/// at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A decimal formed by sixteen bytes beginning at startIndex.</returns>
public decimal ToDecimal(byte[] value, int startIndex)
{
int[] parts = new int[4];
for (int i = 0; i < 4; i++)
{
parts[i] = ToInt32(value, startIndex + i * 4);
}
return new Decimal(parts);
}
/// <summary>
/// Returns the specified decimal value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 16.</returns>
public byte[] GetBytes(decimal value)
{
byte[] bytes = new byte[16];
int[] parts = decimal.GetBits(value);
for (int i = 0; i < 4; i++)
{
CopyBytesImpl(parts[i], 4, bytes, i * 4);
}
return bytes;
}
/// <summary>
/// Copies the specified decimal value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">A character to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(decimal value, byte[] buffer, int index)
{
int[] parts = decimal.GetBits(value);
for (int i = 0; i < 4; i++)
{
CopyBytesImpl(parts[i], 4, buffer, i * 4 + index);
}
}
#endregion
#region GetBytes conversions
/// <summary>
/// Returns an array with the given number of bytes formed
/// from the least significant bytes of the specified value.
/// This is used to implement the other GetBytes methods.
/// </summary>
/// <param name="value">The value to get bytes for</param>
/// <param name="bytes">The number of significant bytes to return</param>
byte[] GetBytes(long value, int bytes)
{
byte[] buffer = new byte[bytes];
CopyBytes(value, bytes, buffer, 0);
return buffer;
}
/// <summary>
/// Returns the specified Boolean value as an array of bytes.
/// </summary>
/// <param name="value">A Boolean value.</param>
/// <returns>An array of bytes with length 1.</returns>
public byte[] GetBytes(bool value)
{
return BitConverter.GetBytes(value);
}
/// <summary>
/// Returns the specified Unicode character value as an array of bytes.
/// </summary>
/// <param name="value">A character to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
public byte[] GetBytes(char value)
{
return GetBytes(value, 2);
}
/// <summary>
/// Returns the specified double-precision floating point value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
public byte[] GetBytes(double value)
{
return GetBytes(DoubleToInt64Bits(value), 8);
}
/// <summary>
/// Returns the specified 16-bit signed integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
public byte[] GetBytes(short value)
{
return GetBytes(value, 2);
}
/// <summary>
/// Returns the specified 32-bit signed integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
public byte[] GetBytes(int value)
{
return GetBytes(value, 4);
}
/// <summary>
/// Returns the specified 64-bit signed integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
public byte[] GetBytes(long value)
{
return GetBytes(value, 8);
}
/// <summary>
/// Returns the specified single-precision floating point value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
public byte[] GetBytes(float value)
{
return GetBytes(SingleToInt32Bits(value), 4);
}
/// <summary>
/// Returns the specified 16-bit unsigned integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
public byte[] GetBytes(ushort value)
{
return GetBytes(value, 2);
}
/// <summary>
/// Returns the specified 32-bit unsigned integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
public byte[] GetBytes(uint value)
{
return GetBytes(value, 4);
}
/// <summary>
/// Returns the specified 64-bit unsigned integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
public byte[] GetBytes(ulong value)
{
return GetBytes(unchecked((long)value), 8);
}
#endregion
#region CopyBytes conversions
/// <summary>
/// Copies the given number of bytes from the least-specific
/// end of the specified value into the specified byte array, beginning
/// at the specified index.
/// This is used to implement the other CopyBytes methods.
/// </summary>
/// <param name="value">The value to copy bytes for</param>
/// <param name="bytes">The number of significant bytes to copy</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
void CopyBytes(long value, int bytes, byte[] buffer, int index)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", "Byte array must not be null");
}
if (buffer.Length < index + bytes)
{
throw new ArgumentOutOfRangeException("Buffer not big enough for value");
}
CopyBytesImpl(value, bytes, buffer, index);
}
/// <summary>
/// Copies the given number of bytes from the least-specific
/// end of the specified value into the specified byte array, beginning
/// at the specified index.
/// This must be implemented in concrete derived classes, but the implementation
/// may assume that the value will fit into the buffer.
/// </summary>
/// <param name="value">The value to copy bytes for</param>
/// <param name="bytes">The number of significant bytes to copy</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
protected abstract void CopyBytesImpl(long value, int bytes, byte[] buffer, int index);
/// <summary>
/// Copies the specified Boolean value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">A Boolean value.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(bool value, byte[] buffer, int index)
{
CopyBytes(value ? 1 : 0, 1, buffer, index);
}
/// <summary>
/// Copies the specified Unicode character value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">A character to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(char value, byte[] buffer, int index)
{
CopyBytes(value, 2, buffer, index);
}
/// <summary>
/// Copies the specified double-precision floating point value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(double value, byte[] buffer, int index)
{
CopyBytes(DoubleToInt64Bits(value), 8, buffer, index);
}
/// <summary>
/// Copies the specified 16-bit signed integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(short value, byte[] buffer, int index)
{
CopyBytes(value, 2, buffer, index);
}
/// <summary>
/// Copies the specified 32-bit signed integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(int value, byte[] buffer, int index)
{
CopyBytes(value, 4, buffer, index);
}
/// <summary>
/// Copies the specified 64-bit signed integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(long value, byte[] buffer, int index)
{
CopyBytes(value, 8, buffer, index);
}
/// <summary>
/// Copies the specified single-precision floating point value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(float value, byte[] buffer, int index)
{
CopyBytes(SingleToInt32Bits(value), 4, buffer, index);
}
/// <summary>
/// Copies the specified 16-bit unsigned integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(ushort value, byte[] buffer, int index)
{
CopyBytes(value, 2, buffer, index);
}
/// <summary>
/// Copies the specified 32-bit unsigned integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(uint value, byte[] buffer, int index)
{
CopyBytes(value, 4, buffer, index);
}
/// <summary>
/// Copies the specified 64-bit unsigned integer value into the specified byte array,
/// beginning at the specified index.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <param name="buffer">The byte array to copy the bytes into</param>
/// <param name="index">The first index into the array to copy the bytes into</param>
public void CopyBytes(ulong value, byte[] buffer, int index)
{
CopyBytes(unchecked((long)value), 8, buffer, index);
}
#endregion
#region Private struct used for Single/Int32 conversions
/// <summary>
/// Union used solely for the equivalent of DoubleToInt64Bits and vice versa.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
struct Int32SingleUnion
{
/// <summary>
/// Int32 version of the value.
/// </summary>
[FieldOffset(0)]
int i;
/// <summary>
/// Single version of the value.
/// </summary>
[FieldOffset(0)]
float f;
/// <summary>
/// Creates an instance representing the given integer.
/// </summary>
/// <param name="i">The integer value of the new instance.</param>
internal Int32SingleUnion(int i)
{
this.f = 0; // Just to keep the compiler happy
this.i = i;
}
/// <summary>
/// Creates an instance representing the given floating point number.
/// </summary>
/// <param name="f">The floating point value of the new instance.</param>
internal Int32SingleUnion(float f)
{
this.i = 0; // Just to keep the compiler happy
this.f = f;
}
/// <summary>
/// Returns the value of the instance as an integer.
/// </summary>
internal int AsInt32
{
get { return i; }
}
/// <summary>
/// Returns the value of the instance as a floating point number.
/// </summary>
internal float AsSingle
{
get { return f; }
}
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Elasticsearch.Net.Connection.Thrift.Protocol;
using Elasticsearch.Net.Connection.Thrift.Transport;
using Elasticsearch.Net.Providers;
namespace Elasticsearch.Net.Connection.Thrift
{
public class ThriftConnection : IConnection, IDisposable
{
private readonly ConcurrentQueue<Rest.Client> _clients = new ConcurrentQueue<Rest.Client>();
private readonly Semaphore _resourceLock;
private readonly int _timeout;
private readonly int _poolSize;
private bool _disposed;
private readonly IConnectionConfigurationValues _connectionSettings;
public ThriftConnection(IConnectionConfigurationValues connectionSettings)
{
this._connectionSettings = connectionSettings;
this._timeout = connectionSettings.Timeout;
this._poolSize = Math.Max(1, connectionSettings.MaximumAsyncConnections);
this._resourceLock = new Semaphore(_poolSize, _poolSize);
int seed; bool shouldPingHint;
for (var i = 0; i <= connectionSettings.MaximumAsyncConnections; i++)
{
var uri = this._connectionSettings.ConnectionPool.GetNext(null, out seed, out shouldPingHint);
var host = uri.Host;
var port = uri.Port;
var tsocket = new TSocket(host, port);
var transport = new TBufferedTransport(tsocket, 1024);
var protocol = new TBinaryProtocol(transport);
var client = new Rest.Client(protocol);
_clients.Enqueue(client);
}
}
#region IConnection Members
public Task<ElasticsearchResponse<Stream>> Get(Uri uri, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.GET;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, deserializationState);
});
}
public Task<ElasticsearchResponse<Stream>> Head(Uri uri, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.HEAD;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(()=>
{
return this.Execute(restRequest, deserializationState);
});
}
public ElasticsearchResponse<Stream> GetSync(Uri uri, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.GET;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, deserializationState);
}
public ElasticsearchResponse<Stream> HeadSync(Uri uri, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.HEAD;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, deserializationState);
}
public Task<ElasticsearchResponse<Stream>> Post(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.POST;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, deserializationState);
});
}
public Task<ElasticsearchResponse<Stream>> Put(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.PUT;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, deserializationState);
});
}
public Task<ElasticsearchResponse<Stream>> Delete(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.DELETE;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, deserializationState);
});
}
public ElasticsearchResponse<Stream> PostSync(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.POST;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, deserializationState);
}
public ElasticsearchResponse<Stream> PutSync(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.PUT;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, deserializationState);
}
public Task<ElasticsearchResponse<Stream>> Delete(Uri uri, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.DELETE;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() =>
{
return this.Execute(restRequest, deserializationState);
});
}
public ElasticsearchResponse<Stream> DeleteSync(Uri uri, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.DELETE;
restRequest.Uri = uri;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, deserializationState);
}
public ElasticsearchResponse<Stream> DeleteSync(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null)
{
var restRequest = new RestRequest();
restRequest.Method = Method.DELETE;
restRequest.Uri = uri;
restRequest.Body = data;
restRequest.Headers = new Dictionary<string, string>();
restRequest.Headers.Add("Content-Type", "application/json");
return this.Execute(restRequest, deserializationState);
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
#endregion
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
foreach (var c in this._clients)
{
if (c != null
&& c.InputProtocol != null
&& c.InputProtocol.Transport != null
&& c.InputProtocol.Transport.IsOpen)
c.InputProtocol.Transport.Close();
}
_disposed = true;
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="HttpConnection"/> is reclaimed by garbage collection.
/// </summary>
~ThriftConnection()
{
Dispose(false);
}
private ElasticsearchResponse<Stream> Execute(RestRequest restRequest, object deserializationState)
{
//RestResponse result = GetClient().execute(restRequest);
//
var method = Enum.GetName(typeof (Method), restRequest.Method);
var path = restRequest.Uri.ToString();
var requestData = restRequest.Body;
if (!this._resourceLock.WaitOne(this._timeout))
{
var m = "Could not start the thrift operation before the timeout of " + this._timeout + "ms completed while waiting for the semaphore";
return ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, new TimeoutException(m), method, path, requestData);
}
try
{
Rest.Client client = null;
if (!this._clients.TryDequeue(out client))
{
var m = string.Format("Could dequeue a thrift client from internal socket pool of size {0}", this._poolSize);
var status = ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, new Exception(m), method, path, requestData);
return status;
}
try
{
if (!client.InputProtocol.Transport.IsOpen)
client.InputProtocol.Transport.Open();
var result = client.execute(restRequest);
if (result.Status == Status.OK || result.Status == Status.CREATED || result.Status == Status.ACCEPTED)
{
var response = ElasticsearchResponse<Stream>.Create(this._connectionSettings, (int)result.Status, method, path, requestData);
response.Response = new MemoryStream(result.Body);
return response;
}
else
{
var response = ElasticsearchResponse<Stream>.Create(this._connectionSettings, (int)result.Status, method, path, requestData);
response.Response = new MemoryStream(result.Body);
return response;
}
}
finally
{
//make sure we make the client available again.
this._clients.Enqueue(client);
}
}
catch (Exception e)
{
return ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, e, method, path, requestData);
}
finally
{
this._resourceLock.Release();
}
}
public string DecodeStr(byte[] bytes)
{
if (bytes != null && bytes.Length > 0)
{
return Encoding.UTF8.GetString(bytes);
}
return string.Empty;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management.WebSites.Models;
namespace Microsoft.WindowsAzure.Management.WebSites.Models
{
/// <summary>
/// The Get Web Site Historical Usage Metrics operation response.
/// </summary>
public partial class WebSiteGetHistoricalUsageMetricsResponse : OperationResponse, IEnumerable<WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetric>
{
private IList<WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetric> _usageMetrics;
/// <summary>
/// Historical metric snapshots for the web site.
/// </summary>
public IList<WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetric> UsageMetrics
{
get { return this._usageMetrics; }
set { this._usageMetrics = value; }
}
/// <summary>
/// Initializes a new instance of the
/// WebSiteGetHistoricalUsageMetricsResponse class.
/// </summary>
public WebSiteGetHistoricalUsageMetricsResponse()
{
this._usageMetrics = new List<WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetric>();
}
/// <summary>
/// Gets the sequence of UsageMetrics.
/// </summary>
public IEnumerator<WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetric> GetEnumerator()
{
return this.UsageMetrics.GetEnumerator();
}
/// <summary>
/// Gets the sequence of UsageMetrics.
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// Historical metric snapshot for the web site.
/// </summary>
public partial class HistoricalUsageMetric
{
private string _code;
/// <summary>
/// Reports whether the metric data was returned successfully.
/// </summary>
public string Code
{
get { return this._code; }
set { this._code = value; }
}
private WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricData _data;
/// <summary>
/// Historical metric snapshot data for the web site.
/// </summary>
public WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricData Data
{
get { return this._data; }
set { this._data = value; }
}
private string _message;
/// <summary>
/// A string for optional message content.
/// </summary>
public string Message
{
get { return this._message; }
set { this._message = value; }
}
/// <summary>
/// Initializes a new instance of the HistoricalUsageMetric class.
/// </summary>
public HistoricalUsageMetric()
{
}
}
/// <summary>
/// Historical metric snapshot data for the web site.
/// </summary>
public partial class HistoricalUsageMetricData
{
private string _displayName;
/// <summary>
/// The display name of the metric, including spaces.
/// </summary>
public string DisplayName
{
get { return this._displayName; }
set { this._displayName = value; }
}
private DateTime _endTime;
/// <summary>
/// The end time of the data reported.
/// </summary>
public DateTime EndTime
{
get { return this._endTime; }
set { this._endTime = value; }
}
private string _name;
/// <summary>
/// The name of the metric.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private string _primaryAggregationType;
/// <summary>
/// The primary data aggregation type. This value is usually Total.
/// </summary>
public string PrimaryAggregationType
{
get { return this._primaryAggregationType; }
set { this._primaryAggregationType = value; }
}
private DateTime _startTime;
/// <summary>
/// The start time of the data reported.
/// </summary>
public DateTime StartTime
{
get { return this._startTime; }
set { this._startTime = value; }
}
private string _timeGrain;
/// <summary>
/// Length of time (rollup) during which the information was
/// gathered. For more information, see Supported Rollups.
/// </summary>
public string TimeGrain
{
get { return this._timeGrain; }
set { this._timeGrain = value; }
}
private string _unit;
/// <summary>
/// The unit of measurement for the metric (for example,
/// milliseconds, bytes, or count).
/// </summary>
public string Unit
{
get { return this._unit; }
set { this._unit = value; }
}
private IList<WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricSample> _values;
/// <summary>
/// One or more MetricSample elements.
/// </summary>
public IList<WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricSample> Values
{
get { return this._values; }
set { this._values = value; }
}
/// <summary>
/// Initializes a new instance of the HistoricalUsageMetricData
/// class.
/// </summary>
public HistoricalUsageMetricData()
{
this._values = new List<WebSiteGetHistoricalUsageMetricsResponse.HistoricalUsageMetricSample>();
}
}
/// <summary>
/// Historical metric snapshot data sample.
/// </summary>
public partial class HistoricalUsageMetricSample
{
private int _count;
/// <summary>
/// The metric sample count. This value is usually 1.
/// </summary>
public int Count
{
get { return this._count; }
set { this._count = value; }
}
private string _maximum;
/// <summary>
/// Maximum value recorded.
/// </summary>
public string Maximum
{
get { return this._maximum; }
set { this._maximum = value; }
}
private string _minimum;
/// <summary>
/// Minimum value recorded.
/// </summary>
public string Minimum
{
get { return this._minimum; }
set { this._minimum = value; }
}
private DateTime _timeCreated;
/// <summary>
/// Time the metric was taken.
/// </summary>
public DateTime TimeCreated
{
get { return this._timeCreated; }
set { this._timeCreated = value; }
}
private string _total;
/// <summary>
/// Value of the metric sample for the time taken.
/// </summary>
public string Total
{
get { return this._total; }
set { this._total = value; }
}
/// <summary>
/// Initializes a new instance of the HistoricalUsageMetricSample
/// class.
/// </summary>
public HistoricalUsageMetricSample()
{
}
}
}
}
| |
// 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.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using AngleSharp.Parser.Html;
using BasicWebSite;
using BasicWebSite.Services;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests
{
public class ComponentRenderingFunctionalTests : IClassFixture<MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting>>
{
public ComponentRenderingFunctionalTests(MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting> fixture)
{
Factory = fixture;
}
public MvcTestFixture<StartupWithoutEndpointRouting> Factory { get; }
[Fact]
public async Task Renders_BasicComponent()
{
// Arrange & Act
var client = CreateClient(Factory);
var response = await client.GetAsync("http://localhost/components");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
AssertComponent("<p>Hello world!</p>", "Greetings", content);
}
[Fact]
public async Task Renders_RoutingComponent()
{
// Arrange & Act
var client = CreateClient(Factory.WithWebHostBuilder(builder => builder.ConfigureServices(services => services.AddServerSideBlazor())));
var response = await client.GetAsync("http://localhost/components/routable");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
AssertComponent("Router component\n<p>Routed successfully</p>", "Routing", content);
}
[Fact]
public async Task Redirects_Navigation_Component()
{
// Arrange & Act
var fixture = Factory.WithWebHostBuilder(builder => builder.ConfigureServices(services => services.AddServerSideBlazor()));
fixture.ClientOptions.AllowAutoRedirect = false;
var client = CreateClient(fixture);
var response = await client.GetAsync("http://localhost/components/Navigation");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.Redirect);
Assert.Equal("http://localhost/navigation-redirect", response.Headers.Location.ToString());
}
[Fact]
public async Task Renders_RoutingComponent_UsingRazorComponents_Prerenderer()
{
// Arrange & Act
var client = CreateClient(Factory
.WithWebHostBuilder(builder => builder.ConfigureServices(services => services.AddServerSideBlazor())));
var response = await client.GetAsync("http://localhost/components/routable");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
AssertComponent("Router component\n<p>Routed successfully</p>", "Routing", content);
}
[Fact]
public async Task Renders_ThrowingComponent_UsingRazorComponents_Prerenderer()
{
// Arrange & Act
var client = CreateClient(Factory.WithWebHostBuilder(builder => builder.ConfigureServices(services => services.AddServerSideBlazor())));
var response = await client.GetAsync("http://localhost/components/throws");
// Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
var content = await response.Content.ReadAsStringAsync();
Assert.Contains("InvalidTimeZoneException: test", content);
}
[Fact]
public async Task Renders_AsyncComponent()
{
// Arrange & Act
var expectedHtml = @"<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
<p>Weather data for 01/15/2019</p>
<table class=""table"">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
<tr>
<td>06/05/2018</td>
<td>1</td>
<td>33</td>
<td>Freezing</td>
</tr>
<tr>
<td>07/05/2018</td>
<td>14</td>
<td>57</td>
<td>Bracing</td>
</tr>
<tr>
<td>08/05/2018</td>
<td>-13</td>
<td>9</td>
<td>Freezing</td>
</tr>
<tr>
<td>09/05/2018</td>
<td>-16</td>
<td>4</td>
<td>Balmy</td>
</tr>
<tr>
<td>10/05/2018</td>
<td>2</td>
<td>29</td>
<td>Chilly</td>
</tr>
</tbody>
</table>
";
var client = CreateClient(Factory);
var response = await client.GetAsync("http://localhost/components");
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
var content = await response.Content.ReadAsStringAsync();
AssertComponent(expectedHtml, "FetchData", content);
}
private void AssertComponent(string expectedContent, string divId, string responseContent)
{
var parser = new HtmlParser();
var htmlDocument = parser.Parse(responseContent);
var div = htmlDocument.Body.QuerySelector($"#{divId}");
var content = div.InnerHtml;
Assert.Equal(
expectedContent.Replace("\r\n","\n"),
content.Replace("\r\n","\n"));
}
// A simple delegating handler used in setting up test services so that we can configure
// services that talk back to the TestServer using HttpClient.
private class LoopHttpHandler : DelegatingHandler
{
}
private HttpClient CreateClient(
WebApplicationFactory<BasicWebSite.StartupWithoutEndpointRouting> fixture)
{
var loopHandler = new LoopHttpHandler();
var client = fixture
.WithWebHostBuilder(builder => builder.ConfigureServices(ConfigureTestWeatherForecastService))
.CreateClient();
// We configure the inner handler with a handler to this TestServer instance so that calls to the
// server can get routed properly.
loopHandler.InnerHandler = fixture.Server.CreateHandler();
void ConfigureTestWeatherForecastService(IServiceCollection services) =>
// We configure the test service here with an HttpClient that uses this loopback handler to talk
// to this TestServer instance.
services.AddSingleton(new WeatherForecastService(new HttpClient(loopHandler)
{
BaseAddress = fixture.ClientOptions.BaseAddress
}));
return client;
}
}
}
| |
using System;
using System.Xml;
using System.Collections;
using System.Drawing;
using GuruComponents.CodeEditor.CodeEditor.Syntax;
using System.IO;
using System.Collections.Specialized;
using System.Text;
namespace GuruComponents.CodeEditor.CodeEditor.Syntax
{
/// <summary>
///
/// </summary>
public class SyntaxLoader
{
private Hashtable mStyles = new Hashtable();
private Hashtable mBlocks = new Hashtable();
private Language mLanguage = new Language();
private static bool _UseUserCustomStyles = false;
//protected BlockType mLanguage.MainBlock=null;
private static string _UserCustomStyles = null;
/// <summary>
/// Directory where is saved language font and color configurations
/// </summary>
public static string UserCustomStyles
{
get { return SyntaxLoader._UserCustomStyles; }
set { SyntaxLoader._UserCustomStyles = value; }
}
/// <summary>
/// Set if user can user custom user styles for the Language
/// </summary>
public static bool UseUserCustomStyles
{
get { return _UseUserCustomStyles; }
set { _UseUserCustomStyles = value; }
}
/// <summary>
/// Load a specific language file
/// </summary>
/// <param name="File">File name</param>
/// <returns>Language object</returns>
public Language Load(string filename)
{
return Load(File.OpenRead(filename));
}
public Language Load(Stream stream)
{
mStyles = new Hashtable();
mBlocks = new Hashtable();
mLanguage = new Language();
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load(stream);
if (_UseUserCustomStyles && Directory.Exists(_UserCustomStyles))
{
string langName = myXmlDocument.SelectSingleNode("Language/@Name").InnerText;
string path = Path.Combine(SyntaxLoader.UserCustomStyles, langName + ".conf");
if (File.Exists(path))
{
XmlDocument userConf = new XmlDocument();
userConf.Load(path);
XmlNodeList xlist = myXmlDocument.SelectNodes("Language/Style");
foreach (XmlNode current in xlist)
{
XmlNode userStyleNode = userConf.SelectSingleNode("styles/Style[@Name='" +
current.Attributes["Name"].InnerText + "']");
if (userStyleNode == null)
continue;
foreach (XmlAttribute userAtt in userStyleNode.Attributes)
{
current.Attributes[userAtt.LocalName].InnerText = userAtt.InnerText;
}
}
}
}
ReadLanguageDef(myXmlDocument);
return mLanguage;
}
/// <summary>
///
/// </summary>
/// <param name="File"></param>
/// <returns></returns>
public Language Load(string File, string Separators)
{
mStyles = new Hashtable();
mBlocks = new Hashtable();
mLanguage = new Language();
mLanguage.Separators = Separators;
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load(File);
ReadLanguageDef(myXmlDocument);
return mLanguage;
}
/// <summary>
/// Load a specific language from an xml string
/// </summary>
/// <param name="XML"></param>
/// <returns></returns>
public Language LoadXML(string XML)
{
mStyles = new Hashtable();
mBlocks = new Hashtable();
mLanguage = new Language();
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.LoadXml(XML);
ReadLanguageDef(myXmlDocument);
return mLanguage;
}
private void ReadLanguageDef(XmlDocument xml)
{
ParseLanguage(xml["Language"]);
}
private void ParseLanguage(XmlNode node)
{
//get language name and startblock
string Name = "";
string StartBlock = "";
foreach (XmlAttribute att in node.Attributes)
{
if (att.Name.ToLower() == "name")
Name = att.Value;
if (att.Name.ToLower() == "startblock")
StartBlock = att.Value;
}
mLanguage.Name = Name;
mLanguage.MainBlock = GetBlock(StartBlock);
foreach (XmlNode n in node.ChildNodes)
{
if (n.NodeType == XmlNodeType.Element)
{
if (n.Name.ToLower() == "filetypes")
ParseFileTypes(n);
if (n.Name.ToLower() == "block")
ParseBlock(n);
if (n.Name.ToLower() == "style")
ParseStyle(n);
}
}
}
private void ParseFileTypes(XmlNode node)
{
foreach (XmlNode n in node.ChildNodes)
{
if (n.NodeType == XmlNodeType.Element)
{
if (n.Name.ToLower() == "filetype")
{
//add filetype
string Extension = "";
string Name = "";
foreach (XmlAttribute a in n.Attributes)
{
if (a.Name.ToLower() == "name")
Name = a.Value;
if (a.Name.ToLower() == "extension")
Extension = a.Value;
}
FileType ft = new FileType();
ft.Extension = Extension;
ft.Name = Name;
mLanguage.FileTypes.Add(ft);
}
}
}
}
private void ParseBlock(XmlNode node)
{
string Name = "", Style = "", PatternStyle = "";
bool IsMultiline = false;
bool TerminateChildren = false;
Color BackColor = Color.Transparent;
foreach (XmlAttribute att in node.Attributes)
{
if (att.Name.ToLower() == "name")
Name = att.Value;
if (att.Name.ToLower() == "style")
Style = att.Value;
if (att.Name.ToLower() == "patternstyle")
PatternStyle = att.Value;
if (att.Name.ToLower() == "ismultiline")
IsMultiline = bool.Parse(att.Value);
if (att.Name.ToLower() == "terminatechildren")
TerminateChildren = bool.Parse(att.Value);
if (att.Name.ToLower() == "backcolor")
{
BackColor = Color.FromName(att.Value);
//Transparent =false;
}
}
//create block object here
BlockType bl = GetBlock(Name);
bl.BackColor = BackColor;
bl.Name = Name;
bl.MultiLine = IsMultiline;
bl.Style = GetStyle(Style);
bl.TerminateChildren = TerminateChildren;
// if (PatternStyle!="")
// bl.PatternStyle = GetStyle(PatternStyle);
// else
// bl.PatternStyle = bl.Style;
foreach (XmlNode n in node.ChildNodes)
{
if (n.NodeType == XmlNodeType.Element)
{
if (n.Name.ToLower() == "scope")
{
//bool IsComplex=false;
//bool IsSeparator=false;
string Start = "";
string End = "";
string style = "";
string text = "";
string EndIsSeparator = "";
string StartIsSeparator = "";
string StartIsComplex = "false";
string EndIsComplex = "false";
string StartIsKeyword = "false";
string EndIsKeyword = "false";
string spawnstart = "";
string spawnend = "";
string EscapeChar = "";
string CauseIndent = "false";
bool expanded = true;
foreach (XmlAttribute att in n.Attributes)
{
if (att.Name.ToLower() == "start")
Start = att.Value;
if (att.Name.ToLower() == "escapechar")
EscapeChar = att.Value;
if (att.Name.ToLower() == "end")
End = att.Value;
if (att.Name.ToLower() == "style")
style = att.Value;
if (att.Name.ToLower() == "text")
text = att.Value;
if (att.Name.ToLower() == "defaultexpanded")
expanded = bool.Parse(att.Value);
if (att.Name.ToLower() == "endisseparator")
EndIsSeparator = att.Value;
if (att.Name.ToLower() == "startisseparator")
StartIsSeparator = att.Value;
if (att.Name.ToLower() == "startiskeyword")
StartIsKeyword = att.Value;
if (att.Name.ToLower() == "startiscomplex")
StartIsComplex = att.Value;
if (att.Name.ToLower() == "endiscomplex")
EndIsComplex = att.Value;
if (att.Name.ToLower() == "endiskeyword")
EndIsKeyword = att.Value;
if (att.Name.ToLower() == "spawnblockonstart")
spawnstart = att.Value;
if (att.Name.ToLower() == "spawnblockonend")
spawnend = att.Value;
if (att.Name.ToLower() == "causeindent")
CauseIndent = att.Value;
}
if (Start != "")
{
//bl.StartPattern =new Pattern (Pattern,IsComplex,false,IsSeparator);
//bl.StartPatterns.Add (new Pattern (Pattern,IsComplex,IsSeparator,true));
Scope scop = new Scope();
scop.Style = GetStyle(style);
scop.ExpansionText = text;
scop.DefaultExpanded = expanded;
bool blnStartIsComplex = bool.Parse(StartIsComplex);
bool blnEndIsComplex = bool.Parse(EndIsComplex);
bool blnCauseIndent = bool.Parse(CauseIndent);
scop.CauseIndent = blnCauseIndent;
Pattern StartP = new Pattern(Start, blnStartIsComplex, false, bool.Parse(StartIsKeyword));
Pattern EndP = null;
if (EscapeChar != "")
{
EndP = new Pattern(End, blnEndIsComplex, false, bool.Parse(EndIsKeyword), EscapeChar);
}
else
{
EndP = new Pattern(End, blnEndIsComplex, false, bool.Parse(EndIsKeyword));
}
if (EndIsSeparator != "")
EndP.IsSeparator = bool.Parse(EndIsSeparator);
scop.Start = StartP;
scop.EndPatterns.Add(EndP);
bl.ScopePatterns.Add(scop);
if (spawnstart != "")
{
scop.SpawnBlockOnStart = GetBlock(spawnstart);
}
if (spawnend != "")
{
scop.SpawnBlockOnEnd = GetBlock(spawnend);
}
}
}
if (n.Name.ToLower() == "bracket")
{
//bool IsComplex=false;
//bool IsSeparator=false;
string Start = "";
string End = "";
string style = "";
string EndIsSeparator = "";
string StartIsSeparator = "";
string StartIsComplex = "false";
string EndIsComplex = "false";
string StartIsKeyword = "false";
string EndIsKeyword = "false";
string IsMultiLineB = "true";
foreach (XmlAttribute att in n.Attributes)
{
if (att.Name.ToLower() == "start")
Start = att.Value;
if (att.Name.ToLower() == "end")
End = att.Value;
if (att.Name.ToLower() == "style")
style = att.Value;
if (att.Name.ToLower() == "endisseparator")
EndIsSeparator = att.Value;
if (att.Name.ToLower() == "startisseparator")
StartIsSeparator = att.Value;
if (att.Name.ToLower() == "startiskeyword")
StartIsKeyword = att.Value;
if (att.Name.ToLower() == "startiscomplex")
StartIsComplex = att.Value;
if (att.Name.ToLower() == "endiscomplex")
EndIsComplex = att.Value;
if (att.Name.ToLower() == "endiskeyword")
EndIsKeyword = att.Value;
if (att.Name.ToLower() == "ismultiline")
IsMultiLineB = att.Value;
}
if (Start != "")
{
PatternList pl = new PatternList();
pl.Style = GetStyle(style);
bool blnStartIsComplex = bool.Parse(StartIsComplex);
bool blnEndIsComplex = bool.Parse(EndIsComplex);
bool blnIsMultiLineB = bool.Parse(IsMultiLineB);
Pattern StartP = new Pattern(Start, blnStartIsComplex, false, bool.Parse(StartIsKeyword));
Pattern EndP = new Pattern(End, blnEndIsComplex, false, bool.Parse(EndIsKeyword));
StartP.MatchingBracket = EndP;
EndP.MatchingBracket = StartP;
StartP.BracketType = BracketType.StartBracket;
EndP.BracketType = BracketType.EndBracket;
StartP.IsMultiLineBracket = EndP.IsMultiLineBracket = blnIsMultiLineB;
pl.Add(StartP);
pl.Add(EndP);
bl.OperatorsList.Add(pl);
}
}
}
if (n.Name.ToLower() == "keywords")
foreach (XmlNode cn in n.ChildNodes)
{
if (cn.Name.ToLower() == "patterngroup")
{
PatternList pl = new PatternList();
bl.KeywordsList.Add(pl);
foreach (XmlAttribute att in cn.Attributes)
{
if (att.Name.ToLower() == "style")
pl.Style = GetStyle(att.Value);
if (att.Name.ToLower() == "name")
pl.Name = att.Value;
if (att.Name.ToLower() == "normalizecase")
pl.NormalizeCase = bool.Parse(att.Value);
if (att.Name.ToLower() == "casesensitive")
pl.CaseSensitive = bool.Parse(att.Value);
}
foreach (XmlNode pt in cn.ChildNodes)
{
if (pt.Name.ToLower() == "pattern")
{
bool IsComplex = false;
bool IsSeparator = false;
string Category = null;
string Pattern = "";
if (pt.Attributes != null)
{
foreach (XmlAttribute att in pt.Attributes)
{
if (att.Name.ToLower() == "text")
Pattern = att.Value;
if (att.Name.ToLower() == "iscomplex")
IsComplex = bool.Parse(att.Value);
if (att.Name.ToLower() == "isseparator")
IsSeparator = bool.Parse(att.Value);
if (att.Name.ToLower() == "category")
Category = (att.Value);
}
}
if (Pattern != "")
{
Pattern pat = new Pattern(Pattern, IsComplex, IsSeparator, true);
pat.Category = Category;
pl.Add(pat);
}
}
else if (pt.Name.ToLower() == "patterns")
{
string Patterns = pt.ChildNodes[0].Value;
Patterns = Patterns.Replace("\t", " ");
while (Patterns.IndexOf(" ") >= 0)
Patterns = Patterns.Replace(" ", " ");
foreach (string Pattern in Patterns.Split())
{
if (Pattern != "")
pl.Add(new Pattern(Pattern, false, false, true));
}
}
}
}
}
//if (n.Name == "Operators")
// ParseStyle(n);
if (n.Name.ToLower() == "operators")
foreach (XmlNode cn in n.ChildNodes)
{
if (cn.Name.ToLower() == "patterngroup")
{
PatternList pl = new PatternList();
bl.OperatorsList.Add(pl);
foreach (XmlAttribute att in cn.Attributes)
{
if (att.Name.ToLower() == "style")
pl.Style = GetStyle(att.Value);
if (att.Name.ToLower() == "name")
pl.Name = att.Value;
if (att.Name.ToLower() == "normalizecase")
pl.NormalizeCase = bool.Parse(att.Value);
if (att.Name.ToLower() == "casesensitive")
pl.CaseSensitive = bool.Parse(att.Value);
}
foreach (XmlNode pt in cn.ChildNodes)
{
if (pt.Name.ToLower() == "pattern")
{
bool IsComplex = false;
bool IsSeparator = false;
string Pattern = "";
string Category = null;
if (pt.Attributes != null)
{
foreach (XmlAttribute att in pt.Attributes)
{
if (att.Name.ToLower() == "text")
Pattern = att.Value;
if (att.Name.ToLower() == "iscomplex")
IsComplex = bool.Parse(att.Value);
if (att.Name.ToLower() == "isseparator")
IsSeparator = bool.Parse(att.Value);
if (att.Name.ToLower() == "category")
Category = (att.Value);
}
}
if (Pattern != "")
{
Pattern pat = new Pattern(Pattern, IsComplex, IsSeparator, false);
pat.Category = Category;
pl.Add(pat);
}
}
else if (pt.Name.ToLower() == "patterns")
{
string Patterns = pt.ChildNodes[0].Value;
Patterns = Patterns.Replace("\t", " ");
while (Patterns.IndexOf(" ") >= 0)
Patterns = Patterns.Replace(" ", " ");
string[] pattSplit = Patterns.Split();
foreach (string Pattern in pattSplit)
{
if (Pattern != "")
pl.Add(new Pattern(Pattern, false, false, false));
}
}
}
}
}
if (n.Name.ToLower() == "childblocks")
{
foreach (XmlNode cn in n.ChildNodes)
{
if (cn.Name.ToLower() == "child")
{
foreach (XmlAttribute att in cn.Attributes)
if (att.Name.ToLower() == "name")
bl.ChildBlocks.Add(GetBlock(att.Value));
}
}
}
}
}
//done
private TextStyle GetStyle(string Name)
{
if (mStyles[Name] == null)
{
TextStyle s = new TextStyle();
mStyles.Add(Name, s);
}
return (TextStyle)mStyles[Name];
}
//done
private BlockType GetBlock(string Name)
{
if (mBlocks[Name] == null)
{
GuruComponents.CodeEditor.CodeEditor.Syntax.BlockType b = new GuruComponents.CodeEditor.CodeEditor.Syntax.BlockType(mLanguage);
mBlocks.Add(Name, b);
}
return (BlockType)mBlocks[Name];
}
//done
private void ParseStyle(XmlNode node)
{
string Name = "";
string ForeColor = "", BackColor = "";
bool Bold = false, Italic = false, Underline = false;
foreach (XmlAttribute att in node.Attributes)
{
if (att.Name.ToLower() == "name")
Name = att.Value;
if (att.Name.ToLower() == "forecolor")
ForeColor = att.Value;
if (att.Name.ToLower() == "backcolor")
BackColor = att.Value;
if (att.Name.ToLower() == "bold")
Bold = bool.Parse(att.Value);
if (att.Name.ToLower() == "italic")
Italic = bool.Parse(att.Value);
if (att.Name.ToLower() == "underline")
Underline = bool.Parse(att.Value);
}
TextStyle st = GetStyle(Name);
if (BackColor != "")
{
st.BackColor = Color.FromName(BackColor);
}
else
{
}
st.ForeColor = Color.FromName(ForeColor);
st.Bold = Bold;
st.Italic = Italic;
st.Underline = Underline;
st.Name = Name;
}
}
}
| |
namespace Rafty.Concensus.States
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FiniteStateMachine;
using Infrastructure;
using Log;
using Messages;
using Microsoft.Extensions.Logging;
using Node;
using Peers;
public sealed class Follower : IState
{
private readonly IFiniteStateMachine _fsm;
private readonly ILog _log;
private readonly IRandomDelay _random;
private Timer _electionTimer;
private int _messagesSinceLastElectionExpiry;
private readonly INode _node;
private readonly ISettings _settings;
private readonly IRules _rules;
private List<IPeer> _peers;
private readonly ILogger<Follower> _logger;
private readonly SemaphoreSlim _appendingEntries = new SemaphoreSlim(1,1);
private bool _checkingElectionStatus;
private bool _disposed;
public Follower(
CurrentState state,
IFiniteStateMachine stateMachine,
ILog log,
IRandomDelay random,
INode node,
ISettings settings,
IRules rules,
List<IPeer> peers,
ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<Follower>();
_peers = peers;
_rules = rules;
_random = random;
_node = node;
_settings = settings;
_fsm = stateMachine;
CurrentState = state;
_log = log;
ResetElectionTimer();
}
public CurrentState CurrentState { get; private set;}
public async Task<AppendEntriesResponse> Handle(AppendEntries appendEntries)
{
try
{
await _appendingEntries.WaitAsync();
var response = _rules.AppendEntriesTermIsLessThanCurrentTerm(appendEntries, CurrentState);
if (response.shouldReturn)
{
return response.appendEntriesResponse;
}
response =
await _rules.LogDoesntContainEntryAtPreviousLogIndexWhoseTermMatchesPreviousLogTerm(appendEntries,
_log, CurrentState);
if (response.shouldReturn)
{
return response.appendEntriesResponse;
}
await _rules.DeleteAnyConflictsInLog(appendEntries, _log);
var terms = appendEntries.Entries.Any()
? string.Join(",", appendEntries.Entries.Select(x => x.Term))
: string.Empty;
_logger.LogInformation(
$"{CurrentState.Id} as {nameof(Follower)} applying {appendEntries.Entries.Count} to log, term {terms}");
await _rules.ApplyNewEntriesToLog(appendEntries, _log);
var commitIndexAndLastApplied =
await _rules.CommitIndexAndLastApplied(appendEntries, _log, CurrentState);
await ApplyToStateMachine(commitIndexAndLastApplied.commitIndex, commitIndexAndLastApplied.lastApplied,
appendEntries);
SetLeaderId(appendEntries);
_messagesSinceLastElectionExpiry++;
return new AppendEntriesResponse(CurrentState.CurrentTerm, true);
}
finally
{
_appendingEntries.Release();
}
}
public async Task<RequestVoteResponse> Handle(RequestVote requestVote)
{
var response = RequestVoteTermIsGreaterThanCurrentTerm(requestVote);
if(response.shouldReturn)
{
return response.requestVoteResponse;
}
response = _rules.RequestVoteTermIsLessThanCurrentTerm(requestVote, CurrentState);
if(response.shouldReturn)
{
return response.requestVoteResponse;
}
response = _rules.VotedForIsNotThisOrNobody(requestVote, CurrentState);
if(response.shouldReturn)
{
return response.requestVoteResponse;
}
response = await LastLogIndexAndLastLogTermMatchesThis(requestVote);
_messagesSinceLastElectionExpiry++;
if(response.shouldReturn)
{
return response.requestVoteResponse;
}
return new RequestVoteResponse(false, CurrentState.CurrentTerm);
}
public async Task<Response<T>> Accept<T>(T command) where T : ICommand
{
var leader = _peers.FirstOrDefault(x => x.Id == CurrentState.LeaderId);
if(leader != null)
{
_logger.LogInformation($"follower id: {CurrentState.Id} forward to leader id: {leader.Id}");
return await leader.Request(command);
}
return new ErrorResponse<T>("Please retry command later. Unable to find leader.", command);
}
public void Stop()
{
_disposed = true;
_electionTimer.Dispose();
}
private (RequestVoteResponse requestVoteResponse, bool shouldReturn) RequestVoteTermIsGreaterThanCurrentTerm(RequestVote requestVote)
{
if (requestVote.Term > CurrentState.CurrentTerm)
{
CurrentState = new CurrentState(CurrentState.Id, requestVote.Term, requestVote.CandidateId,
CurrentState.CommitIndex, CurrentState.LastApplied, CurrentState.LeaderId);
return (new RequestVoteResponse(true, CurrentState.CurrentTerm), true);
}
return (null, false);
}
private async Task<(RequestVoteResponse requestVoteResponse, bool shouldReturn)> LastLogIndexAndLastLogTermMatchesThis(RequestVote requestVote)
{
if (requestVote.LastLogIndex == await _log.LastLogIndex() &&
requestVote.LastLogTerm == await _log.LastLogTerm())
{
CurrentState = new CurrentState(CurrentState.Id, CurrentState.CurrentTerm, requestVote.CandidateId, CurrentState.CommitIndex, CurrentState.LastApplied, CurrentState.LeaderId);
return (new RequestVoteResponse(true, CurrentState.CurrentTerm), true);
}
return (null, false);
}
private async Task ApplyToStateMachine(int commitIndex, int lastApplied, AppendEntries appendEntries)
{
while (commitIndex > lastApplied)
{
_logger.LogInformation($"id: {CurrentState.Id} handling log in fsm in loop, commitIndex: {commitIndex}, lastApplied: {lastApplied}, ae.Count: {appendEntries.Entries.Count}");
lastApplied++;
var log = await _log.Get(lastApplied);
await _fsm.Handle(log);
}
CurrentState = new CurrentState(CurrentState.Id, appendEntries.Term,
CurrentState.VotedFor, commitIndex, lastApplied, CurrentState.LeaderId);
_logger.LogInformation($"id: {CurrentState.Id} handling log in fsm out of loop now, commitIndex: {commitIndex}, lastApplied: {lastApplied}, ae.Count: {appendEntries.Entries.Count}");
_logger.LogInformation($"id: {CurrentState.Id} CurrentState.CommitIndex: {CurrentState.CommitIndex}, CurrentState.LastApplied: {CurrentState.LastApplied}");
}
private void ElectionTimerExpired()
{
try
{
_appendingEntries.Wait();
if (_messagesSinceLastElectionExpiry == 0)
{
_node.BecomeCandidate(CurrentState);
}
else
{
ResetElectionTimer();
}
}
finally
{
_appendingEntries.Release();
}
}
private void SetLeaderId(AppendEntries appendEntries)
{
CurrentState = new CurrentState(CurrentState.Id, CurrentState.CurrentTerm, CurrentState.VotedFor, CurrentState.CommitIndex, CurrentState.LastApplied, appendEntries.LeaderId);
}
private void ResetElectionTimer()
{
_messagesSinceLastElectionExpiry = 0;
var timeout = _random.Get(_settings.MinTimeout, _settings.MaxTimeout);
_electionTimer?.Dispose();
_electionTimer = new Timer(x =>
{
if (_checkingElectionStatus)
{
return;
}
_checkingElectionStatus = true;
ElectionTimerExpired();
_checkingElectionStatus = false;
}, null, Convert.ToInt32(timeout.TotalMilliseconds), Convert.ToInt32(timeout.TotalMilliseconds));
}
}
}
| |
// 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 sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>CampaignSharedSet</c> resource.</summary>
public sealed partial class CampaignSharedSetName : gax::IResourceName, sys::IEquatable<CampaignSharedSetName>
{
/// <summary>The possible contents of <see cref="CampaignSharedSetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>
/// .
/// </summary>
CustomerCampaignSharedSet = 1,
}
private static gax::PathTemplate s_customerCampaignSharedSet = new gax::PathTemplate("customers/{customer_id}/campaignSharedSets/{campaign_id_shared_set_id}");
/// <summary>Creates a <see cref="CampaignSharedSetName"/> 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="CampaignSharedSetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CampaignSharedSetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CampaignSharedSetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CampaignSharedSetName"/> with the pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CampaignSharedSetName"/> constructed from the provided ids.</returns>
public static CampaignSharedSetName FromCustomerCampaignSharedSet(string customerId, string campaignId, string sharedSetId) =>
new CampaignSharedSetName(ResourceNameType.CustomerCampaignSharedSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), sharedSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignSharedSetName"/> with pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignSharedSetName"/> with pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>.
/// </returns>
public static string Format(string customerId, string campaignId, string sharedSetId) =>
FormatCustomerCampaignSharedSet(customerId, campaignId, sharedSetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignSharedSetName"/> with pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignSharedSetName"/> with pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>.
/// </returns>
public static string FormatCustomerCampaignSharedSet(string customerId, string campaignId, string sharedSetId) =>
s_customerCampaignSharedSet.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignSharedSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="campaignSharedSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CampaignSharedSetName"/> if successful.</returns>
public static CampaignSharedSetName Parse(string campaignSharedSetName) => Parse(campaignSharedSetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignSharedSetName"/> 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>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignSharedSetName">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="CampaignSharedSetName"/> if successful.</returns>
public static CampaignSharedSetName Parse(string campaignSharedSetName, bool allowUnparsed) =>
TryParse(campaignSharedSetName, allowUnparsed, out CampaignSharedSetName 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="CampaignSharedSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="campaignSharedSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignSharedSetName"/>, 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 campaignSharedSetName, out CampaignSharedSetName result) =>
TryParse(campaignSharedSetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignSharedSetName"/> 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>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignSharedSetName">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="CampaignSharedSetName"/>, 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 campaignSharedSetName, bool allowUnparsed, out CampaignSharedSetName result)
{
gax::GaxPreconditions.CheckNotNull(campaignSharedSetName, nameof(campaignSharedSetName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignSharedSet.TryParseName(campaignSharedSetName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCampaignSharedSet(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(campaignSharedSetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private CampaignSharedSetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string customerId = null, string sharedSetId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignId = campaignId;
CustomerId = customerId;
SharedSetId = sharedSetId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CampaignSharedSetName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/campaignSharedSets/{campaign_id}~{shared_set_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sharedSetId">The <c>SharedSet</c> ID. Must not be <c>null</c> or empty.</param>
public CampaignSharedSetName(string customerId, string campaignId, string sharedSetId) : this(ResourceNameType.CustomerCampaignSharedSet, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), sharedSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(sharedSetId, nameof(sharedSetId)))
{
}
/// <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>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>SharedSet</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SharedSetId { 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.CustomerCampaignSharedSet: return s_customerCampaignSharedSet.Expand(CustomerId, $"{CampaignId}~{SharedSetId}");
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 CampaignSharedSetName);
/// <inheritdoc/>
public bool Equals(CampaignSharedSetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CampaignSharedSetName a, CampaignSharedSetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CampaignSharedSetName a, CampaignSharedSetName b) => !(a == b);
}
public partial class CampaignSharedSet
{
/// <summary>
/// <see cref="CampaignSharedSetName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CampaignSharedSetName ResourceNameAsCampaignSharedSetName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CampaignSharedSetName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="SharedSetName"/>-typed view over the <see cref="SharedSet"/> resource name property.
/// </summary>
internal SharedSetName SharedSetAsSharedSetName
{
get => string.IsNullOrEmpty(SharedSet) ? null : SharedSetName.Parse(SharedSet, allowUnparsed: true);
set => SharedSet = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Website.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);
}
}
}
}
| |
// created on 09/12/2002 at 21:03
using System;
using System.Runtime.InteropServices;
using SharpLib.Audio.Wave;
// TODO: add function help from MSDN
// TODO: Create enums for flags parameters
namespace SharpLib.Audio.Mixer
{
class MixerInterop
{
public const UInt32 MIXERCONTROL_CONTROLF_UNIFORM = 0x00000001;
public const UInt32 MIXERCONTROL_CONTROLF_MULTIPLE = 0x00000002;
public const UInt32 MIXERCONTROL_CONTROLF_DISABLED = 0x80000000;
public const Int32 MAXPNAMELEN = 32;
public const Int32 MIXER_SHORT_NAME_CHARS = 16;
public const Int32 MIXER_LONG_NAME_CHARS = 64;
// http://msdn.microsoft.com/en-us/library/dd757304%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
public static extern Int32 mixerGetNumDevs();
// http://msdn.microsoft.com/en-us/library/dd757308%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
public static extern MmResult mixerOpen(out IntPtr hMixer, int uMxId, IntPtr dwCallback, IntPtr dwInstance, MixerFlags dwOpenFlags);
// http://msdn.microsoft.com/en-us/library/dd757292%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
public static extern MmResult mixerClose(IntPtr hMixer);
// http://msdn.microsoft.com/en-us/library/dd757299%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
public static extern MmResult mixerGetControlDetails(IntPtr hMixer, ref MIXERCONTROLDETAILS mixerControlDetails, MixerFlags dwDetailsFlags);
// http://msdn.microsoft.com/en-us/library/dd757300%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
public static extern MmResult mixerGetDevCaps(IntPtr nMixerID, ref MIXERCAPS mixerCaps, Int32 mixerCapsSize);
// http://msdn.microsoft.com/en-us/library/dd757301%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
public static extern MmResult mixerGetID(IntPtr hMixer, out Int32 mixerID, MixerFlags dwMixerIDFlags);
// http://msdn.microsoft.com/en-us/library/dd757302%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
public static extern MmResult mixerGetLineControls(IntPtr hMixer, ref MIXERLINECONTROLS mixerLineControls, MixerFlags dwControlFlags);
// http://msdn.microsoft.com/en-us/library/dd757303%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
public static extern MmResult mixerGetLineInfo(IntPtr hMixer, ref MIXERLINE mixerLine, MixerFlags dwInfoFlags);
// http://msdn.microsoft.com/en-us/library/dd757307%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
public static extern MmResult mixerMessage(IntPtr hMixer, UInt32 nMessage, IntPtr dwParam1, IntPtr dwParam2);
// http://msdn.microsoft.com/en-us/library/dd757309%28VS.85%29.aspx
[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
public static extern MmResult mixerSetControlDetails(IntPtr hMixer, ref MIXERCONTROLDETAILS mixerControlDetails, MixerFlags dwDetailsFlags);
// http://msdn.microsoft.com/en-us/library/dd757294%28VS.85%29.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
public struct MIXERCONTROLDETAILS
{
public Int32 cbStruct; // size of the MIXERCONTROLDETAILS structure
public Int32 dwControlID;
public Int32 cChannels; // Number of channels on which to get or set control properties
public IntPtr hwndOwner; // Union with DWORD cMultipleItems
public Int32 cbDetails; // Size of the paDetails Member
public IntPtr paDetails; // LPVOID
}
// http://msdn.microsoft.com/en-us/library/dd757291%28VS.85%29.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct MIXERCAPS
{
public UInt16 wMid;
public UInt16 wPid;
public UInt32 vDriverVersion; // MMVERSION - major high byte, minor low byte
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAXPNAMELEN)]
public String szPname;
public UInt32 fdwSupport;
public UInt32 cDestinations;
}
// http://msdn.microsoft.com/en-us/library/dd757306%28VS.85%29.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct MIXERLINECONTROLS
{
public Int32 cbStruct; // size of the MIXERLINECONTROLS structure
public Int32 dwLineID; // Line identifier for which controls are being queried
public Int32 dwControlID; // union with UInt32 dwControlType
public Int32 cControls;
public Int32 cbmxctrl;
public IntPtr pamxctrl; // see MSDN "Structs Sample"
}
/// <summary>
/// Mixer Line Flags
/// </summary>
[Flags]
public enum MIXERLINE_LINEF
{
/// <summary>
/// Audio line is active. An active line indicates that a signal is probably passing
/// through the line.
/// </summary>
MIXERLINE_LINEF_ACTIVE = 1,
/// <summary>
/// Audio line is disconnected. A disconnected line's associated controls can still be
/// modified, but the changes have no effect until the line is connected.
/// </summary>
MIXERLINE_LINEF_DISCONNECTED = 0x8000,
/// <summary>
/// Audio line is an audio source line associated with a single audio destination line.
/// If this flag is not set, this line is an audio destination line associated with zero
/// or more audio source lines.
/// </summary>
MIXERLINE_LINEF_SOURCE = (unchecked((int)0x80000000))
}
// http://msdn.microsoft.com/en-us/library/dd757305%28VS.85%29.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct MIXERLINE
{
public Int32 cbStruct;
public Int32 dwDestination;
public Int32 dwSource;
public Int32 dwLineID;
public MIXERLINE_LINEF fdwLine;
public IntPtr dwUser;
public MixerLineComponentType dwComponentType;
public Int32 cChannels;
public Int32 cConnections;
public Int32 cControls;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MIXER_SHORT_NAME_CHARS)]
public String szShortName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MIXER_LONG_NAME_CHARS)]
public String szName;
// start of target struct 'Target'
public UInt32 dwType;
public UInt32 dwDeviceID;
public UInt16 wMid;
public UInt16 wPid;
public UInt32 vDriverVersion; // MMVERSION - major high byte, minor low byte
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAXPNAMELEN)]
public String szPname;
// end of target struct
}
/// <summary>
/// BOUNDS structure
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Bounds
{
/// <summary>
/// dwMinimum / lMinimum / reserved 0
/// </summary>
public int minimum;
/// <summary>
/// dwMaximum / lMaximum / reserved 1
/// </summary>
public int maximum;
/// <summary>
/// reserved 2
/// </summary>
public int reserved2;
/// <summary>
/// reserved 3
/// </summary>
public int reserved3;
/// <summary>
/// reserved 4
/// </summary>
public int reserved4;
/// <summary>
/// reserved 5
/// </summary>
public int reserved5;
}
/// <summary>
/// METRICS structure
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Metrics
{
/// <summary>
/// cSteps / reserved[0]
/// </summary>
public int step;
/// <summary>
/// cbCustomData / reserved[1], number of bytes for control details
/// </summary>
public int customData;
/// <summary>
/// reserved 2
/// </summary>
public int reserved2;
/// <summary>
/// reserved 3
/// </summary>
public int reserved3;
/// <summary>
/// reserved 4
/// </summary>
public int reserved4;
/// <summary>
/// reserved 5
/// </summary>
public int reserved5;
}
/// <summary>
/// MIXERCONTROL struct
/// http://msdn.microsoft.com/en-us/library/dd757293%28VS.85%29.aspx
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct MIXERCONTROL
{
public UInt32 cbStruct;
public Int32 dwControlID;
public MixerControlType dwControlType;
public UInt32 fdwControl;
public UInt32 cMultipleItems;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MIXER_SHORT_NAME_CHARS)]
public String szShortName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MIXER_LONG_NAME_CHARS)]
public String szName;
public Bounds Bounds;
public Metrics Metrics;
}
// http://msdn.microsoft.com/en-us/library/dd757295%28VS.85%29.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MIXERCONTROLDETAILS_BOOLEAN
{
public Int32 fValue;
}
// http://msdn.microsoft.com/en-us/library/dd757297%28VS.85%29.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MIXERCONTROLDETAILS_SIGNED
{
public Int32 lValue;
}
// http://msdn.microsoft.com/en-us/library/dd757296%28VS.85%29.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct MIXERCONTROLDETAILS_LISTTEXT
{
public UInt32 dwParam1;
public UInt32 dwParam2;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MIXER_LONG_NAME_CHARS)]
public String szName;
}
// http://msdn.microsoft.com/en-us/library/dd757298%28VS.85%29.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MIXERCONTROLDETAILS_UNSIGNED
{
public UInt32 dwValue;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Button.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web;
using System.Web.UI;
using System.Web.Util;
/// <devdoc>
/// <para>Represents a Windows button control.</para>
/// </devdoc>
[
DataBindingHandler("System.Web.UI.Design.TextDataBindingHandler, " + AssemblyRef.SystemDesign),
DefaultEvent("Click"),
DefaultProperty("Text"),
Designer("System.Web.UI.Design.WebControls.ButtonDesigner, " + AssemblyRef.SystemDesign),
ToolboxData("<{0}:Button runat=\"server\" Text=\"Button\"></{0}:Button>"),
SupportsEventValidation
]
public class Button : WebControl, IButtonControl, IPostBackEventHandler {
private static readonly object EventClick = new object();
private static readonly object EventCommand = new object();
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Web.UI.WebControls.Button'/> class.</para>
/// </devdoc>
public Button() : base(HtmlTextWriterTag.Input) {
}
/// <devdoc>
/// <para>Gets or sets whether pressing the button causes page validation to fire. This defaults to True so that when
/// using validation controls, the validation state of all controls are updated when the button is clicked, both
/// on the client and the server. Setting this to False is useful when defining a cancel or reset button on a page
/// that has validators.</para>
/// </devdoc>
[
DefaultValue(true),
Themeable(false),
WebCategory("Behavior"),
WebSysDescription(SR.Button_CausesValidation),
]
public virtual bool CausesValidation {
get {
object b = ViewState["CausesValidation"];
return((b == null) ? true : (bool)b);
}
set {
ViewState["CausesValidation"] = value;
}
}
/// <devdoc>
/// <para>Gets or sets the command associated with a <see cref='System.Web.UI.WebControls.Button'/> propogated in the <see langword='Command'/> event along with the <see cref='System.Web.UI.WebControls.Button.CommandArgument'/>
/// property.</para>
/// </devdoc>
[
DefaultValue(""),
Themeable(false),
WebCategory("Behavior"),
WebSysDescription(SR.WebControl_CommandName),
]
public string CommandName {
get {
string s = (string)ViewState["CommandName"];
return((s == null) ? String.Empty : s);
}
set {
ViewState["CommandName"] = value;
}
}
/// <devdoc>
/// <para>Gets or sets the property propogated in
/// the <see langword='Command'/> event with the associated <see cref='System.Web.UI.WebControls.Button.CommandName'/>
/// property.</para>
/// </devdoc>
[
Bindable(true),
DefaultValue(""),
Themeable(false),
WebCategory("Behavior"),
WebSysDescription(SR.WebControl_CommandArgument),
]
public string CommandArgument {
get {
string s = (string)ViewState["CommandArgument"];
return((s == null) ? String.Empty : s);
}
set {
ViewState["CommandArgument"] = value;
}
}
/// <devdoc>
/// The script that is executed on a client-side click.
/// </devdoc>
[
DefaultValue(""),
Themeable(false),
WebCategory("Behavior"),
WebSysDescription(SR.Button_OnClientClick),
]
public virtual string OnClientClick {
get {
string s = (string)ViewState["OnClientClick"];
if (s == null) {
return String.Empty;
}
return s;
}
set {
ViewState["OnClientClick"] = value;
}
}
[
DefaultValue(""),
Editor("System.Web.UI.Design.UrlEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
Themeable(false),
UrlProperty("*.aspx"),
WebCategory("Behavior"),
WebSysDescription(SR.Button_PostBackUrl),
]
public virtual string PostBackUrl {
get {
string s = (string)ViewState["PostBackUrl"];
return s == null? String.Empty : s;
}
set {
ViewState["PostBackUrl"] = value;
}
}
/// <devdoc>
/// <para>Gets or sets the text caption displayed on the <see cref='System.Web.UI.WebControls.Button'/> .</para>
/// </devdoc>
[
Bindable(true),
Localizable(true),
WebCategory("Appearance"),
DefaultValue(""),
WebSysDescription(SR.Button_Text),
]
public string Text {
get {
string s = (string)ViewState["Text"];
return((s == null) ? String.Empty : s);
}
set {
ViewState["Text"] = value;
}
}
/// <devdoc>
/// Whether the button should use the client's submit mechanism to implement its
/// behavior, or whether it should use the ASP.NET postback mechanism similar
/// to LinkButton. By default, it uses the browser's submit mechanism.
/// </devdoc>
[
DefaultValue(true),
Themeable(false),
WebCategory("Behavior"),
WebSysDescription(SR.Button_UseSubmitBehavior),
]
public virtual bool UseSubmitBehavior {
get {
object b = ViewState["UseSubmitBehavior"];
return ((b == null) ? true : (bool)b);
}
set {
ViewState["UseSubmitBehavior"] = value;
}
}
[
DefaultValue(""),
Themeable(false),
WebCategory("Behavior"),
WebSysDescription(SR.PostBackControl_ValidationGroup),
]
public virtual string ValidationGroup {
get {
string s = (string)ViewState["ValidationGroup"];
return((s == null) ? String.Empty : s);
}
set {
ViewState["ValidationGroup"] = value;
}
}
/// <devdoc>
/// <para>Occurs when the <see cref='System.Web.UI.WebControls.Button'/> is clicked.</para>
/// </devdoc>
[
WebCategory("Action"),
WebSysDescription(SR.Button_OnClick)
]
public event EventHandler Click {
add {
Events.AddHandler(EventClick, value);
}
remove {
Events.RemoveHandler(EventClick, value);
}
}
/// <devdoc>
/// <para>Occurs when the <see cref='System.Web.UI.WebControls.Button'/> is clicked.</para>
/// </devdoc>
[
WebCategory("Action"),
WebSysDescription(SR.Button_OnCommand)
]
public event CommandEventHandler Command {
add {
Events.AddHandler(EventCommand, value);
}
remove {
Events.RemoveHandler(EventCommand, value);
}
}
/// <internalonly/>
/// <devdoc>
/// <para>Adds the attributes of the <see cref='System.Web.UI.WebControls.Button'/> control to the output stream for rendering
/// on the client.</para>
/// </devdoc>
protected override void AddAttributesToRender(HtmlTextWriter writer) {
bool submitButton = UseSubmitBehavior;
// Make sure we are in a form tag with runat=server.
if (Page != null) {
Page.VerifyRenderingInServerForm(this);
}
if (submitButton) {
writer.AddAttribute(HtmlTextWriterAttribute.Type, "submit");
}
else {
writer.AddAttribute(HtmlTextWriterAttribute.Type, "button");
}
PostBackOptions options = GetPostBackOptions();
string uniqueID = UniqueID;
// Don't render Name on a button if __doPostBack is posting back to a different control
// because Page will register this control as requiring post back notification even though
// it's not the target of the postback. If the TargetControl isn't this control, this control's
// RaisePostBackEvent should never get called. See VSWhidbey 477095.
if (uniqueID != null && (options == null || options.TargetControl == this)) {
writer.AddAttribute(HtmlTextWriterAttribute.Name, uniqueID);
}
writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);
//
bool effectiveEnabled = IsEnabled;
string onClick = String.Empty;
if (effectiveEnabled) {
// Need to merge the onclick attribute with the OnClientClick
// VSWhidbey 111791: Defensively add a ';' in case it is
// missing in user customized onClick value above.
onClick = Util.EnsureEndWithSemiColon(OnClientClick);
if (HasAttributes) {
string userOnClick = Attributes["onclick"];
if (userOnClick != null) {
onClick += Util.EnsureEndWithSemiColon(userOnClick);
Attributes.Remove("onclick");
}
}
if (Page != null) {
string reference = Page.ClientScript.GetPostBackEventReference(options, false);
if (reference != null) {
onClick = Util.MergeScript(onClick, reference);
}
}
}
if (Page != null) {
Page.ClientScript.RegisterForEventValidation(options);
}
if (onClick.Length > 0) {
writer.AddAttribute(HtmlTextWriterAttribute.Onclick, onClick);
if (EnableLegacyRendering) {
writer.AddAttribute("language", "javascript", false);
}
}
if (Enabled && !effectiveEnabled && SupportsDisabledAttribute) {
// We need to do the cascade effect on the server, because the browser
// only renders as disabled, but doesn't disable the functionality.
writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
}
base.AddAttributesToRender(writer);
}
protected virtual PostBackOptions GetPostBackOptions() {
PostBackOptions options = new PostBackOptions(this, String.Empty);
options.ClientSubmit = false;
if (Page != null) {
if (CausesValidation && Page.GetValidators(ValidationGroup).Count > 0) {
options.PerformValidation = true;
options.ValidationGroup = ValidationGroup;
}
if (!String.IsNullOrEmpty(PostBackUrl)) {
options.ActionUrl = HttpUtility.UrlPathEncode(ResolveClientUrl(PostBackUrl));
}
options.ClientSubmit = !UseSubmitBehavior;
}
return options;
}
/// <devdoc>
/// <para>Raises the <see langword='Click '/>event of a <see cref='System.Web.UI.WebControls.Button'/>
/// .</para>
/// </devdoc>
protected virtual void OnClick(EventArgs e) {
EventHandler handler = (EventHandler)Events[EventClick];
if (handler != null) handler(this,e);
}
/// <devdoc>
/// <para>Raises the <see langword='Command '/>event of a <see cref='System.Web.UI.WebControls.Button'/>
/// .</para>
/// </devdoc>
protected virtual void OnCommand(CommandEventArgs e) {
CommandEventHandler handler = (CommandEventHandler)Events[EventCommand];
if (handler != null)
handler(this,e);
// Command events are bubbled up the control heirarchy
RaiseBubbleEvent(this, e);
}
protected internal override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
// VSWhidbey 489577
if (Page != null && IsEnabled) {
if ((CausesValidation && Page.GetValidators(ValidationGroup).Count > 0) ||
!String.IsNullOrEmpty(PostBackUrl)) {
Page.RegisterWebFormsScript();
}
else if (!UseSubmitBehavior) {
Page.RegisterPostBackScript();
}
}
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
protected internal override void RenderContents(HtmlTextWriter writer) {
// Do not render the children of a button since it does not
// make sense to have children of an <input> tag.
}
/// <internalonly/>
/// <devdoc>
/// <para>Raises events for the <see cref='System.Web.UI.WebControls.Button'/>
/// control on post back.</para>
/// </devdoc>
void IPostBackEventHandler.RaisePostBackEvent(string eventArgument) {
RaisePostBackEvent(eventArgument);
}
/// <internalonly/>
/// <devdoc>
/// <para>Raises events for the <see cref='System.Web.UI.WebControls.Button'/>
/// control on post back.</para>
/// </devdoc>
protected virtual void RaisePostBackEvent(string eventArgument) {
ValidateEvent(this.UniqueID, eventArgument);
if (CausesValidation) {
Page.Validate(ValidationGroup);
}
OnClick(EventArgs.Empty);
OnCommand(new CommandEventArgs(CommandName, CommandArgument));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Cache;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public abstract class WebRequest : MarshalByRefObject, ISerializable
{
internal class WebRequestPrefixElement
{
public readonly string Prefix;
public readonly IWebRequestCreate Creator;
public WebRequestPrefixElement(string prefix, IWebRequestCreate creator)
{
Prefix = prefix;
Creator = creator;
}
}
private static List<WebRequestPrefixElement> s_prefixList;
private static object s_internalSyncObject = new object();
internal const int DefaultTimeoutMilliseconds = 100 * 1000;
protected WebRequest() { }
protected WebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
throw new PlatformNotSupportedException();
}
// Create a WebRequest.
//
// This is the main creation routine. We take a Uri object, look
// up the Uri in the prefix match table, and invoke the appropriate
// handler to create the object. We also have a parameter that
// tells us whether or not to use the whole Uri or just the
// scheme portion of it.
//
// Input:
// requestUri - Uri object for request.
// useUriBase - True if we're only to look at the scheme portion of the Uri.
//
// Returns:
// Newly created WebRequest.
private static WebRequest Create(Uri requestUri, bool useUriBase)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(null, requestUri);
string LookupUri;
WebRequestPrefixElement Current = null;
bool Found = false;
if (!useUriBase)
{
LookupUri = requestUri.AbsoluteUri;
}
else
{
// schemes are registered as <schemeName>":", so add the separator
// to the string returned from the Uri object
LookupUri = requestUri.Scheme + ':';
}
int LookupLength = LookupUri.Length;
// Copy the prefix list so that if it is updated it will
// not affect us on this thread.
List<WebRequestPrefixElement> prefixList = PrefixList;
// Look for the longest matching prefix.
// Walk down the list of prefixes. The prefixes are kept longest
// first. When we find a prefix that is shorter or the same size
// as this Uri, we'll do a compare to see if they match. If they
// do we'll break out of the loop and call the creator.
for (int i = 0; i < prefixList.Count; i++)
{
Current = prefixList[i];
// See if this prefix is short enough.
if (LookupLength >= Current.Prefix.Length)
{
// It is. See if these match.
if (String.Compare(Current.Prefix,
0,
LookupUri,
0,
Current.Prefix.Length,
StringComparison.OrdinalIgnoreCase) == 0)
{
// These match. Remember that we found it and break
// out.
Found = true;
break;
}
}
}
WebRequest webRequest = null;
if (Found)
{
// We found a match, so just call the creator and return what it does.
webRequest = Current.Creator.Create(requestUri);
if (NetEventSource.IsEnabled) NetEventSource.Exit(null, webRequest);
return webRequest;
}
// Otherwise no match, throw an exception.
if (NetEventSource.IsEnabled) NetEventSource.Exit(null);
throw new NotSupportedException(SR.net_unknown_prefix);
}
// Create - Create a WebRequest.
//
// An overloaded utility version of the real Create that takes a
// string instead of an Uri object.
//
// Input:
// RequestString - Uri string to create.
//
// Returns:
// Newly created WebRequest.
public static WebRequest Create(string requestUriString)
{
if (requestUriString == null)
{
throw new ArgumentNullException(nameof(requestUriString));
}
return Create(new Uri(requestUriString), false);
}
// Create - Create a WebRequest.
//
// Another overloaded version of the Create function that doesn't
// take the UseUriBase parameter.
//
// Input:
// requestUri - Uri object for request.
//
// Returns:
// Newly created WebRequest.
public static WebRequest Create(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException(nameof(requestUri));
}
return Create(requestUri, false);
}
// CreateDefault - Create a default WebRequest.
//
// This is the creation routine that creates a default WebRequest.
// We take a Uri object and pass it to the base create routine,
// setting the useUriBase parameter to true.
//
// Input:
// RequestUri - Uri object for request.
//
// Returns:
// Newly created WebRequest.
public static WebRequest CreateDefault(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException(nameof(requestUri));
}
return Create(requestUri, true);
}
public static HttpWebRequest CreateHttp(string requestUriString)
{
if (requestUriString == null)
{
throw new ArgumentNullException(nameof(requestUriString));
}
return CreateHttp(new Uri(requestUriString));
}
public static HttpWebRequest CreateHttp(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException(nameof(requestUri));
}
if ((requestUri.Scheme != "http") && (requestUri.Scheme != "https"))
{
throw new NotSupportedException(SR.net_unknown_prefix);
}
return (HttpWebRequest)CreateDefault(requestUri);
}
// RegisterPrefix - Register an Uri prefix for creating WebRequests.
//
// This function registers a prefix for creating WebRequests. When an
// user wants to create a WebRequest, we scan a table looking for a
// longest prefix match for the Uri they're passing. We then invoke
// the sub creator for that prefix. This function puts entries in
// that table.
//
// We don't allow duplicate entries, so if there is a dup this call
// will fail.
//
// Input:
// Prefix - Represents Uri prefix being registered.
// Creator - Interface for sub creator.
//
// Returns:
// True if the registration worked, false otherwise.
public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
{
bool Error = false;
int i;
WebRequestPrefixElement Current;
if (prefix == null)
{
throw new ArgumentNullException(nameof(prefix));
}
if (creator == null)
{
throw new ArgumentNullException(nameof(creator));
}
// Lock this object, then walk down PrefixList looking for a place to
// to insert this prefix.
lock (s_internalSyncObject)
{
// Clone the object and update the clone, thus
// allowing other threads to still read from the original.
List<WebRequestPrefixElement> prefixList = new List<WebRequestPrefixElement>(PrefixList);
// As AbsoluteUri is used later for Create, account for formating changes
// like Unicode escaping, default ports, etc.
Uri tempUri;
if (Uri.TryCreate(prefix, UriKind.Absolute, out tempUri))
{
String cookedUri = tempUri.AbsoluteUri;
// Special case for when a partial host matching is requested, drop the added trailing slash
// IE: http://host could match host or host.domain
if (!prefix.EndsWith("/", StringComparison.Ordinal)
&& tempUri.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.UriEscaped)
.Equals("/"))
{
cookedUri = cookedUri.Substring(0, cookedUri.Length - 1);
}
prefix = cookedUri;
}
i = 0;
// The prefix list is sorted with longest entries at the front. We
// walk down the list until we find a prefix shorter than this
// one, then we insert in front of it. Along the way we check
// equal length prefixes to make sure this isn't a dupe.
while (i < prefixList.Count)
{
Current = prefixList[i];
// See if the new one is longer than the one we're looking at.
if (prefix.Length > Current.Prefix.Length)
{
// It is. Break out of the loop here.
break;
}
// If these are of equal length, compare them.
if (prefix.Length == Current.Prefix.Length)
{
// They're the same length.
if (string.Equals(Current.Prefix, prefix, StringComparison.OrdinalIgnoreCase))
{
// ...and the strings are identical. This is an error.
Error = true;
break;
}
}
i++;
}
// When we get here either i contains the index to insert at or
// we've had an error, in which case Error is true.
if (!Error)
{
// No error, so insert.
prefixList.Insert(i, new WebRequestPrefixElement(prefix, creator));
// Assign the clone to the static object. Other threads using it
// will have copied the original object already.
PrefixList = prefixList;
}
}
return !Error;
}
internal class HttpRequestCreator : IWebRequestCreate
{
// Create - Create an HttpWebRequest.
//
// This is our method to create an HttpWebRequest. We register
// for HTTP and HTTPS Uris, and this method is called when a request
// needs to be created for one of those.
//
//
// Input:
// uri - Uri for request being created.
//
// Returns:
// The newly created HttpWebRequest.
public WebRequest Create(Uri Uri)
{
return new HttpWebRequest(Uri);
}
}
// PrefixList - Returns And Initialize our prefix list.
//
//
// This is the method that initializes the prefix list. We create
// an List for the PrefixList, then each of the request creators,
// and then we register them with the associated prefixes.
//
// Returns:
// true
internal static List<WebRequestPrefixElement> PrefixList
{
get
{
// GetConfig() might use us, so we have a circular dependency issue
// that causes us to nest here. We grab the lock only if we haven't
// initialized.
return LazyInitializer.EnsureInitialized(ref s_prefixList, ref s_internalSyncObject, () =>
{
var httpRequestCreator = new HttpRequestCreator();
var ftpRequestCreator = new FtpWebRequestCreator();
var fileRequestCreator = new FileWebRequestCreator();
const int Count = 4;
var prefixList = new List<WebRequestPrefixElement>(Count)
{
new WebRequestPrefixElement("http:", httpRequestCreator),
new WebRequestPrefixElement("https:", httpRequestCreator),
new WebRequestPrefixElement("ftp:", ftpRequestCreator),
new WebRequestPrefixElement("file:", fileRequestCreator),
};
Debug.Assert(prefixList.Count == Count, $"Expected {Count}, got {prefixList.Count}");
return prefixList;
});
}
set
{
Volatile.Write(ref s_prefixList, value);
}
}
public static RequestCachePolicy DefaultCachePolicy { get; set; } = new RequestCachePolicy(RequestCacheLevel.BypassCache);
public virtual RequestCachePolicy CachePolicy { get; set; }
public AuthenticationLevel AuthenticationLevel { get; set; } = AuthenticationLevel.MutualAuthRequested;
public TokenImpersonationLevel ImpersonationLevel { get; set; } = TokenImpersonationLevel.Delegation;
public virtual string ConnectionGroupName
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual string Method
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual Uri RequestUri
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual WebHeaderCollection Headers
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual long ContentLength
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual string ContentType
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual ICredentials Credentials
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual int Timeout
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual bool UseDefaultCredentials
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual Stream GetRequestStream()
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual WebResponse GetResponse()
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual WebResponse EndGetResponse(IAsyncResult asyncResult)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual Stream EndGetRequestStream(IAsyncResult asyncResult)
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
public virtual Task<Stream> GetRequestStreamAsync()
{
// Offload to a different thread to avoid blocking the caller during request submission.
// We use Task.Run rather than Task.Factory.StartNew even though StartNew would let us pass 'this'
// as a state argument to avoid the closure to capture 'this' and the associated delegate.
// This is because the task needs to call FromAsync and marshal the inner Task out, and
// Task.Run's implementation of this is sufficiently more efficient than what we can do with
// Unwrap() that it's worth it to just rely on Task.Run and accept the closure/delegate.
return Task.Run(() =>
Task<Stream>.Factory.FromAsync(
(callback, state) => ((WebRequest)state).BeginGetRequestStream(callback, state),
iar => ((WebRequest)iar.AsyncState).EndGetRequestStream(iar),
this));
}
public virtual Task<WebResponse> GetResponseAsync()
{
// See comment in GetRequestStreamAsync(). Same logic applies here.
return Task.Run(() =>
Task<WebResponse>.Factory.FromAsync(
(callback, state) => ((WebRequest)state).BeginGetResponse(callback, state),
iar => ((WebRequest)iar.AsyncState).EndGetResponse(iar),
this));
}
public virtual void Abort()
{
throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
}
// Default Web Proxy implementation.
private static IWebProxy s_DefaultWebProxy;
private static bool s_DefaultWebProxyInitialized;
public static IWebProxy GetSystemWebProxy() => SystemWebProxy.Get();
public static IWebProxy DefaultWebProxy
{
get
{
return LazyInitializer.EnsureInitialized(ref s_DefaultWebProxy, ref s_DefaultWebProxyInitialized, ref s_internalSyncObject, () => SystemWebProxy.Get());
}
set
{
lock (s_internalSyncObject)
{
s_DefaultWebProxy = value;
s_DefaultWebProxyInitialized = true;
}
}
}
public virtual bool PreAuthenticate
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual IWebProxy Proxy
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="AutomationTestsControl" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: User Control showing Automation-Element Tests
//
// History:
// 08/29/2006 : Ondrej Lehecka, created
//
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Drawing=System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Windows.Automation;
using System.Diagnostics;
using VisualUIAVerify.Features;
using VisualUIAVerify.Utils;
namespace VisualUIAVerify.Controls
{
/// <summary></summary>
public enum MovementDirections
{
/// <summary></summary>
Left,
/// <summary></summary>
Right,
/// <summary></summary>
Up,
/// <summary></summary>
Down
}
/// <summary>
/// This control shows AutomationElementTests
/// </summary>
public partial class AutomationTestsControl : UserControl
{
#region private properties
/// <summary>
/// scope of shown the tests
/// </summary>
private TestsScope _scope;
/// <summary>
/// types of shown tests
/// </summary>
private TestTypes _types;
/// <summary>
/// priorities of shown tests
/// </summary>
private TestPriorities _priorities;
/// <summary>
/// selected element
/// </summary>
private AutomationElement _selectedElement;
/// <summary>
/// indicating that ShowTests method was called
/// </summary>
private bool _showTests;
#endregion
/// <summary>
/// events fired when menu items clicked
/// </summary>
public event EventHandler RunTestRequired, RunTestOnAllChildrenRequired;
/// <summary>
/// initializes new instance.
/// </summary>
public AutomationTestsControl()
{
InitializeComponent();
}
/// <summary>
/// get/set scope of tests
/// </summary>
public TestsScope Scope
{
get { return this._scope; }
set
{
if(this._scope != value)
{
this._scope = value;
RefreshTests();
}
}
}
/// <summary>
/// get/set types of the tests to be shown
/// </summary>
public TestTypes Types
{
get { return this._types; }
set
{
if(this._types != value)
{
this._types = value;
RefreshTests();
}
}
}
/// <summary>
/// get/set test priorities
/// </summary>
public TestPriorities Priorities
{
get { return this._priorities; }
set
{
if(this._priorities != value)
{
this._priorities = value;
RefreshTests();
}
}
}
/// <summary>
/// get/set selected automation element which is to be tested
/// </summary>
public AutomationElement SelectedElement
{
get { return this._selectedElement; }
set
{
if(this._selectedElement != value)
{
this._selectedElement = value;
if(this._scope == TestsScope.SelectedElementTests)
RefreshTests();
}
}
}
/// <summary>
///
/// </summary>
/// <param name="direction"></param>
public void MoveToTest(MovementDirections direction)
{
TreeNode selectedNode = _testsTreeView.SelectedNode;
if (selectedNode == null)
selectedNode = _testsTreeView.Nodes[0];
switch (direction)
{
case MovementDirections.Left:
selectedNode = selectedNode.Parent;
break;
case MovementDirections.Right:
if (selectedNode.Nodes.Count > 0)
selectedNode = selectedNode.Nodes[0];
else
selectedNode = null;
break;
case MovementDirections.Up:
// SendKeys.Send("UP");
// it does not work on certain builds of Vista
selectedNode = selectedNode.PrevNode;
break;
case MovementDirections.Down:
// SendKeys.Send("DOWN");
selectedNode = selectedNode.NextNode;
break;
}
if (selectedNode != null)
{
_testsTreeView.SelectedNode = selectedNode;
selectedNode.EnsureVisible();
}
}
/// <summary>
/// this is to grab all selected tests
/// </summary>
public IEnumerable<AutomationTest> SelectedTests
{
get
{
List<AutomationTest> selectedTests = new List<AutomationTest>();
if(this._testsTreeView.SelectedNode != null)
GrabTests(this._testsTreeView.SelectedNode, selectedTests);
return selectedTests;
}
}
/// <summary>
/// helper method to grab selected tests
/// </summary>
private void GrabTests(TreeNode treeNode, List<AutomationTest> selectedTests)
{
// get automation test for treeNode
AutomationTest nodeTest = treeNode.Tag as AutomationTest;
// if automation test is not contained in tests collection then add him to the collection
if (nodeTest != null && !selectedTests.Contains(nodeTest))
selectedTests.Add(nodeTest);
// add all tests in children nodes
foreach (TreeNode childNode in treeNode.Nodes)
GrabTests(childNode, selectedTests);
}
/// <summary>
/// this method causes showing of tests in the tree.
/// </summary>
public void ShowTests()
{
this._showTests = true;
RefreshTests();
}
/// <summary>
///
/// </summary>
/// <param name="refreshTestsCollection"></param>
public void RefreshTests(bool refreshTestsCollection)
{
if(refreshTestsCollection)
AutomationTestCollection.RefreshTests();
RefreshTests();
}
#region creating the automation tests tree
/// <summary>
/// this method will clear and create new tree of automation tests according to required
/// TestScope, TestTypes, TestPriorities.
/// </summary>
private void RefreshTests()
{
// if we are not showing tests then we don't have to do anything
if(!_showTests)
return;
//editing is starting, so don't update the tree until it finishes
_testsTreeView.BeginUpdate();
//ensure we have one root currentTestTypeRootNode named 'Tests' without children nodes
if (_testsTreeView.Nodes.Count == 0)
_testsTreeView.Nodes.Add("Tests");
else
_testsTreeView.Nodes[0].Nodes.Clear();
SetSelectedTest(_testsTreeView.Nodes[0]);
//go thru all kinds of possible TestTypes and if there is any required, create subtree for it
foreach (TestTypes testType in Enum.GetValues(typeof(TestTypes)))
{
if (testType != TestTypes.None &&
(this._types & testType) == testType
)
{
//create subtree for this type of tests
CreateTestTypeNodeSubtree(testType, new TestFilterType(testType));
}
}
// sort tree nodes
_testsTreeView.Sort();
// expand the tree to certain level
ExpandTree(_testsTreeView.Nodes, 2);
//editing of the tree is finished
_testsTreeView.EndUpdate();
}
/// <summary>
/// this method expand tests tree to certain level
/// </summary>
private void ExpandTree(TreeNodeCollection nodes, int levels)
{
if (levels > 0)
{
foreach (TreeNode node in nodes)
{
node.Expand();
ExpandTree(node.Nodes, levels - 1);
}
}
}
/// <summary>
/// this method creates automation tests subtree for particular test type
/// </summary>
/// <param name="testType"></param>
/// <param name="testFilter">filter to be applied on all available automation tests collection</param>
private void CreateTestTypeNodeSubtree(TestTypes testType, AutomationTestsFilter testFilter)
{
//create root currentTestTypeRootNode for the currentTestTypeRootNode type
TreeNode currentTestTypeRootNode = new TreeNode(GetTestTypeName(testType));
_testsTreeView.Nodes[0].Nodes.Add(currentTestTypeRootNode);
if (testType == TestTypes.ControlTest)
{
//if ControlTest test type is required then let's get automation ControlType
//for the selected automation element. If we are showing all tests, not only for selected
//elements then let's get all automation element ControlTypes.
//for all grabbed ControlTypes let's create subtree with tests
ControlType[] controlTypes;
if (this._scope == TestsScope.SelectedElementTests)
{
try
{
//get control type if selected automation element
controlTypes = new ControlType[] { this._selectedElement.Current.ControlType };
}
catch (ElementNotAvailableException)
{
//if there are problems with the elements then ignore it
controlTypes = new ControlType[] { };
}
}
else
{
// let's get all automation technology ControlTypes
controlTypes = AutomationHelper.GetAllAutomationControlTypes();
}
//fore each control type, let's create subtree
foreach (ControlType controlType in controlTypes)
{
//create automation tests filter for the controlType
FilterControlTypeTests controlTypeFilter = new FilterControlTypeTests(controlType);
//create tree currentTestTypeRootNode for the control type
TreeNode controlTypeNode = new TreeNode(controlTypeFilter.ControlTypeName);
currentTestTypeRootNode.Nodes.Add(controlTypeNode);
//create priority subtree for the controlType
CreatePrioritySubtreesForTestType(controlTypeNode, new AndFilter(testFilter, controlTypeFilter), testType);
//if the currentRootNode has no children nodes then remove it
if (controlTypeNode.Nodes.Count == 0)
controlTypeNode.Remove();
}
}
else
{
if (testType == TestTypes.PatternTest)
{
//if PatternTest test type is required then let's get all supported patterns
//for the selected automation element. If we are showing all tests, not only for selected
//elements then let's get all automation element Patterns.
//for all grabbed Patterns let's create subtree with tests
IEnumerable<AutomationPattern> supportedPatterns;
if (this._scope == TestsScope.SelectedElementTests)
{
try
{
//get all supported patterns
supportedPatterns = this._selectedElement.GetSupportedPatterns();
}
catch (ElementNotAvailableException)
{
//is there is problem with the element then ignore his patterns
supportedPatterns = new AutomationPattern[0];
}
}
else
{
//let's get all automation technology patterns
supportedPatterns = AutomationHelper.GetAllAutomationPatterns();
}
//for each pattern let's create subtree
foreach (AutomationPattern pattern in supportedPatterns)
{
//create filter filtering automation tests testing this pattern
FilterPatternTests patternFilter = new FilterPatternTests(pattern);
//create tree currentRootNode for the pattern
TreeNode patternNode = new TreeNode(patternFilter.PatternName);
currentTestTypeRootNode.Nodes.Add(patternNode);
//create priority subtree for the pattern
CreatePrioritySubtreesForTestType(patternNode, new AndFilter(testFilter, patternFilter), testType);
//if the currentRootNode has no children nodes then remove it
if (patternNode.Nodes.Count == 0)
patternNode.Remove();
}
}
else
{
//if other TestType than ControlTests or PatternTests is required then
//create subtree for it
CreatePrioritySubtreesForTestType(currentTestTypeRootNode, testFilter, testType);
}
}
//if there are no children then remove the currentTestTypeRootNode
if (currentTestTypeRootNode.Nodes.Count == 0)
currentTestTypeRootNode.Remove();
}
/// <summary>
/// create subtree for currentRootNode according to the testType and testFilter
/// </summary>
private void CreatePrioritySubtreesForTestType(TreeNode node, AutomationTestsFilter testFilter, TestTypes testType)
{
//go thru all test priorities and create subtree for each
foreach (TestPriorities priority in Enum.GetValues(typeof(TestPriorities)))
{
if (priority != TestPriorities.None && (this._priorities & priority) == priority)
CreateTestPrioritySubtree(priority, testType, node, testFilter);
}
}
/// <summary>
/// create subtree for parentNode according to the testPriority, testType and testFilter
/// </summary>
private void CreateTestPrioritySubtree(TestPriorities testPriority, TestTypes testType, TreeNode parentNode, AutomationTestsFilter testFilter)
{
//create node for the priority
TreeNode priorityNode = new TreeNode(GetPriorityName(testPriority));
parentNode.Nodes.Add(priorityNode);
TreeNode currentRootNode = priorityNode;
//create filter for the priority
AndFilter priorityFilter = new AndFilter(new TestFilterPriority(testPriority), testFilter);
//for all filtered available automation tests lets create tree node
foreach (AutomationTest test in AutomationTestCollection.Filter(priorityFilter))
{
//lets make copy ot the test with only TestType and TestPriority belonging to this
//branch
AutomationTest testClone = new AutomationTest(test, testPriority, testType);
TreeNode testNode = new TreeNode(testClone.Name);
testNode.Tag = testClone;
currentRootNode.Nodes.Add(testNode);
}
//if no child currentTestTypeRootNode was added then remove priority currentTestTypeRootNode
if (currentRootNode.Nodes.Count == 0)
currentRootNode.Remove();
}
/// <summary>
/// returns user friendly name for testType
/// </summary>
private string GetTestTypeName(TestTypes testType)
{
string name;
switch (testType)
{
case TestTypes.AutomationElementTest: name = "Automation Element Tests"; break;
case TestTypes.PatternTest: name = "Pattern Tests"; break;
case TestTypes.ControlTest: name = "Control Tests"; break;
//case TestTypes.ScenarioTest: name = "Scenario Tests"; break;
default:
{
Debug.Fail("unexpected TestTypes value");
name = Enum.GetName(typeof(TestTypes), testType);
}
break;
}
return name;
}
/// <summary>
/// returns user friendly name for testPriority
/// </summary>
/// <param name="testPriority"></param>
/// <returns></returns>
private string GetPriorityName(TestPriorities testPriority)
{
string name;
switch (testPriority)
{
case TestPriorities.BuildVerificationTests: name = "Build Verification Tests"; break;
case TestPriorities.Priority0Tests: name = "Priority 0 Tests"; break;
case TestPriorities.Priority1Tests: name = "Priority 1 Tests"; break;
case TestPriorities.Priority2Tests: name = "Priority 2 Tests"; break;
case TestPriorities.Priority3Tests: name = "Priority 3 Tests"; break;
case TestPriorities.OnlyPriorityAllTests: name = "Priority All Tests"; break;
default:
{
Debug.Fail("unexpected TestPriorities value");
name = Enum.GetName(typeof(TestPriorities), testPriority);
}
break;
}
return name;
}
#endregion
/// <summary>
/// Causes firing RunTestRequired event
/// </summary>
protected virtual void OnRunTest()
{
if (this.RunTestRequired != null)
this.RunTestRequired(this, EventArgs.Empty);
}
/// <summary>
/// Causes firing RunTestOnAllChildrenRequired event
/// </summary>
protected virtual void OnRunTestOnAllChildren()
{
if (this.RunTestOnAllChildrenRequired != null)
this.RunTestOnAllChildrenRequired(this, EventArgs.Empty);
}
private void SetSelectedTest(TreeNode node)
{
SetSelectedNodeTransparentColor();
_testsTreeView.SelectedNode = node;
SetSelectedNodeActiveColor();
}
private void SetSelectedNodeActiveColor()
{
TreeNode selectedNode = _testsTreeView.SelectedNode;
if (selectedNode != null)
selectedNode.BackColor = Drawing.SystemColors.GradientActiveCaption;
}
private void SetSelectedNodeTransparentColor()
{
TreeNode selectedNode = _testsTreeView.SelectedNode;
if (selectedNode != null)
selectedNode.BackColor = Drawing.Color.Transparent;
}
#region events
private void _testsTreeView_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
SetSelectedNodeTransparentColor();
}
private void _testsTreeView_AfterSelect(object sender, TreeViewEventArgs e)
{
SetSelectedNodeActiveColor();
}
// whatever mouse button pressed, it will select the currentTestTypeRootNode
private void _testsTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
//we will select the currentTestTypeRootNode which was clicked
this._testsTreeView.SelectedNode = e.Node;
}
private void runTestToolStripMenuItem_Click(object sender, EventArgs e)
{
OnRunTest();
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Threading;
using System.Threading;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Security;
using System.Security.Permissions;
using MS.Internal.KnownBoxes;
namespace System.Windows.Input
{
/// <summary>
/// FocusManager define attached property used for tracking the FocusedElement with a focus scope
/// </summary>
public static class FocusManager
{
#region Public Events
/// <summary>
/// GotFocus event
/// </summary>
public static readonly RoutedEvent GotFocusEvent = EventManager.RegisterRoutedEvent("GotFocus", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(FocusManager));
/// <summary>
/// Adds a handler for the GotFocus attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddGotFocusHandler(DependencyObject element, RoutedEventHandler handler)
{
UIElement.AddHandler(element, GotFocusEvent, handler);
}
/// <summary>
/// Removes a handler for the GotFocus attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveGotFocusHandler(DependencyObject element, RoutedEventHandler handler)
{
UIElement.RemoveHandler(element, GotFocusEvent, handler);
}
/// <summary>
/// LostFocus event
/// </summary>
public static readonly RoutedEvent LostFocusEvent = EventManager.RegisterRoutedEvent("LostFocus", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(FocusManager));
/// <summary>
/// Adds a handler for the LostFocus attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be added</param>
public static void AddLostFocusHandler(DependencyObject element, RoutedEventHandler handler)
{
UIElement.AddHandler(element, LostFocusEvent, handler);
}
/// <summary>
/// Removes a handler for the LostFocus attached event
/// </summary>
/// <param name="element">UIElement or ContentElement that listens to this event</param>
/// <param name="handler">Event Handler to be removed</param>
public static void RemoveLostFocusHandler(DependencyObject element, RoutedEventHandler handler)
{
UIElement.RemoveHandler(element, LostFocusEvent, handler);
}
#endregion Public Events
#region Public Properties
#region FocusedElement property
/// <summary>
/// The DependencyProperty for the FocusedElement property. This internal property tracks IsActive
/// element ref inside TrackFocus
/// Default Value: null
/// </summary>
public static readonly DependencyProperty FocusedElementProperty =
DependencyProperty.RegisterAttached(
"FocusedElement",
typeof(IInputElement),
typeof(FocusManager),
new PropertyMetadata(new PropertyChangedCallback(OnFocusedElementChanged)));
#endregion FocusedElement property
#region IsFocusScope Property
/// <summary>
/// The DependencyProperty for the IsFocusScope property.
/// This property is used to mark the special containers (like Window, Menu) so they can
/// keep track of the FocusedElement element inside the container. Once focus is set
/// on the container - it is delegated to the FocusedElement element
/// Default Value: false
/// </summary>
public static readonly DependencyProperty IsFocusScopeProperty
= DependencyProperty.RegisterAttached("IsFocusScope", typeof(bool), typeof(FocusManager),
new PropertyMetadata(BooleanBoxes.FalseBox));
#endregion IsFocusScope Property
#endregion
#region Public static methods
/// <summary>
/// Return the property value of FocusedElement property.
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static IInputElement GetFocusedElement(DependencyObject element)
{
return GetFocusedElement(element, false);
}
/// <summary>
/// Return the property value of FocusedElement property. The return value is validated
/// to be in the subtree of element. If FocusedElement element is not a descendant of element this method return null
/// </summary>
/// <param name="element"></param>
/// <param name="validate"></param>
/// <returns></returns>
/// <SecurityNote>
/// Critical: This code accesses PresentationSource.CriticalFromVisual which is critical
/// TreatAsSafe: This code does not expose it and simply uses it for determining if the FocusedElement is valid
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal static IInputElement GetFocusedElement(DependencyObject element, bool validate)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
DependencyObject focusedElement = (DependencyObject) element.GetValue(FocusedElementProperty);
// Validate FocusedElement wrt to its FocusScope. If the two do not belong to the same PresentationSource
// then sever this link between them. The classic scenario for this is when an element with logical focus is
// dragged out into a floating widow. We want to prevent the MainWindow (focus scope) to point to the
// element in the floating window as its logical FocusedElement.
if (validate && focusedElement != null)
{
DependencyObject focusScope = element;
if (PresentationSource.CriticalFromVisual(focusScope) != PresentationSource.CriticalFromVisual(focusedElement))
{
SetFocusedElement(focusScope, null);
focusedElement = null;
}
}
return (IInputElement)focusedElement;
}
/// <summary>
/// Set FocusedElement property for element.
/// </summary>
/// <param name="element"></param>
/// <param name="value"></param>
public static void SetFocusedElement(DependencyObject element, IInputElement value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(FocusedElementProperty, value);
}
/// <summary>
/// Writes the attached property IsFocusScope to the given element.
/// </summary>
/// <param name="element">The element to which to write the attached property.</param>
/// <param name="value">The property value to set</param>
public static void SetIsFocusScope(DependencyObject element, bool value)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
element.SetValue(IsFocusScopeProperty, value);
}
/// <summary>
/// Reads the attached property IsFocusScope from the given element.
/// </summary>
/// <param name="element">The element from which to read the attached property.</param>
/// <returns>The property's value.</returns>
public static bool GetIsFocusScope(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return (bool)element.GetValue(IsFocusScopeProperty);
}
/// <summary>
/// Find the closest visual ancestor that has IsFocusScope set to true
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static DependencyObject GetFocusScope(DependencyObject element)
{
if (element == null)
{
throw new ArgumentNullException("element");
}
return _GetFocusScope(element);
}
#endregion Public methods
#region private implementation
//
private static void OnFocusedElementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
IInputElement newFocusedElement = (IInputElement)e.NewValue;
DependencyObject oldVisual = (DependencyObject)e.OldValue;
DependencyObject newVisual = (DependencyObject)e.NewValue;
if (oldVisual != null)
{
oldVisual.ClearValue(UIElement.IsFocusedPropertyKey);
}
if (newVisual != null)
{
// set IsFocused on the element. The element may redirect Keyboard focus
// in response to this (e.g. Editable ComboBox redirects to the
// child TextBox), so detect whether this happens.
DependencyObject oldFocus = Keyboard.FocusedElement as DependencyObject;
newVisual.SetValue(UIElement.IsFocusedPropertyKey, BooleanBoxes.TrueBox);
DependencyObject newFocus = Keyboard.FocusedElement as DependencyObject;
// set the Keyboard focus to the new element, provided that
// a) the element didn't already set Keyboard focus
// b) Keyboard focus is not already on the new element
// c) the new element is within the same focus scope as the current
// holder (if any) of Keyboard focus
if (oldFocus == newFocus && newVisual != newFocus &&
(newFocus == null || GetRoot(newVisual) == GetRoot(newFocus)))
{
Keyboard.Focus(newFocusedElement);
}
}
/*
if (!_currentlyUpdatingTree)
{
_currentlyUpdatingTree = true;
IInputElement newFocusedElement = (IInputElement) newValue;
Visual oldVisual = GetNearestVisual(args.OldValue);
Visual newVisual = GetNearestVisual(args.NewValue);
if (oldVisual != null)
{
oldVisual.ClearValue(UIElement.IsFocusedPropertyKey);
// reverse-inherit: clear the property on all parents that aren't also in the
// new focused element ancestry
while (oldVisual != null)
{
oldVisual.ClearValue(FocusedElementProperty);
oldVisual = VisualTreeHelper.GetParent(oldVisual);
if ((oldVisual == newVisual) || oldVisual.IsAncestorOf(newVisual))
{
// only walk up until you reach a common parent -- the new value walk will take care of the rest
break;
}
}
}
if (newVisual != null)
{
newVisual.SetValue(UIElement.IsFocusedPropertyKey, BooleanBoxes.TrueBox);
// reverse-inherit: set the property on all parents
while (newVisual != null)
{
newVisual.SetValue(FocusedElementProperty, newFocusedElement);
newVisual = VisualTreeHelper.GetParent(newVisual);
}
// Set Keyboard focus to the element if not already focused && current focus is within the current focus scope
DependencyObject currentFocus = Keyboard.FocusedElement as DependencyObject;
if ((currentFocus == null) &&
(newVisual != currentFocus) &&
(GetRoot(newVisual) == GetRoot(currentFocus)))
{
Keyboard.Focus(newFocusedElement);
}
}
_currentlyUpdatingTree = false;
}
*/
}
/*
private static Visual GetNearestVisual(object value)
{
Visual visual = null;
if (value != null)
{
visual = value as Visual;
if (visual == null)
{
ContentElement ce = value as ContentElement;
if (ce != null)
{
visual = ce.GetUIParent() as Visual;
}
}
}
return visual;
}
*/
private static DependencyObject GetRoot(DependencyObject element)
{
if (element == null)
return null;
DependencyObject parent = null;
DependencyObject dependencyObject = element;
ContentElement ce = element as ContentElement;
if (ce != null)
dependencyObject = ce.GetUIParent();
while (dependencyObject != null)
{
parent = dependencyObject;
dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
}
return parent;
}
// Walk up the parent chain to find the closest element with IsFocusScope=true
private static DependencyObject _GetFocusScope(DependencyObject d)
{
if (d == null)
return null;
if ((bool)d.GetValue(IsFocusScopeProperty))
return d;
// Step 1: Walk up the logical tree
UIElement uiElement = d as UIElement;
if (uiElement != null)
{
DependencyObject logicalParent = uiElement.GetUIParentCore();
if (logicalParent != null)
{
return GetFocusScope(logicalParent);
}
}
else
{
ContentElement ce = d as ContentElement;
if (ce != null)
{
DependencyObject logicalParent = ce.GetUIParent(true);
if (logicalParent != null)
{
return _GetFocusScope(logicalParent);
}
}
else
{
UIElement3D uiElement3D = d as UIElement3D;
if (uiElement3D != null)
{
DependencyObject logicalParent = uiElement3D.GetUIParentCore();
if (logicalParent != null)
{
return GetFocusScope(logicalParent);
}
}
}
}
// Step 2: Walk up the visual tree
if (d is Visual || d is Visual3D)
{
DependencyObject visualParent = VisualTreeHelper.GetParent(d);
if (visualParent != null)
{
return _GetFocusScope(visualParent);
}
}
// If visual and logical parent is null - then the element is implicit focus scope
return d;
}
#endregion private implementation
#region private data
private static readonly UncommonField<bool> IsFocusedElementSet = new UncommonField<bool>();
private static readonly UncommonField<WeakReference> FocusedElementWeakCacheField = new UncommonField<WeakReference>();
private static readonly UncommonField<bool> IsFocusedElementCacheValid = new UncommonField<bool>();
private static readonly UncommonField<WeakReference> FocusedElementCache = new UncommonField<WeakReference>();
// private static bool _currentlyUpdatingTree = false;
#endregion private data
}
}
| |
namespace Microsoft.Azure.Management.StorSimple8000Series
{
using Azure;
using Management;
using Rest;
using 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>
/// CloudAppliancesOperations operations.
/// </summary>
internal partial class CloudAppliancesOperations : IServiceOperations<StorSimple8000SeriesManagementClient>, ICloudAppliancesOperations
{
/// <summary>
/// Initializes a new instance of the CloudAppliancesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal CloudAppliancesOperations(StorSimple8000SeriesManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the StorSimple8000SeriesManagementClient
/// </summary>
public StorSimple8000SeriesManagementClient Client { get; private set; }
/// <summary>
/// Lists supported cloud appliance models and supported configurations.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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<IEnumerable<CloudApplianceConfiguration>>> ListSupportedConfigurationsWithHttpMessagesAsync(string resourceGroupName, string managerName, 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 (managerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "managerName");
}
if (managerName != null)
{
if (managerName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "managerName", 50);
}
if (managerName.Length < 2)
{
throw new ValidationException(ValidationRules.MinLength, "managerName", 2);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("managerName", managerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListSupportedConfigurations", 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.StorSimple/managers/{managerName}/cloudApplianceConfigurations").ToString();
_url = _url.Replace("{subscriptionId}", Client.SubscriptionId);
_url = _url.Replace("{resourceGroupName}", resourceGroupName);
_url = _url.Replace("{managerName}", managerName);
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Client.ApiVersion));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new 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 (Newtonsoft.Json.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<IEnumerable<CloudApplianceConfiguration>>();
_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<Page1<CloudApplianceConfiguration>>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.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>
/// Provisions cloud appliance.
/// </summary>
/// <param name='parameters'>
/// The cloud appliance
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> ProvisionWithHttpMessagesAsync(CloudAppliance parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginProvisionWithHttpMessagesAsync(parameters, resourceGroupName, managerName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Provisions cloud appliance.
/// </summary>
/// <param name='parameters'>
/// The cloud appliance
/// </param>
/// <param name='resourceGroupName'>
/// The resource group name
/// </param>
/// <param name='managerName'>
/// The manager name
/// </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="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> BeginProvisionWithHttpMessagesAsync(CloudAppliance parameters, string resourceGroupName, string managerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (managerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "managerName");
}
if (managerName != null)
{
if (managerName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "managerName", 50);
}
if (managerName.Length < 2)
{
throw new ValidationException(ValidationRules.MinLength, "managerName", 2);
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("managerName", managerName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginProvision", 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.StorSimple/managers/{managerName}/provisionCloudAppliance").ToString();
_url = _url.Replace("{subscriptionId}", Client.SubscriptionId);
_url = _url.Replace("{resourceGroupName}", resourceGroupName);
_url = _url.Replace("{managerName}", managerName);
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Client.ApiVersion));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new 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();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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 Bridge.Test.NUnit;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
namespace Bridge.ClientTest.IO
{
[Category(Constants.MODULE_IO)]
[TestFixture(TestNameFormat = "StreamMethods - {0}")]
public class StreamMethods
{
protected virtual Stream CreateStream()
{
return new MemoryStream();
}
protected virtual Stream CreateStream(int bufferSize)
{
return new MemoryStream(new byte[bufferSize]);
}
[Test]
public void Synchronized_NewObject()
{
using (Stream str = CreateStream())
{
using (Stream synced = Stream.Synchronized(str))
{
synced.Write(new byte[] { 1 }, 0, 1);
Assert.True(1 == str.Length);
}
}
}
[Test]
public void MemoryStreamSeekStress()
{
var ms1 = CreateStream();
SeekTest(ms1, false);
}
[Test]
public void MemoryStreamSeekStressWithInitialBuffer()
{
var ms1 = CreateStream(1024);
SeekTest(ms1, false);
}
[Test]
public void MemoryStreamStress()
{
var ms1 = CreateStream();
StreamTest(ms1, false);
}
public static void SeekTest(Stream stream, Boolean fSuppres)
{
long lngPos;
byte btValue;
stream.Position = 0;
Assert.True(0 == stream.Position);
int length = 1 << 10; //fancy way of writing 2 to the pow 10
byte[] btArr = new byte[length];
for (int i = 0; i < btArr.Length; i++)
btArr[i] = unchecked((byte)i);
if (stream.CanWrite)
stream.Write(btArr, 0, btArr.Length);
else
stream.Position = btArr.Length;
Assert.True(btArr.Length == stream.Position);
lngPos = stream.Seek(0, SeekOrigin.Begin);
Assert.True(0 == lngPos);
Assert.True(0 == stream.Position);
for (int i = 0; i < btArr.Length; i++)
{
if (stream.CanWrite)
{
btValue = (byte)stream.ReadByte();
Assert.AreEqual(btArr[i], btValue);
}
else
{
stream.Seek(1, SeekOrigin.Current);
}
Assert.True((i + 1) == stream.Position);
}
Assert.Throws<IOException>(() => stream.Seek(-5, SeekOrigin.Begin));
lngPos = stream.Seek(5, SeekOrigin.Begin);
Assert.True(5 == lngPos);
Assert.True(5 == stream.Position);
lngPos = stream.Seek(5, SeekOrigin.End);
Assert.True((length + 5) == lngPos);
Assert.Throws<IOException>(() => stream.Seek(-(btArr.Length + 1), SeekOrigin.End));
lngPos = stream.Seek(-5, SeekOrigin.End);
Assert.True(btArr.Length - 5 == lngPos);
Assert.True((btArr.Length - 5) == stream.Position);
lngPos = stream.Seek(0, SeekOrigin.End);
Assert.True(btArr.Length == stream.Position);
for (int i = btArr.Length; i > 0; i--)
{
stream.Seek(-1, SeekOrigin.Current);
Assert.True(i - 1 == stream.Position);
}
Assert.Throws<IOException>(() => stream.Seek(-1, SeekOrigin.Current));
}
public static void StreamTest(Stream stream, Boolean fSuppress)
{
string strValue;
int iValue;
//[] We will first use the stream's 2 writing methods
int iLength = 1 << 10;
stream.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < iLength; i++)
stream.WriteByte(unchecked((byte)i));
byte[] btArr = new byte[iLength];
for (int i = 0; i < iLength; i++)
btArr[i] = unchecked((byte)i);
stream.Write(btArr, 0, iLength);
//we will write many things here using a binary writer
BinaryWriter bw1 = new BinaryWriter(stream);
bw1.Write(false);
bw1.Write(true);
for (int i = 0; i < 10; i++)
{
bw1.Write((byte)i);
bw1.Write((sbyte)i);
bw1.Write((short)i);
bw1.Write((char)i);
bw1.Write((UInt16)i);
bw1.Write(i);
bw1.Write((uint)i);
bw1.Write((Int64)i);
bw1.Write((ulong)i);
bw1.Write((float)i);
bw1.Write((double)i);
}
//Some strings, chars and Bytes
char[] chArr = new char[iLength];
for (int i = 0; i < iLength; i++)
chArr[i] = (char)i;
bw1.Write(chArr);
bw1.Write(chArr, 512, 512);
bw1.Write(new string(chArr));
bw1.Write(new string(chArr));
//[] we will now read
stream.Seek(0, SeekOrigin.Begin);
for (int i = 0; i < iLength; i++)
{
Assert.AreEqual(i % 256, stream.ReadByte());
}
btArr = new byte[iLength];
stream.Read(btArr, 0, iLength);
for (int i = 0; i < iLength; i++)
{
Assert.AreEqual(unchecked((byte)i), btArr[i]);
}
//Now, for the binary reader
BinaryReader br1 = new BinaryReader(stream);
Assert.False(br1.ReadBoolean());
Assert.True(br1.ReadBoolean());
for (int i = 0; i < 10; i++)
{
Assert.AreEqual((byte)i, br1.ReadByte());
Assert.AreEqual((sbyte)i, br1.ReadSByte());
Assert.AreEqual((short)i, br1.ReadInt16());
Assert.AreEqual((char)i, br1.ReadChar());
Assert.AreEqual((UInt16)i, br1.ReadUInt16());
Assert.AreEqual(i, br1.ReadInt32());
Assert.AreEqual((uint)i, br1.ReadUInt32());
Assert.True((Int64)i == br1.ReadInt64());
Assert.True((ulong)i == br1.ReadUInt64());
Assert.AreEqual((float)i, br1.ReadSingle());
Assert.AreEqual((double)i, br1.ReadDouble());
}
chArr = br1.ReadChars(iLength);
for (int i = 0; i < iLength; i++)
{
Assert.AreEqual((char)i, chArr[i]);
}
chArr = new char[512];
chArr = br1.ReadChars(iLength / 2);
for (int i = 0; i < iLength / 2; i++)
{
Assert.AreEqual((char)(iLength / 2 + i), chArr[i]);
}
chArr = new char[iLength];
for (int i = 0; i < iLength; i++)
chArr[i] = (char)i;
strValue = br1.ReadString();
Assert.AreEqual(new string(chArr), strValue);
strValue = br1.ReadString();
Assert.AreEqual(new string(chArr), strValue);
stream.Seek(1, SeekOrigin.Current); // In the original test, success here would end the test
//[] we will do some async tests here now
stream.Position = 0;
btArr = new byte[iLength];
for (int i = 0; i < iLength; i++)
btArr[i] = unchecked((byte)(i + 5));
stream.Write(btArr, 0, btArr.Length);
stream.Position = 0;
for (int i = 0; i < iLength; i++)
{
Assert.AreEqual(unchecked((byte)(i + 5)), stream.ReadByte());
}
//we will read asynchronously
stream.Position = 0;
byte[] compArr = new byte[iLength];
iValue = stream.Read(compArr, 0, compArr.Length);
Assert.AreEqual(btArr.Length, iValue);
for (int i = 0; i < iLength; i++)
{
Assert.AreEqual(compArr[i], btArr[i]);
}
}
[Test]
public void FlushAsyncTest()
{
byte[] data = Enumerable.Range(0, 8000).Select(i => unchecked((byte)i)).ToArray();
Stream stream = CreateStream();
for (int i = 0; i < 4; i++)
{
stream.Write(data, 2000 * i, 2000);
stream.Flush();
}
stream.Position = 0;
byte[] output = new byte[data.Length];
int bytesRead, totalRead = 0;
while ((bytesRead = stream.Read(output, totalRead, data.Length - totalRead)) > 0)
totalRead += bytesRead;
Assert.AreEqual(data, output);
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Cassandra.DataStax.Graph
{
/// <summary>
/// The default graph options to use for a DSE cluster.
/// <para>
/// These options will be used for all graph statements sent to the cluster, unless they have been explicitly overridden
/// at the statement level.
/// </para>
/// </summary>
public class GraphOptions
{
/// <summary>
/// Default value for graph language.
/// </summary>
public const string DefaultLanguage = GraphOptions.GremlinGroovy;
/// <summary>
/// Default value for graph language.
/// </summary>
internal const string BytecodeJson = "bytecode-json";
internal const string GremlinGroovy = "gremlin-groovy";
/// <summary>
/// Default value for graph source.
/// </summary>
public const string DefaultSource = "g";
/// <summary>
/// Default value for read timeout.
/// </summary>
public const int DefaultReadTimeout = Timeout.Infinite;
private static class PayloadKey
{
public const string Results = "graph-results";
public const string Language = "graph-language";
public const string Name = "graph-name";
public const string Source = "graph-source";
public const string ReadConsistencyLevel = "graph-read-consistency";
public const string WriteConsitencyLevel = "graph-write-consistency";
public const string RequestTimeout = "request-timeout";
}
private volatile IDictionary<string, byte[]> _defaultPayload;
private volatile string _language = GraphOptions.DefaultLanguage;
private volatile string _name;
private volatile string _source = GraphOptions.DefaultSource;
private long _readConsistencyLevel = long.MinValue;
private long _writeConsistencyLevel = long.MinValue;
private volatile int _readTimeout = GraphOptions.DefaultReadTimeout;
private volatile object _nullableGraphProtocol = null;
/// <summary>
/// The consistency levels names that are different from ConsistencyLevel.ToString().ToUpper()
/// </summary>
private static readonly IDictionary<ConsistencyLevel, string> ConsistencyLevelNames =
new Dictionary<ConsistencyLevel, string>
{
{ ConsistencyLevel.LocalQuorum, "LOCAL_QUORUM" },
{ ConsistencyLevel.EachQuorum, "EACH_QUORUM" },
{ ConsistencyLevel.LocalSerial, "LOCAL_SERIAL" },
{ ConsistencyLevel.LocalOne, "LOCAL_ONE" }
};
/// <summary>
/// Gets the graph language to use in graph queries. The default is <see cref="DefaultLanguage"/>.
/// </summary>
public string Language
{
get { return _language; }
}
/// <summary>
/// Gets the graph name to use in graph queries.
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Gets the consistency level used for read queries
/// </summary>
public ConsistencyLevel? ReadConsistencyLevel
{
get
{
//4 bytes for consistency representation and 1 bit for null flag
long value = Interlocked.Read(ref _readConsistencyLevel);
if (value == long.MinValue)
{
return null;
}
return (ConsistencyLevel) value;
}
}
/// <summary>
/// Gets the value that overrides the
/// <see href="http://docs.datastax.com/en/drivers/csharp/3.0/html/P_Cassandra_SocketOptions_ReadTimeoutMillis.htm">
/// default per-host read timeout</see> in milliseconds for all graph queries.
/// <para>Default: <c>Timeout.Infinite</c> (-1).</para>
/// </summary>
/// <seealso cref="SetReadTimeoutMillis"/>
public int ReadTimeoutMillis
{
get { return _readTimeout; }
}
/// <summary>
/// Gets the graph traversal source name in graph queries.
/// </summary>
public string Source
{
get { return _source; }
}
/// <summary>
/// If not explicitly specified, the following rules apply:
/// <list type=""></list>
/// <list type="bullet">
/// <item>
/// <description>If <see cref="Name"/> is specified and is a Core graph,
/// set <see cref="GraphProtocol.GraphSON3"/>.</description>
/// </item>
/// <item>
/// <description>If <see cref="Language"/> is gremlin-groovy,
/// set <see cref="GraphProtocol.GraphSON1"/>.</description>
/// </item>
/// <item>
/// <description>Otherwise set <see cref="GraphProtocol.GraphSON2"/>.</description>
/// </item>
/// </list>
/// </summary>
public GraphProtocol? GraphProtocolVersion => (GraphProtocol?) _nullableGraphProtocol;
/// <summary>
/// Gets the consistency level used for read queries
/// </summary>
public ConsistencyLevel? WriteConsistencyLevel
{
get
{
//4 bytes for consistency representation and 1 bit for null flag
long value = Interlocked.Read(ref _writeConsistencyLevel);
if (value == long.MinValue)
{
return null;
}
return (ConsistencyLevel)value;
}
}
/// <summary>
/// Creates a new instance of <see cref="GraphOptions"/>.
/// </summary>
public GraphOptions()
{
RebuildDefaultPayload();
}
/// <summary>
/// Clone a graph options object, replacing the graph protocol version.
/// </summary>
internal GraphOptions(GraphOptions other, GraphProtocol version)
{
_language = other._language;
_name = other._name;
_source = other._source;
_readConsistencyLevel = Interlocked.Read(ref other._readConsistencyLevel);
_writeConsistencyLevel = Interlocked.Read(ref other._writeConsistencyLevel);
_readTimeout = other._readTimeout;
_nullableGraphProtocol = version;
RebuildDefaultPayload();
}
internal bool IsAnalyticsQuery(IGraphStatement statement)
{
return (statement.GraphSource ?? Source) == "a";
}
/// <summary>
/// Sets the graph language to use in graph queries.
/// If you don't call this method, it defaults to <see cref="DefaultLanguage"/>.
/// </summary>
/// <param name="language"></param>
/// <returns></returns>
public GraphOptions SetLanguage(string language)
{
_language = language ?? GraphOptions.DefaultLanguage;
RebuildDefaultPayload();
return this;
}
/// <summary>
/// Sets the graph name to use in graph queries.
/// </summary>
public GraphOptions SetName(string name)
{
_name = name;
RebuildDefaultPayload();
return this;
}
/// <summary>
/// Sets the graph protocol version to use in graph queries. See <see cref="GraphProtocolVersion"/>.
/// </summary>
public GraphOptions SetGraphProtocolVersion(GraphProtocol version)
{
_nullableGraphProtocol = version;
RebuildDefaultPayload();
return this;
}
/// <summary>
/// Sets the consistency level for the read graph queries.
/// </summary>
/// <param name="consistency">The consistency level to use in read graph queries.</param>
public GraphOptions SetReadConsistencyLevel(ConsistencyLevel consistency)
{
Interlocked.Exchange(ref _readConsistencyLevel, (long)consistency);
RebuildDefaultPayload();
return this;
}
/// <summary>
/// Sets the default per-host read timeout in milliseconds for all graph queries.
/// <para>
/// When setting a value of less than or equals to zero (<see cref="Timeout.Infinite"/>),
/// it will use an infinite timeout.
/// </para>
/// </summary>
public GraphOptions SetReadTimeoutMillis(int timeout)
{
_readTimeout = timeout;
RebuildDefaultPayload();
return this;
}
/// <summary>
/// Sets the graph traversal source name to use in graph queries.
/// If you don't call this method, it defaults to <see cref="DefaultSource"/>.
/// </summary>
public GraphOptions SetSource(string source)
{
_source = source ?? GraphOptions.DefaultSource;
RebuildDefaultPayload();
return this;
}
/// <summary>
/// Sets the graph source to the server-defined analytic traversal source ('a')
/// </summary>
public GraphOptions SetSourceAnalytics()
{
return SetSource("a");
}
/// <summary>
/// Sets the consistency level for the write graph queries.
/// </summary>
/// <param name="consistency">The consistency level to use in write graph queries.</param>
public GraphOptions SetWriteConsistencyLevel(ConsistencyLevel consistency)
{
Interlocked.Exchange(ref _writeConsistencyLevel, (long)consistency);
RebuildDefaultPayload();
return this;
}
internal IDictionary<string, byte[]> BuildPayload(IGraphStatement statement)
{
if (statement.GraphProtocolVersion == null && GraphProtocolVersion == null)
{
throw new DriverInternalError(
"Could not resolve graph protocol version. This is a bug, please report.");
}
if (statement.GraphLanguage == null && statement.GraphName == null &&
statement.GraphSource == null && statement.ReadTimeoutMillis == 0
&& statement.GraphProtocolVersion == null)
{
if (!statement.IsSystemQuery || !_defaultPayload.ContainsKey(PayloadKey.Name))
{
//The user has not used the graph settings at statement level
//Or is a system query but there isn't a name defined at GraphOptions level
return _defaultPayload;
}
}
var payload = new Dictionary<string, byte[]>();
Add(payload, PayloadKey.Results, statement.GraphProtocolVersion?.GetInternalRepresentation(), null);
Add(payload, PayloadKey.Language, statement.GraphLanguage, null);
if (!statement.IsSystemQuery)
{
Add(payload, PayloadKey.Name, statement.GraphName, null);
}
Add(payload, PayloadKey.Source, statement.GraphSource, null);
Add(payload, PayloadKey.ReadConsistencyLevel,
statement.GraphReadConsistencyLevel == null ? null : GraphOptions.GetConsistencyName(statement.GraphReadConsistencyLevel.Value), null);
Add(payload, PayloadKey.WriteConsitencyLevel,
statement.GraphWriteConsistencyLevel == null ? null : GraphOptions.GetConsistencyName(statement.GraphWriteConsistencyLevel.Value), null);
var readTimeout = statement.ReadTimeoutMillis != 0 ? statement.ReadTimeoutMillis : ReadTimeoutMillis;
if (readTimeout > 0)
{
// only non-infinite timeouts needs to be included in the payload
Add<long>(payload, PayloadKey.RequestTimeout, statement.ReadTimeoutMillis, 0, GraphOptions.ToBuffer);
}
return payload;
}
private void Add<T>(IDictionary<string, byte[]> payload, string key, T value, T empty, Func<T, byte[]> converter = null)
{
if (converter == null)
{
converter = v => GraphOptions.ToUtf8Buffer((string)(object)v);
}
byte[] payloadValue;
if (value != null && !value.Equals(empty))
{
payloadValue = converter(value);
}
else
{
_defaultPayload.TryGetValue(key, out payloadValue);
}
if (payloadValue == null)
{
return;
}
payload.Add(key, payloadValue);
}
private void RebuildDefaultPayload()
{
var payload = new Dictionary<string, byte[]>
{
{ PayloadKey.Language, GraphOptions.ToUtf8Buffer(_language) },
{ PayloadKey.Source, GraphOptions.ToUtf8Buffer(_source) }
};
if (_name != null)
{
payload.Add(PayloadKey.Name, GraphOptions.ToUtf8Buffer(_name));
}
var readConsistencyLevel = ReadConsistencyLevel;
if (readConsistencyLevel != null)
{
payload.Add(PayloadKey.ReadConsistencyLevel, GraphOptions.ToUtf8Buffer(
GraphOptions.GetConsistencyName(readConsistencyLevel.Value)));
}
var writeConsistencyLevel = WriteConsistencyLevel;
if (writeConsistencyLevel != null)
{
payload.Add(PayloadKey.WriteConsitencyLevel, GraphOptions.ToUtf8Buffer(
GraphOptions.GetConsistencyName(writeConsistencyLevel.Value)));
}
if (ReadTimeoutMillis > 0)
{
payload.Add(PayloadKey.RequestTimeout, GraphOptions.ToBuffer(ReadTimeoutMillis));
}
if (GraphProtocolVersion != null)
{
payload.Add(
PayloadKey.Results,
GraphOptions.ToUtf8Buffer(GraphProtocolVersion.Value.GetInternalRepresentation()));
}
_defaultPayload = payload;
}
private static string GetConsistencyName(ConsistencyLevel consistency)
{
if (!GraphOptions.ConsistencyLevelNames.TryGetValue(consistency, out string name))
{
//If not defined, use upper case representation
name = consistency.ToString().ToUpperInvariant();
}
return name;
}
private static byte[] ToUtf8Buffer(string value)
{
return Encoding.UTF8.GetBytes(value);
}
private static byte[] ToBuffer(long value)
{
var serializer = Serialization.TypeSerializer.PrimitiveLongSerializer;
return serializer.Serialize((ushort) Cluster.MaxProtocolVersion, value);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GvrAudio.cs" company="Google Inc.">
// 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 UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
/// This is the main GVR audio class that communicates with the native code implementation of
/// the audio system. Native functions of the system can only be called through this class to
/// preserve the internal system functionality. Public function calls are *not* thread-safe.
#if UNITY_2017_1_OR_NEWER
[System.Obsolete("GvrAudio is deprecated. Please upgrade to Resonance Audio (https://developers.google.com/resonance-audio/migrate).")]
#endif // UNITY_2017_1_OR_NEWER
public static class GvrAudio
{
/// Audio system rendering quality.
public enum Quality
{
/// Stereo-only rendering
Stereo = 0,
/// Low quality binaural rendering (first-order HRTF)
Low = 1,
/// High quality binaural rendering (third-order HRTF)
High = 2,
}
/// Native audio spatializer effect data.
public enum SpatializerData
{
/// ID.
Id = 0,
/// Spatializer type.
Type = 1,
/// Number of input channels.
NumChannels = 2,
/// Soundfield channel set.
ChannelSet = 3,
/// Gain.
Gain = 4,
/// Computed distance attenuation.
DistanceAttenuation = 5,
/// Minimum distance for distance-based attenuation.
MinDistance = 6,
/// Should zero out the output buffer?
ZeroOutput = 7,
}
/// Native audio spatializer type.
public enum SpatializerType
{
/// 3D sound object.
Source = 0,
/// First-order ambisonic soundfield.
Soundfield = 1
}
/// System sampling rate.
public static int SampleRate
{
get { return sampleRate; }
}
private static int sampleRate = -1;
/// System number of output channels.
public static int NumChannels
{
get { return numChannels; }
}
private static int numChannels = -1;
/// System number of frames per buffer.
public static int FramesPerBuffer
{
get { return framesPerBuffer; }
}
private static int framesPerBuffer = -1;
/// Initializes the audio system with the current audio configuration.
/// @note This should only be called from the main Unity thread.
public static void Initialize(GvrAudioListener listener, Quality quality)
{
if (!initialized)
{
// Initialize the audio system.
AudioConfiguration config = AudioSettings.GetConfiguration();
sampleRate = config.sampleRate;
numChannels = (int)config.speakerMode;
framesPerBuffer = config.dspBufferSize;
if (numChannels != (int)AudioSpeakerMode.Stereo)
{
Debug.LogError("Only 'Stereo' speaker mode is supported by GVR Audio.");
return;
}
Initialize((int)quality, sampleRate, numChannels, framesPerBuffer);
listenerTransform = listener.transform;
initialized = true;
}
else if (listener.transform != listenerTransform)
{
Debug.LogError("Only one GvrAudioListener component is allowed in the scene.");
GvrAudioListener.Destroy(listener);
}
}
/// Shuts down the audio system.
/// @note This should only be called from the main Unity thread.
public static void Shutdown(GvrAudioListener listener)
{
if (initialized && listener.transform == listenerTransform)
{
initialized = false;
Shutdown();
sampleRate = -1;
numChannels = -1;
framesPerBuffer = -1;
listenerTransform = null;
}
}
/// Updates the audio listener.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioListener(float globalGainDb, LayerMask occlusionMask)
{
if (initialized)
{
occlusionMaskValue = occlusionMask.value;
SetListenerGain(ConvertAmplitudeFromDb(globalGainDb));
}
}
/// Creates a new first-order ambisonic soundfield with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioSoundfield()
{
int soundfieldId = -1;
if (initialized)
{
soundfieldId = CreateSoundfield(numFoaChannels);
}
return soundfieldId;
}
/// Updates the |soundfield| with given |id| and its properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioSoundfield(int id, GvrAudioSoundfield soundfield)
{
if (initialized)
{
SetSourceBypassRoomEffects(id, soundfield.bypassRoomEffects);
}
}
/// Creates a new audio source with a unique id.
/// @note This should only be called from the main Unity thread.
public static int CreateAudioSource(bool hrtfEnabled)
{
int sourceId = -1;
if (initialized)
{
sourceId = CreateSoundObject(hrtfEnabled);
}
return sourceId;
}
/// Destroys the audio source with given |id|.
/// @note This should only be called from the main Unity thread.
public static void DestroyAudioSource(int id)
{
if (initialized)
{
DestroySource(id);
}
}
/// Updates the audio |source| with given |id| and its properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioSource(int id, GvrAudioSource source, float currentOcclusion)
{
if (initialized)
{
SetSourceBypassRoomEffects(id, source.bypassRoomEffects);
SetSourceDirectivity(id, source.directivityAlpha, source.directivitySharpness);
SetSourceListenerDirectivity(id, source.listenerDirectivityAlpha,
source.listenerDirectivitySharpness);
SetSourceOcclusionIntensity(id, currentOcclusion);
}
}
/// Updates the room effects of the environment with given |room| properties.
/// @note This should only be called from the main Unity thread.
public static void UpdateAudioRoom(GvrAudioRoom room, bool roomEnabled)
{
// Update the enabled rooms list.
if (roomEnabled)
{
if (!enabledRooms.Contains(room))
{
enabledRooms.Add(room);
}
}
else
{
enabledRooms.Remove(room);
}
// Update the current room effects to be applied.
if (initialized)
{
if (enabledRooms.Count > 0)
{
GvrAudioRoom currentRoom = enabledRooms[enabledRooms.Count - 1];
RoomProperties roomProperties = GetRoomProperties(currentRoom);
// Pass the room properties into a pointer.
IntPtr roomPropertiesPtr = Marshal.AllocHGlobal(Marshal.SizeOf(roomProperties));
Marshal.StructureToPtr(roomProperties, roomPropertiesPtr, false);
SetRoomProperties(roomPropertiesPtr);
Marshal.FreeHGlobal(roomPropertiesPtr);
}
else
{
// Set the room properties to null, which will effectively disable the room effects.
SetRoomProperties(IntPtr.Zero);
}
}
}
/// Computes the occlusion intensity of a given |source| using point source detection.
/// @note This should only be called from the main Unity thread.
public static float ComputeOcclusion(Transform sourceTransform)
{
float occlusion = 0.0f;
if (initialized)
{
Vector3 listenerPosition = listenerTransform.position;
Vector3 sourceFromListener = sourceTransform.position - listenerPosition;
int numHits = Physics.RaycastNonAlloc(listenerPosition, sourceFromListener, occlusionHits,
sourceFromListener.magnitude, occlusionMaskValue);
for (int i = 0; i < numHits; ++i)
{
if (occlusionHits[i].transform != listenerTransform &&
occlusionHits[i].transform != sourceTransform)
{
occlusion += 1.0f;
}
}
}
return occlusion;
}
/// Converts given |db| value to its amplitude equivalent where 'dB = 20 * log10(amplitude)'.
public static float ConvertAmplitudeFromDb(float db)
{
return Mathf.Pow(10.0f, 0.05f * db);
}
/// Generates a set of points to draw a 2D polar pattern.
public static Vector2[] Generate2dPolarPattern(float alpha, float order, int resolution)
{
Vector2[] points = new Vector2[resolution];
float interval = 2.0f * Mathf.PI / resolution;
for (int i = 0; i < resolution; ++i)
{
float theta = i * interval;
// Magnitude |r| for |theta| in radians.
float r = Mathf.Pow(Mathf.Abs((1 - alpha) + alpha * Mathf.Cos(theta)), order);
points[i] = new Vector2(r * Mathf.Sin(theta), r * Mathf.Cos(theta));
}
return points;
}
/// Returns whether the listener is currently inside the given |room| boundaries.
public static bool IsListenerInsideRoom(GvrAudioRoom room)
{
bool isInside = false;
if (initialized)
{
Vector3 relativePosition = listenerTransform.position - room.transform.position;
Quaternion rotationInverse = Quaternion.Inverse(room.transform.rotation);
bounds.size = Vector3.Scale(room.transform.lossyScale, room.size);
isInside = bounds.Contains(rotationInverse * relativePosition);
}
return isInside;
}
/// Listener directivity GUI color.
public static readonly Color listenerDirectivityColor = 0.65f * Color.magenta;
/// Source directivity GUI color.
public static readonly Color sourceDirectivityColor = 0.65f * Color.blue;
/// Minimum distance threshold between |minDistance| and |maxDistance|.
public const float distanceEpsilon = 0.01f;
/// Max distance limit that can be set for volume rolloff.
public const float maxDistanceLimit = 1000000.0f;
/// Min distance limit that can be set for volume rolloff.
public const float minDistanceLimit = 990099.0f;
/// Maximum allowed gain value in decibels.
public const float maxGainDb = 24.0f;
/// Minimum allowed gain value in decibels.
public const float minGainDb = -24.0f;
/// Maximum allowed reverb brightness modifier value.
public const float maxReverbBrightness = 1.0f;
/// Minimum allowed reverb brightness modifier value.
public const float minReverbBrightness = -1.0f;
/// Maximum allowed reverb time modifier value.
public const float maxReverbTime = 3.0f;
/// Maximum allowed reflectivity multiplier of a room surface material.
public const float maxReflectivity = 2.0f;
/// Maximum allowed number of raycast hits for occlusion computation per source.
public const int maxNumOcclusionHits = 12;
/// Source occlusion detection rate in seconds.
public const float occlusionDetectionInterval = 0.2f;
/// Number of first-order ambisonic input channels.
public const int numFoaChannels = 4;
[StructLayout(LayoutKind.Sequential)]
private struct RoomProperties
{
// Center position of the room in world space.
public float positionX;
public float positionY;
public float positionZ;
// Rotation (quaternion) of the room in world space.
public float rotationX;
public float rotationY;
public float rotationZ;
public float rotationW;
// Size of the shoebox room in world space.
public float dimensionsX;
public float dimensionsY;
public float dimensionsZ;
// Material name of each surface of the shoebox room.
public GvrAudioRoom.SurfaceMaterial materialLeft;
public GvrAudioRoom.SurfaceMaterial materialRight;
public GvrAudioRoom.SurfaceMaterial materialBottom;
public GvrAudioRoom.SurfaceMaterial materialTop;
public GvrAudioRoom.SurfaceMaterial materialFront;
public GvrAudioRoom.SurfaceMaterial materialBack;
// User defined uniform scaling factor for reflectivity. This parameter has no effect when set
// to 1.0f.
public float reflectionScalar;
// User defined reverb tail gain multiplier. This parameter has no effect when set to 0.0f.
public float reverbGain;
// Adjusts the reverberation time across all frequency bands. RT60 values are multiplied by this
// factor. Has no effect when set to 1.0f.
public float reverbTime;
// Controls the slope of a line from the lowest to the highest RT60 values (increases high
// frequency RT60s when positive, decreases when negative). Has no effect when set to 0.0f.
public float reverbBrightness;
}
// Converts given |position| and |rotation| from Unity space to audio space.
private static void ConvertAudioTransformFromUnity(ref Vector3 position,
ref Quaternion rotation)
{
transformMatrix = Pose3D.FlipHandedness(Matrix4x4.TRS(position, rotation, Vector3.one));
position = transformMatrix.GetColumn(3);
rotation = Quaternion.LookRotation(transformMatrix.GetColumn(2), transformMatrix.GetColumn(1));
}
// Returns room properties of the given |room|.
private static RoomProperties GetRoomProperties(GvrAudioRoom room)
{
RoomProperties roomProperties;
Vector3 position = room.transform.position;
Quaternion rotation = room.transform.rotation;
Vector3 scale = Vector3.Scale(room.transform.lossyScale, room.size);
ConvertAudioTransformFromUnity(ref position, ref rotation);
roomProperties.positionX = position.x;
roomProperties.positionY = position.y;
roomProperties.positionZ = position.z;
roomProperties.rotationX = rotation.x;
roomProperties.rotationY = rotation.y;
roomProperties.rotationZ = rotation.z;
roomProperties.rotationW = rotation.w;
roomProperties.dimensionsX = scale.x;
roomProperties.dimensionsY = scale.y;
roomProperties.dimensionsZ = scale.z;
roomProperties.materialLeft = room.leftWall;
roomProperties.materialRight = room.rightWall;
roomProperties.materialBottom = room.floor;
roomProperties.materialTop = room.ceiling;
roomProperties.materialFront = room.frontWall;
roomProperties.materialBack = room.backWall;
roomProperties.reverbGain = ConvertAmplitudeFromDb(room.reverbGainDb);
roomProperties.reverbTime = room.reverbTime;
roomProperties.reverbBrightness = room.reverbBrightness;
roomProperties.reflectionScalar = room.reflectivity;
return roomProperties;
}
// Boundaries instance to be used in room detection logic.
private static Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
// Container to store the currently active rooms in the scene.
private static List<GvrAudioRoom> enabledRooms = new List<GvrAudioRoom>();
// Denotes whether the system is initialized properly.
private static bool initialized = false;
// Listener transform.
private static Transform listenerTransform = null;
// Pre-allocated raycast hit list for occlusion computation.
private static RaycastHit[] occlusionHits = new RaycastHit[maxNumOcclusionHits];
// Occlusion layer mask.
private static int occlusionMaskValue = -1;
// 4x4 transformation matrix to be used in transform space conversion.
private static Matrix4x4 transformMatrix = Matrix4x4.identity;
#if !UNITY_EDITOR && UNITY_IOS
private const string pluginName = "__Internal";
#else
private const string pluginName = "audioplugingvrunity";
#endif // !UNITY_EDITOR && UNITY_IOS
// Listener handlers.
[DllImport(pluginName)]
private static extern void SetListenerGain(float gain);
// Soundfield handlers.
[DllImport(pluginName)]
private static extern int CreateSoundfield(int numChannels);
// Source handlers.
[DllImport(pluginName)]
private static extern int CreateSoundObject(bool enableHrtf);
[DllImport(pluginName)]
private static extern void DestroySource(int sourceId);
[DllImport(pluginName)]
private static extern void SetSourceBypassRoomEffects(int sourceId, bool bypassRoomEffects);
[DllImport(pluginName)]
private static extern void SetSourceDirectivity(int sourceId, float alpha, float order);
[DllImport(pluginName)]
private static extern void SetSourceListenerDirectivity(int sourceId, float alpha, float order);
[DllImport(pluginName)]
private static extern void SetSourceOcclusionIntensity(int sourceId, float intensity);
// Room handlers.
[DllImport(pluginName)]
private static extern void SetRoomProperties(IntPtr roomProperties);
// System handlers.
[DllImport(pluginName)]
private static extern void Initialize(int quality, int sampleRate, int numChannels,
int framesPerBuffer);
[DllImport(pluginName)]
private static extern void Shutdown();
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
/// <summary>
/// System.Globalization.StringInfo.GetNextTestElement(string,int32)
/// </summary>
public class StringInfoGetNextTextElement2
{
private const int c_MINI_STRING_LENGTH = 8;
private const int c_MAX_STRING_LENGTH = 256;
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Get the text element from a random index in a string");
try
{
string str = TestLibrary.Generator.GetString(-55, true, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
int index = this.GetInt32(8, str.Length);
string result = StringInfo.GetNextTextElement(str, index);
if (result != str[index].ToString())
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,the result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The first element is a surrogate pair");
try
{
string str = "\uDBFF\uDFFF";
string result = StringInfo.GetNextTextElement("ef45-;\uDBFF\uDFFFabcde", 6);
if (result.Length != 2)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
retVal = false;
}
if (result != str)
{
TestLibrary.TestFramework.LogError("004", "The result is not the value as expected,the result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The element is a combining character");
try
{
string str = "a\u20D1";
string result = StringInfo.GetNextTextElement("13229^a\u20D1abcde", 6);
if (result != str)
{
TestLibrary.TestFramework.LogError("006", "The result is not the value as expected,the result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: The element is a combination of base character and several combining characters");
try
{
string str = "z\uFE22\u20D1\u20EB";
string result = StringInfo.GetNextTextElement("az\uFE22\u20D1\u20EBabcde", 1);
if (result.Length != 4)
{
TestLibrary.TestFramework.LogError("008", "The result is not the value as expected,length is: " + result.Length);
retVal = false;
}
if (result != str)
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected,the result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The string is a null reference");
try
{
string str = null;
string result = StringInfo.GetNextTextElement(str, 0);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The index is out of the range of the string");
try
{
string str = "abc";
string result = StringInfo.GetNextTextElement(str, -4);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: The index is a negative number");
try
{
string str = "df8%^dk";
string result = StringInfo.GetNextTextElement(str, -1);
TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
StringInfoGetNextTextElement2 test = new StringInfoGetNextTextElement2();
TestLibrary.TestFramework.BeginTestCase("StringInfoGetNextTextElement2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// 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.
// File System.Web.Security.FormsAuthentication.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.Security
{
sealed public partial class FormsAuthentication
{
#region Methods and constructors
public static bool Authenticate(string name, string password)
{
return default(bool);
}
public static FormsAuthenticationTicket Decrypt(string encryptedTicket)
{
return default(FormsAuthenticationTicket);
}
public static void EnableFormsAuthentication(System.Collections.Specialized.NameValueCollection configurationData)
{
}
public static string Encrypt(FormsAuthenticationTicket ticket)
{
return default(string);
}
public FormsAuthentication()
{
}
public static System.Web.HttpCookie GetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath)
{
return default(System.Web.HttpCookie);
}
public static System.Web.HttpCookie GetAuthCookie(string userName, bool createPersistentCookie)
{
return default(System.Web.HttpCookie);
}
public static string GetRedirectUrl(string userName, bool createPersistentCookie)
{
return default(string);
}
public static string HashPasswordForStoringInConfigFile(string password, string passwordFormat)
{
return default(string);
}
public static void Initialize()
{
}
public static void RedirectFromLoginPage(string userName, bool createPersistentCookie, string strCookiePath)
{
}
public static void RedirectFromLoginPage(string userName, bool createPersistentCookie)
{
}
public static void RedirectToLoginPage()
{
}
public static void RedirectToLoginPage(string extraQueryString)
{
}
public static FormsAuthenticationTicket RenewTicketIfOld(FormsAuthenticationTicket tOld)
{
return default(FormsAuthenticationTicket);
}
public static void SetAuthCookie(string userName, bool createPersistentCookie)
{
}
public static void SetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath)
{
}
public static void SignOut()
{
}
#endregion
#region Properties and indexers
public static string CookieDomain
{
get
{
return default(string);
}
}
public static System.Web.HttpCookieMode CookieMode
{
get
{
return default(System.Web.HttpCookieMode);
}
}
public static bool CookiesSupported
{
get
{
return default(bool);
}
}
public static string DefaultUrl
{
get
{
return default(string);
}
}
public static bool EnableCrossAppRedirects
{
get
{
return default(bool);
}
}
public static string FormsCookieName
{
get
{
return default(string);
}
}
public static string FormsCookiePath
{
get
{
return default(string);
}
}
public static bool IsEnabled
{
get
{
return default(bool);
}
}
public static string LoginUrl
{
get
{
return default(string);
}
}
public static bool RequireSSL
{
get
{
return default(bool);
}
}
public static bool SlidingExpiration
{
get
{
return default(bool);
}
}
public static System.Web.Configuration.TicketCompatibilityMode TicketCompatibilityMode
{
get
{
return default(System.Web.Configuration.TicketCompatibilityMode);
}
}
public static TimeSpan Timeout
{
get
{
return default(TimeSpan);
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace DataBoss.Data
{
public static class SequenceDataReader
{
public static DbDataReader Items<T>(params T[] data) => Create(data);
public static DbDataReader Create<T>(IEnumerable<T> data) => Create(data, x => x.MapAll());
public static DbDataReader Create<T>(IEnumerable<T> data, Action<FieldMapping<T>> mapFields) => Create(data?.GetEnumerator(), mapFields);
public static DbDataReader Create<T>(IEnumerator<T> data) => Create(data, x => x.MapAll());
public static DbDataReader Create<T>(IEnumerator<T> data, Action<FieldMapping<T>> mapFields) {
var fieldMapping = new FieldMapping<T>();
mapFields(fieldMapping);
return new SequenceDataReader<T>(data, fieldMapping);
}
public static DbDataReader Create<T>(IEnumerable<T> data, params string[] members) =>
Create(data, fields => Array.ForEach(members, x => fields.Map(x)));
public static DbDataReader Create<T>(IEnumerable<T> data, params MemberInfo[] members) =>
Create(data, fields => Array.ForEach(members, x => fields.Map(x)));
public static DbDataReader ToDataReader<T>(this IEnumerable<T> data) => Create(data);
}
public sealed class SequenceDataReader<T> : DbDataReader, IDataRecordReader
{
abstract class FieldAccessor
{
public abstract bool IsDBNull(T item);
public abstract object GetValue(T item);
public abstract TValue GetFieldValue<TValue>(T item);
public static FieldAccessor Create<TField>(Func<T, TField> get) => new ValueAccessor<TField>(get);
public static FieldAccessor Create<TField>(Func<T, TField> get, Func<T, bool> hasValue) =>
hasValue == null ? Create(get) : new NullableAccessor<TField>(get, hasValue);
}
abstract class FieldAccessor<TField> : FieldAccessor
{
readonly Func<T, TField> get;
public FieldAccessor(Func<T, TField> get) {
this.get = get;
}
public override TValue GetFieldValue<TValue>(T item) {
if (typeof(TValue) == typeof(TField) || typeof(TValue) == typeof(object))
return (TValue)(object)get(item);
ThrowInvalidCastException<TField, TValue>();
return default;
}
protected TField GetFieldValue(T item) => get(item);
}
sealed class ValueAccessor<TField> : FieldAccessor<TField>
{
public ValueAccessor(Func<T, TField> get) : base(get) { }
public override object GetValue(T item) => GetFieldValue(item);
public override bool IsDBNull(T item) => false;
}
sealed class NullableAccessor<TField> : FieldAccessor<TField>
{
readonly Func<T, bool> hasValue;
public NullableAccessor(Func<T, TField> get, Func<T, bool> hasValue) : base(get) {
this.hasValue = hasValue ?? throw new ArgumentNullException(nameof(hasValue));
}
public override object GetValue(T item) => IsDBNull(item) ? DBNull.Value : GetFieldValue(item);
public override bool IsDBNull(T item) => !hasValue(item);
}
sealed class StringAccessor : FieldAccessor<string>
{
public StringAccessor(Func<T, string> get) : base(get) { }
public override object GetValue(T item) => (object)GetFieldValue(item) ?? DBNull.Value;
public override bool IsDBNull(T item) => GetFieldValue(item) == null;
}
static void ThrowInvalidCastException<TField, TValue>() =>
throw new InvalidCastException($"Unable to cast object of type '{typeof(TField)}' to {typeof(TValue)}.");
class DataRecord : IDataRecord
{
readonly DataReaderSchemaTable schema;
readonly FieldAccessor[] fields;
readonly T item;
public DataRecord(DataReaderSchemaTable schema, FieldAccessor[] fields, T item) {
this.schema = schema;
this.fields = fields;
this.item = item;
}
public int FieldCount => fields.Length;
public bool IsDBNull(int i) => GetAccessor(i).IsDBNull(item);
public object GetValue(int i) => GetAccessor(i).GetValue(item);
public bool GetBoolean(int i) => GetAccessor(i).GetFieldValue<bool>(item);
public byte GetByte(int i) => GetAccessor(i).GetFieldValue<byte>(item);
public char GetChar(int i) => GetAccessor(i).GetFieldValue<char>(item);
public short GetInt16(int i) => GetAccessor(i).GetFieldValue<short>(item);
public int GetInt32(int i) => GetAccessor(i).GetFieldValue<int>(item);
public long GetInt64(int i) => GetAccessor(i).GetFieldValue<long>(item);
public float GetFloat(int i) => GetAccessor(i).GetFieldValue<float>(item);
public double GetDouble(int i) => GetAccessor(i).GetFieldValue<double>(item);
public decimal GetDecimal(int i) => GetAccessor(i).GetFieldValue<decimal>(item);
public DateTime GetDateTime(int i) => GetAccessor(i).GetFieldValue<DateTime>(item);
public Guid GetGuid(int i) => GetAccessor(i).GetFieldValue<Guid>(item);
public string GetString(int i) => GetAccessor(i).GetFieldValue<string>(item);
FieldAccessor GetAccessor(int i) => fields[i];
public int GetValues(object[] values) {
var n = Math.Min(FieldCount, values.Length);
for (var i = 0; i != n; ++i)
values[i] = GetValue(i);
return n;
}
public object this[int i] => GetValue(i);
public object this[string name] => GetValue(GetOrdinal(name));
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferOffset, int length) => this.GetArray(i, fieldOffset, buffer, bufferOffset, length);
public long GetChars(int i, long fieldOffset, char[] buffer, int bufferOffset, int length) => this.GetArray(i, fieldOffset, buffer, bufferOffset, length);
public IDataReader GetData(int i) => throw new NotImplementedException();
public string GetDataTypeName(int i) => schema[i].DataTypeName;
public Type GetFieldType(int i) => schema[i].DataType;
public string GetName(int i) => schema[i].ColumnName;
public int GetOrdinal(string name) => schema.GetOrdinal(name);
}
IEnumerator<T> data;
readonly FieldAccessor[] fields;
readonly DataReaderSchemaTable schema;
bool hasData;
internal SequenceDataReader(IEnumerator<T> data, FieldMapping<T> fields) {
this.data = data ?? throw new ArgumentNullException(nameof(data));
this.schema = GetSchema(fields);
this.fields = new FieldAccessor[fields.Count];
for (var i = 0; i != this.fields.Length; ++i)
this.fields[i] = MakeAccessor(fields.Source, fields[i]);
}
static DataReaderSchemaTable GetSchema(FieldMapping<T> mapping) {
var schema = new DataReaderSchemaTable();
for (var i = 0; i != mapping.Count; ++i) {
var dbType = mapping.GetDbType(i);
schema.Add(
ordinal: i,
name: mapping.GetFieldName(i),
dataType: mapping.GetFieldType(i),
allowDBNull: dbType.IsNullable,
columnSize: dbType.ColumnSize,
dataTypeName: dbType.TypeName);
}
return schema;
}
static FieldAccessor MakeAccessor(ParameterExpression source, in FieldMappingItem field) {
if (field.FieldType == typeof(string))
return new StringAccessor(CompileSelector<string>(source, field.GetValue));
var (hasValue, selector) = field.HasValue == null ? (null, field.Selector) : (CompileSelector<bool>(source, field.HasValue), field.GetValue);
var createAccessor = Lambdas.CreateDelegate<Func<ParameterExpression, Expression, Func<T, bool>, FieldAccessor>>(
MakeAccessorMethod.MakeGenericMethod(selector.Type));
return createAccessor(source, selector, hasValue);
}
static readonly MethodInfo MakeAccessorMethod = typeof(SequenceDataReader<T>)
.GetMethod(nameof(MakeAccessorT), BindingFlags.Static | BindingFlags.NonPublic);
static FieldAccessor MakeAccessorT<TFieldType>(ParameterExpression source, Expression selector, Func<T, bool> hasValue) =>
FieldAccessor.Create(CompileSelector<TFieldType>(source, selector), hasValue);
static Func<T, TResult> CompileSelector<TResult>(ParameterExpression source, Expression selector) =>
Expression.Lambda<Func<T, TResult>>(selector, source).Compile();
public override object this[int i] => GetValue(i);
public override object this[string name] => GetValue(GetOrdinal(name));
public override int FieldCount => fields.Length;
public override int Depth => throw new NotSupportedException();
public override bool HasRows => throw new NotSupportedException();
public override bool IsClosed => data is null;
public override int RecordsAffected => throw new NotSupportedException();
public override bool Read() => (hasData = data.MoveNext());
public override bool NextResult() => false;
public override void Close() {
data?.Dispose();
data = null;
}
protected override void Dispose(bool disposing) {
if (disposing)
Close();
}
public override DataTable GetSchemaTable() => schema.ToDataTable();
public override string GetDataTypeName(int i) => schema[i].DataTypeName;
public override Type GetFieldType(int i) => schema[i].DataType;
public override string GetName(int i) => schema[i].ColumnName;
public override int GetOrdinal(string name) => schema.GetOrdinal(name);
public override int GetValues(object[] values) {
var n = Math.Min(FieldCount, values.Length);
for (var i = 0; i != n; ++i)
values[i] = GetValue(i);
return n;
}
public override bool IsDBNull(int i) => fields[i].IsDBNull(Current);
public override object GetValue(int i) => fields[i].GetValue(Current);
public override TValue GetFieldValue<TValue>(int i) => GetCurrentValue<TValue>(i);
public override bool GetBoolean(int i) => GetCurrentValue<bool>(i);
public override byte GetByte(int i) => GetCurrentValue<byte>(i);
public override char GetChar(int i) => GetCurrentValue<char>(i);
public override Guid GetGuid(int i) => GetCurrentValue<Guid>(i);
public override short GetInt16(int i) => GetCurrentValue<short>(i);
public override int GetInt32(int i) => GetCurrentValue<int>(i);
public override long GetInt64(int i) => GetCurrentValue<long>(i);
public override float GetFloat(int i) => GetCurrentValue<float>(i);
public override double GetDouble(int i) => GetCurrentValue<double>(i);
public override string GetString(int i) => GetCurrentValue<string>(i);
public override decimal GetDecimal(int i) => GetCurrentValue<decimal>(i);
public override DateTime GetDateTime(int i) => GetCurrentValue<DateTime>(i);
TValue GetCurrentValue<TValue>(int i) => fields[i].GetFieldValue<TValue>(Current);
T Current => hasData ? data.Current : NoData();
static T NoData() => throw new InvalidOperationException("Invalid attempt to read when no data is present, call Read()");
public override long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferOffset, int length) => this.GetArray(i, fieldOffset, buffer, bufferOffset, length);
public override long GetChars(int i, long fieldOffset, char[] buffer, int bufferOffset, int length) => this.GetArray(i, fieldOffset, buffer, bufferOffset, length);
public IDataRecord GetRecord() => new DataRecord(schema, fields, Current);
public override IEnumerator GetEnumerator() {
while (Read())
yield return this;
}
}
}
| |
// Gardens Point Parser Generator
// Copyright (c) Wayne Kelly, QUT 2005
// (see accompanying GPPGcopyright.rtf)
using System;
using System.Collections.Generic;
using System.IO;
namespace gpcc
{
public class CodeGenerator
{
public Grammar grammar;
public void Generate(List<State> states, Grammar grammar)
{
this.grammar = grammar;
GenerateCopyright();
GenerateUsingHeader();
if (grammar.Namespace != null)
{
Console.WriteLine("namespace {0}", grammar.Namespace);
Console.WriteLine("{");
}
GenerateTokens(grammar.terminals);
GenerateClassHeader(grammar.ParserName);
InsertCode(grammar.prologCode);
GenerateInitializeMethod(states, grammar.productions, grammar.nonTerminals);
GenerateActionMethod(grammar.productions);
GenerateToStringMethod();
InsertCode(grammar.epilogCode);
GenerateClassFooter();
if (grammar.Namespace != null)
Console.WriteLine("}");
}
private void GenerateCopyright()
{
Console.WriteLine("// This code was generated by the Gardens Point Parser Generator");
Console.WriteLine("// Copyright (c) Wayne Kelly, QUT 2005");
Console.WriteLine("// (see accompanying GPPGcopyright.rtf)");
Console.WriteLine();
Console.WriteLine();
}
private void GenerateUsingHeader()
{
Console.WriteLine("using System;");
Console.WriteLine("using System.Collections.Generic;");
Console.WriteLine("using System.Text;");
Console.WriteLine("using IronScheme.Editor.Build;");
Console.WriteLine("using IronScheme.Editor.CodeModel;");
Console.WriteLine("using IronScheme.Editor.ComponentModel;");
Console.WriteLine("using IronScheme.Editor.Languages.CSLex;");
Console.WriteLine("using IronScheme.Editor.Languages.gppg;");
foreach (string use in grammar.use)
{
Console.WriteLine("using {0};", use);
}
Console.WriteLine();
}
private void GenerateTokens(Dictionary<string, Terminal> terminals)
{
Console.Write("{0} enum {1} {{", grammar.Visibility, grammar.TokenName);
Console.Write("IGNORE = -1");
bool first = false;
foreach (Terminal terminal in terminals.Values)
if (terminal.symbolic)
{
if (!first)
Console.Write(",");
Console.Write("{0}={1}", terminal.ToString(), terminal.num);
first = false;
}
Console.WriteLine("};");
Console.WriteLine();
Console.WriteLine("public abstract class LexerBase<T> : global::IronScheme.Editor.Languages.CSLex.Language<T>.LexerBase where T : struct, global::IronScheme.Editor.ComponentModel.IToken");
Console.WriteLine("{");
foreach (Terminal terminal in grammar.terminals.Values)
{
if (terminal.symbolic)
{
Console.WriteLine("public const int {0}={1};", terminal.ToString(), terminal.num);
}
}
Console.WriteLine("}");
}
private string GenerateValueType()
{
if (grammar.unionType != null)
{
Console.WriteLine("{0} struct {1} : global::IronScheme.Editor.ComponentModel.IToken", grammar.Visibility, grammar.ValueTypeName);
InsertCode(grammar.unionType);
return grammar.ValueTypeName;
}
else
return "int";
}
private void GenerateClassHeader(string name)
{
Console.WriteLine("{2} partial class {0}: ShiftReduceParser<{1}>", name, GenerateValueType(), grammar.Visibility);
Console.WriteLine("{");
}
private void GenerateClassFooter()
{
Console.WriteLine("}");
}
private void GenerateInitializeMethod(
List<State> states,
List<Production> productions,
Dictionary<string, NonTerminal> nonTerminals)
{
Console.WriteLine(" protected override void Initialize()");
Console.WriteLine(" {");
Console.WriteLine(" this.errToken = (int){0}.error;", grammar.TokenName);
Console.WriteLine(" this.eofToken = (int){0}.EOF;", grammar.TokenName);
Console.WriteLine();
Console.WriteLine(" states=new State[{0}];", states.Count);
int state_nr = 0;
foreach (State state in states)
GenerateState(state_nr++, state);
Console.WriteLine();
Console.WriteLine(" rules=new Rule[{0}];", productions.Count + 1);
foreach (Production production in productions)
GenerateRule(production);
Console.WriteLine();
Console.Write(" nonTerminals = new string[] {\"\", ");
int length = 37;
foreach (NonTerminal nonTerminal in nonTerminals.Values)
{
string ss = String.Format("\"{0}\", ", nonTerminal.ToString());
length += ss.Length;
Console.Write(ss);
if (length > 70)
{
Console.WriteLine();
Console.Write(" ");
length = 0;
}
}
Console.WriteLine("};");
Console.WriteLine(" }");
Console.WriteLine();
}
private void GenerateState(int state_nr, State state)
{
Console.Write(" AddState({0},new State(", state_nr);
int defaultAction = GetDefaultAction(state);
if (defaultAction != 0)
Console.Write(defaultAction);
else
{
Console.Write("new int[]{");
bool first = true;
foreach (KeyValuePair<Terminal, ParserAction> transition in state.parseTable)
{
if (!first)
Console.Write(",");
Console.Write("{0},{1}", transition.Key.num, transition.Value.ToNum());
first = false;
}
Console.Write("}");
}
if (state.nonTerminalTransitions.Count > 0)
{
Console.Write(",new int[]{");
bool first = true;
foreach (Transition transition in state.nonTerminalTransitions.Values)
{
if (!first)
Console.Write(",");
Console.Write("{0},{1}", transition.A.num, transition.next.num);
first = false;
}
Console.Write("}");
}
if (state.conflictTable.Count > 0)
{
Console.Write(",new int[]{");
bool first = true;
foreach (KeyValuePair<Terminal, ParserAction> transition in state.conflictTable)
{
if (!first)
Console.Write(",");
Console.Write("{0},{1}", transition.Key.num, transition.Value.ToNum());
first = false;
}
Console.Write("}");
}
Console.WriteLine("));");
}
private int GetDefaultAction(State state)
{
IEnumerator<ParserAction> enumerator = state.parseTable.Values.GetEnumerator();
enumerator.MoveNext();
if (enumerator.Current == null)
{
Console.Error.WriteLine("Token not defined near: " + state);
Environment.Exit(1);
}
int defaultAction = enumerator.Current.ToNum();
if (defaultAction > 0)
return 0; // can't have default shift action
foreach (KeyValuePair<Terminal, ParserAction> transition in state.parseTable)
if (transition.Value.ToNum() != defaultAction)
return 0;
return defaultAction;
}
private void GenerateRule(Production production)
{
Console.Write(" rules[{0}]=new Rule({1}, new int[]{{", production.num, production.lhs.num);
bool first = true;
foreach (Symbol sym in production.rhs)
{
if (!first)
Console.Write(",");
else
first = false;
Console.Write("{0}", sym.num);
}
Console.WriteLine("});");
}
private void GenerateActionMethod(List<Production> productions)
{
Console.WriteLine(" protected override void DoAction(int action)");
Console.WriteLine(" {");
Console.WriteLine(" switch (action)");
Console.WriteLine(" {");
foreach (Production production in productions)
{
if (production.semanticAction != null)
{
Console.WriteLine(" case {0}: // {1}", production.num, production.ToString());
production.semanticAction.GenerateCode(this);
if (GPCG.LINES)
{
Console.WriteLine("#line hidden");
}
Console.WriteLine(" break;");
}
}
Console.WriteLine(" }");
Console.WriteLine(" }");
Console.WriteLine();
}
private void GenerateToStringMethod()
{
Console.WriteLine(" protected override string TerminalToString(int terminal)");
Console.WriteLine(" {");
Console.WriteLine(" if (((Tokens)terminal).ToString() != terminal.ToString())");
Console.WriteLine(" return ((Tokens)terminal).ToString();");
Console.WriteLine(" else");
Console.WriteLine(" return CharToString((char)terminal);");
Console.WriteLine(" }");
Console.WriteLine();
}
private void InsertCode(string code)
{
if (code != null)
{
StringReader reader = new StringReader(code);
while (true)
{
string line = reader.ReadLine();
if (line == null)
break;
Console.WriteLine("{0}", line);
}
if (GPCG.LINES)
{
Console.WriteLine("#line default");
}
}
}
}
}
| |
/* ====================================================================
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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace TestCases.POIFS.FileSystem
{
using System;
using System.Collections;
using System.IO;
using NUnit.Framework;
using NPOI.POIFS.FileSystem;
using NPOI.Util;
using NPOI.POIFS.Storage;
using NPOI.POIFS.Properties;
using TestCases.HSSF;
using NPOI.POIFS.Common;
using System.Collections.Generic;
/**
* Tests for POIFSFileSystem
*
* @author Josh Micich
*/
[TestFixture]
public class TestPOIFSFileSystem
{
private POIDataSamples _samples = POIDataSamples.GetPOIFSInstance();
/**
* Mock exception used to ensure correct error handling
*/
private class MyEx : Exception
{
public MyEx()
{
// no fields to initialise
}
}
/**
* Helps facilitate Testing. Keeps track of whether close() was called.
* Also can throw an exception at a specific point in the stream.
*/
private class TestIS : Stream
{
private Stream _is;
private int _FailIndex;
private int _currentIx;
private bool _isClosed;
public TestIS(Stream is1, int FailIndex)
{
_is = is1;
_FailIndex = FailIndex;
_currentIx = 0;
_isClosed = false;
}
public int Read()
{
int result = _is.ReadByte();
if (result >= 0)
{
CheckRead(1);
}
return result;
}
public override int Read(byte[] b, int off, int len)
{
int result = _is.Read(b, off, len);
CheckRead(result);
return result;
}
private void CheckRead(int nBytes)
{
_currentIx += nBytes;
if (_FailIndex > 0 && _currentIx > _FailIndex)
{
throw new MyEx();
}
}
public override void Close()
{
_isClosed = true;
_is.Close();
}
public bool IsClosed()
{
return _isClosed;
}
public override void Flush()
{
_is.Flush();
}
public override long Seek(long offset, SeekOrigin origin)
{
return _is.Seek(offset, origin);
}
public override void SetLength(long value)
{
_is.SetLength(value);
}
// Properties
public override bool CanRead
{
get
{
return _is.CanRead;
}
}
public override bool CanSeek
{
get
{
return _is.CanSeek;
}
}
public override bool CanWrite
{
get
{
return _is.CanWrite;
}
}
public override long Length
{
get
{
return _is.Length;
}
}
public override long Position
{
get
{
return _is.Position;
}
set
{
_is.Position = value;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
}
}
/**
* Test for undesired behaviour observable as of svn revision 618865 (5-Feb-2008).
* POIFSFileSystem was not closing the input stream.
*/
[Test]
public void TestAlwaysClose()
{
TestIS testIS;
// Normal case - Read until EOF and close
testIS = new TestIS(OpenSampleStream("13224.xls"), -1);
try
{
new POIFSFileSystem(testIS);
}
catch (IOException )
{
throw;
}
Assert.IsTrue(testIS.IsClosed(), "input stream was not closed");
// intended to crash after Reading 10000 bytes
testIS = new TestIS(OpenSampleStream("13224.xls"), 10000);
try
{
new POIFSFileSystem(testIS);
Assert.Fail("ex Should have been thrown");
}
catch (IOException)
{
throw;
}
catch (MyEx)
{
// expected
}
Assert.IsTrue(testIS.IsClosed(), "input stream was not closed"); // but still Should close
}
/**
* Test for bug # 48898 - problem opening an OLE2
* file where the last block is short (i.e. not a full
* multiple of 512 bytes)
*
* As yet, this problem remains. One school of thought is
* not not issue an EOF when we discover the last block
* is short, but this seems a bit wrong.
* The other is to fix the handling of the last block in
* POIFS, since it seems to be slight wrong
*/
[Test]
public void TestShortLastBlock()
{
String[] files = new String[] {"ShortLastBlock.qwp", "ShortLastBlock.wps"};
for (int i = 0; i < files.Length; i++)
{
// Open the file up
POIFSFileSystem fs = new POIFSFileSystem(
_samples.OpenResourceAsStream(files[i])
);
// Write it into a temp output array
MemoryStream baos = new MemoryStream();
fs.WriteFileSystem(baos);
// Check sizes
}
}
[Test]
public void TestFATandDIFATsectors()
{
// Open the file up
try
{
POIFSFileSystem fs = new POIFSFileSystem(_samples.OpenResourceAsStream("ReferencesInvalidSectors.mpp")
);
Assert.Fail("File is corrupt and shouldn't have been opened");
}
catch (IOException e)
{
String msg = e.Message;
Assert.IsTrue(msg.StartsWith("Your file contains 695 sectors"));
}
}
[Test]
public void TestBATandXBAT()
{
byte[] hugeStream = new byte[8 * 1024 * 1024];
POIFSFileSystem fs = new POIFSFileSystem();
fs.Root.CreateDocument("BIG", new MemoryStream(hugeStream));
MemoryStream baos = new MemoryStream();
fs.WriteFileSystem(baos);
byte[] fsData = baos.ToArray();
// Check the header was written properly
Stream inp = new MemoryStream(fsData);
HeaderBlock header = new HeaderBlock(inp);
Assert.AreEqual(109 + 21, header.BATCount);
Assert.AreEqual(1, header.XBATCount);
ByteBuffer xbatData = ByteBuffer.CreateBuffer(512);
xbatData.Write(fsData, (1 + header.XBATIndex) * 512, 512);
xbatData.Position = 0;
BATBlock xbat = BATBlock.CreateBATBlock(POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS, xbatData);
for (int i = 0; i < 21; i++)
{
Assert.IsTrue(xbat.GetValueAt(i) != POIFSConstants.UNUSED_BLOCK);
}
for (int i = 21; i < 127; i++)
Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, xbat.GetValueAt(i));
Assert.AreEqual(POIFSConstants.END_OF_CHAIN, xbat.GetValueAt(127));
RawDataBlockList blockList = new RawDataBlockList(inp, POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS);
Assert.AreEqual(fsData.Length / 512, blockList.BlockCount() + 1);
new BlockAllocationTableReader(header.BigBlockSize,
header.BATCount,
header.BATArray,
header.XBATCount,
header.XBATIndex,
blockList);
Assert.AreEqual(fsData.Length / 512, blockList.BlockCount() + 1);
//fs = null;
//fs = new POIFSFileSystem(new MemoryStream(fsData));
//DirectoryNode root = fs.Root;
//Assert.AreEqual(1, root.EntryCount);
//DocumentNode big = (DocumentNode)root.GetEntry("BIG");
//Assert.AreEqual(hugeStream.Length, big.Size);
}
[Test]
public void Test4KBlocks()
{
Stream inp = _samples.OpenResourceAsStream("BlockSize4096.zvi");
// First up, check that we can process the header properly
HeaderBlock header_block = new HeaderBlock(inp);
POIFSBigBlockSize bigBlockSize = header_block.BigBlockSize;
Assert.AreEqual(4096, bigBlockSize.GetBigBlockSize());
// Check the fat info looks sane
Assert.AreEqual(1, header_block.BATArray.Length);
Assert.AreEqual(1, header_block.BATCount);
Assert.AreEqual(0, header_block.XBATCount);
// Now check we can get the basic fat
RawDataBlockList data_blocks = new RawDataBlockList(inp, bigBlockSize);
// Now try and open properly
POIFSFileSystem fs = new POIFSFileSystem(
_samples.OpenResourceAsStream("BlockSize4096.zvi")
);
Assert.IsTrue(fs.Root.EntryCount > 3);
// Check we can get at all the contents
CheckAllDirectoryContents(fs.Root);
// Finally, check we can do a similar 512byte one too
fs = new POIFSFileSystem(
_samples.OpenResourceAsStream("BlockSize512.zvi")
);
Assert.IsTrue(fs.Root.EntryCount > 3);
CheckAllDirectoryContents(fs.Root);
}
private void CheckAllDirectoryContents(DirectoryEntry dir)
{
IEnumerator<Entry> it = dir.Entries;
//foreach (Entry entry in dir)
while(it.MoveNext())
{
Entry entry = it.Current;
if (entry is DirectoryEntry)
{
CheckAllDirectoryContents((DirectoryEntry)entry);
}
else
{
DocumentNode doc = (DocumentNode)entry;
DocumentInputStream dis = new DocumentInputStream(doc);
int numBytes = dis.Available();
byte[] data = new byte[numBytes];
dis.Read(data);
}
}
}
/**
* Test that we can open files that come via Lotus notes.
* These have a top level directory without a name....
*/
[Test]
public void TestNotesOLE2Files()
{
POIDataSamples _samples = POIDataSamples.GetPOIFSInstance();
// Open the file up
POIFSFileSystem fs = new POIFSFileSystem(
_samples.OpenResourceAsStream("Notes.ole2")
);
// Check the contents
Assert.AreEqual(1, fs.Root.EntryCount);
fs.Root.Entries.MoveNext();
//fs.Root.Entries.Current is always null. WHY???
//Entry entry = fs.Root.Entries.Current;
Entry entry = fs.Root.GetEntry(0);
Assert.IsTrue(entry.IsDirectoryEntry);
Assert.IsTrue(entry is DirectoryEntry);
// The directory lacks a name!
DirectoryEntry dir = (DirectoryEntry)entry;
Assert.AreEqual("", dir.Name);
// Has two children
Assert.AreEqual(2, dir.EntryCount);
// Check them
IEnumerator<Entry> it = dir.Entries;
it.MoveNext();
entry = it.Current;
Assert.AreEqual(true, entry.IsDocumentEntry);
Assert.AreEqual("\u0001Ole10Native", entry.Name);
it.MoveNext();
entry = it.Current;
Assert.AreEqual(true, entry.IsDocumentEntry);
Assert.AreEqual("\u0001CompObj", entry.Name);
}
private static Stream OpenSampleStream(String sampleFileName)
{
return HSSFTestDataSamples.OpenSampleFileStream(sampleFileName);
}
}
}
| |
/*
Copyright 2002-2009 Corey Trager
Distributed under the terms of the GNU General Public License
*/
using System;
using System.Web;
using System.Data;
using System.Collections.Specialized;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace btnet
{
public class Security {
public const int MUST_BE_ADMIN = 1;
public const int ANY_USER_OK = 2;
public const int ANY_USER_OK_EXCEPT_GUEST = 3;
public const int MUST_BE_ADMIN_OR_PROJECT_ADMIN = 4;
public const int PERMISSION_NONE = 0;
public const int PERMISSION_READONLY = 1;
public const int PERMISSION_REPORTER = 3;
public const int PERMISSION_ALL = 2;
public User user = new User();
public string auth_method = "";
public HttpContext context = null;
static string goto_form = @"
<td nowrap valign=middle>
<form style='margin: 0px; padding: 0px;' action=edit_bug.aspx method=get>
<input class=menubtn type=submit value='go to ID'>
<input class=menuinput size=4 type=text class=txt name=id accesskey=g>
</form>
</td>";
///////////////////////////////////////////////////////////////////////
public void check_security(HttpContext asp_net_context, int level)
{
Util.set_context(asp_net_context);
HttpRequest Request = asp_net_context.Request;
HttpResponse Response = asp_net_context.Response;
HttpCookie cookie = Request.Cookies["se_id"];
// This logic allows somebody to put a link in an email, like
// edit_bug.aspx?id=66
// The user would click on the link, go to the logon page (default.aspx),
// and then after logging in continue on to edit_bug.aspx?id=66
string original_url = Request.ServerVariables["URL"].ToString().ToLower();
string original_querystring = Request.ServerVariables["QUERY_STRING"].ToString().ToLower();
string target = "default.aspx?url=" + original_url + "&qs=" + HttpUtility.UrlEncode(original_querystring);
DataRow dr = null;
if (cookie == null)
{
if (Util.get_setting("AllowGuestWithoutLogin","0") == "0")
{
Util.write_to_log ("se_id cookie is null, so redirecting");
Util.write_to_log ("Trouble logging in? Your browser might be failing to send back its cookie.");
Util.write_to_log ("See Help forum at http://sourceforge.net/forum/forum.php?forum_id=226938");
Response.Redirect(target);
}
}
else
{
// guard against "Sql Injection" exploit
string se_id = cookie.Value.Replace("'", "''");
int user_id = 0;
object obj = asp_net_context.Session[se_id];
if (obj != null)
{
user_id = Convert.ToInt32(obj);
}
// check for existing session for active user
string sql = @"
/* check session */
declare @project_admin int
select @project_admin = count(1)
from sessions
inner join project_user_xref on pu_user = se_user
and pu_admin = 1
where se_id = '$se';
select us_id, us_admin,
us_username, us_firstname, us_lastname,
isnull(us_email,'') us_email,
isnull(us_bugs_per_page,10) us_bugs_per_page,
isnull(us_forced_project,0) us_forced_project,
us_use_fckeditor,
us_enable_bug_list_popups,
og.*,
isnull(us_forced_project, 0 ) us_forced_project,
isnull(pu_permission_level, $dpl) pu_permission_level,
@project_admin [project_admin]
from sessions
inner join users on se_user = us_id
inner join orgs og on us_org = og_id
left outer join project_user_xref
on pu_project = us_forced_project
and pu_user = us_id
where se_id = '$se'
and us_active = 1";
sql = sql.Replace("$se", se_id);
sql = sql.Replace("$dpl", Util.get_setting("DefaultPermissionLevel","2"));
dr = btnet.DbUtil.get_datarow(sql);
}
if (dr == null)
{
if (Util.get_setting("AllowGuestWithoutLogin","0") == "1")
{
// allow users in, even without logging on.
// The user will have the permissions of the "guest" user.
string sql = @"
/* get guest */
select us_id, us_admin,
us_username, us_firstname, us_lastname,
isnull(us_email,'') us_email,
isnull(us_bugs_per_page,10) us_bugs_per_page,
isnull(us_forced_project,0) us_forced_project,
us_use_fckeditor,
us_enable_bug_list_popups,
og.*,
isnull(us_forced_project, 0 ) us_forced_project,
isnull(pu_permission_level, $dpl) pu_permission_level,
0 [project_admin]
from users
inner join orgs og on us_org = og_id
left outer join project_user_xref
on pu_project = us_forced_project
and pu_user = us_id
where us_username = 'guest'
and us_active = 1";
sql = sql.Replace("$dpl", Util.get_setting("DefaultPermissionLevel","2"));
dr = btnet.DbUtil.get_datarow(sql);
}
}
// no previous session, no guest login allowed
if (dr == null)
{
btnet.Util.write_to_log("no previous session, no guest login allowed");
Response.Redirect(target);
}
else
{
user.set_from_db(dr);
}
if (cookie != null)
{
asp_net_context.Session["session_cookie"] = cookie.Value;
}
else
{
btnet.Util.write_to_log("blanking cookie");
asp_net_context.Session["session_cookie"] = "";
}
if (level == MUST_BE_ADMIN && !user.is_admin)
{
btnet.Util.write_to_log("must be admin, redirecting");
Response.Redirect("default.aspx");
}
else if (level == ANY_USER_OK_EXCEPT_GUEST && user.is_guest)
{
btnet.Util.write_to_log("cant be guest, redirecting");
Response.Redirect("default.aspx");
}
else if (level == MUST_BE_ADMIN_OR_PROJECT_ADMIN && !user.is_admin && !user.is_project_admin)
{
btnet.Util.write_to_log("must be project admin, redirecting");
Response.Redirect("default.aspx");
}
if (Util.get_setting("WindowsAuthentication","0") == "1")
{
auth_method = "windows";
}
else
{
auth_method = "plain";
}
}
///////////////////////////////////////////////////////////////////////
public static void create_session(HttpRequest Request, HttpResponse Response, int userid, string username, string NTLM)
{
// Generate a random session id
// Don't use a regularly incrementing identity
// column because that can be guessed.
string guid = Guid.NewGuid().ToString();
btnet.Util.write_to_log("guid=" + guid);
string sql = @"insert into sessions (se_id, se_user) values('$gu', $us)";
sql = sql.Replace("$gu", guid);
sql = sql.Replace("$us", Convert.ToString(userid));
btnet.DbUtil.execute_nonquery(sql);
HttpContext.Current.Session[guid] = userid;
string sAppPath = Request.Url.AbsolutePath;
sAppPath = sAppPath.Substring(0, sAppPath.LastIndexOf('/'));
Util.write_to_log("AppPath:" + sAppPath);
Response.Cookies["se_id"].Value = guid;
Response.Cookies["se_id"].Path = sAppPath;
Response.Cookies["user"]["name"] = username;
Response.Cookies["user"]["NTLM"] = NTLM;
Response.Cookies["user"].Path = sAppPath;
DateTime dt = DateTime.Now;
TimeSpan ts = new TimeSpan(365, 0, 0, 0);
Response.Cookies["user"].Expires = dt.Add(ts);
}
///////////////////////////////////////////////////////////////////////
public void write_menu_item(HttpResponse Response,
string this_link, string menu_item, string href)
{
Response.Write("<td class='menu_td'>");
if (this_link == menu_item)
{
Response.Write("<a href=" + href + "><span class='selected_menu_item warn' style='margin-left:3px;'>" + menu_item + "</span></a>");
}
else
{
Response.Write("<a href=" + href + "><span class='menu_item warn' style='margin-left:3px;'>" + menu_item + "</span></a>");
}
Response.Write("</td>");
}
///////////////////////////////////////////////////////////////////////
public void write_menu(HttpResponse Response, string this_link)
{
// topmost visible HTML
string custom_header = (string)Util.context.Application["custom_header"];
Response.Write(custom_header);
Response.Write(@"
<span id=debug style='position:absolute;top:0;left:0;'></span>
<script>
function dbg(s)
{
document.getElementById('debug').innerHTML += (s + '<br>')
}
function on_submit_search()
{
el = document.getElementById('lucene_input')
if (el.value == '')
{
alert('Enter the words you are search for.');
el.focus()
return false;
}
else
{
return true;
}
}
</script>
<table border=0 width=100% cellpadding=0 cellspacing=0 class=menubar><tr>");
// logo
string logo = (string)Util.context.Application["custom_logo"];
Response.Write(logo);
Response.Write("<td width=20> </td>");
write_menu_item(Response, this_link, Util.get_setting("PluralBugLabel", "bugs"), "bugs.aspx");
write_menu_item(Response, this_link, "search", "search.aspx");
if (Util.get_setting("EnableWhatsNewPage", "0") == "1")
{
write_menu_item(Response, this_link, "news", "view_whatsnew.aspx");
}
if (!user.is_guest)
{
write_menu_item(Response, this_link, "queries", "queries.aspx");
}
if (user.is_admin || user.can_use_reports || user.can_edit_reports)
{
write_menu_item(Response, this_link, "reports", "reports.aspx");
}
if (Util.get_setting("CustomMenuLinkLabel", "") != "")
{
write_menu_item(Response, this_link,
Util.get_setting("CustomMenuLinkLabel", ""),
Util.get_setting("CustomMenuLinkUrl", ""));
}
if (user.is_admin)
{
write_menu_item(Response, this_link, "admin", "admin.aspx");
}
else if (user.is_project_admin)
{
write_menu_item(Response, this_link, "users", "users.aspx");
}
// go to
Response.Write (goto_form);
// search
if (Util.get_setting("EnableLucene", "1") == "1")
{
string query = (string) HttpContext.Current.Session["query"];
if (query == null)
{
query = "";
}
string search_form = @"
<td nowrap valign=middle>
<form style='margin: 0px; padding: 0px;' action=search_text.aspx method=get onsubmit='return on_submit_search()'>
<input class=menubtn type=submit value='search text'>
<input class=menuinput id=lucene_input size=24 type=text class=txt
value='" + query + @"'name=query accesskey=s>
<a href=lucene_syntax.html target=_blank style='font-size: 7pt;'>advanced</a>
</form>
</td>";
//context.Session["query"] = null;
Response.Write(search_form);
}
Response.Write("<td nowrap valign=middle>");
if (user.is_guest && Util.get_setting("AllowGuestWithoutLogin","0") == "1")
{
Response.Write("<span class=smallnote>using as<br>");
}
else
{
Response.Write("<span class=smallnote>logged in as<br>");
}
Response.Write(user.username);
Response.Write("</span></td>");
if (auth_method == "plain")
{
if (user.is_guest && Util.get_setting("AllowGuestWithoutLogin","0") == "1")
{
write_menu_item(Response, this_link, "login", "default.aspx");
}
else
{
write_menu_item(Response, this_link, "logoff", "logoff.aspx");
}
}
// for guest account, suppress display of "edit_self
if (!user.is_guest)
{
write_menu_item(Response, this_link, "settings", "edit_self.aspx");
}
Response.Write("<td valign=middle align=left'>");
Response.Write("<a target=_blank href=about.html><span class='menu_item' style='margin-left:3px;'>about</span></a></td>");
Response.Write("<td nowrap valign=middle>");
Response.Write("<a target=_blank href=http://ifdefined.com/README.html>help</a></td>");
Response.Write("</tr></table><br>");
}
} // end Security
}
| |
//------------------------------------------------------------------------------
// This code was generated by a tool.
//
// Tool : Bond Compiler 0.10.1.0
// File : ContextTagKeys_types.cs
//
// Changes to this file may cause incorrect behavior and will be lost when
// the code is regenerated.
// <auto-generated />
//------------------------------------------------------------------------------
// suppress "Missing XML comment for publicly visible type or member"
#pragma warning disable 1591
#region ReSharper warnings
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable RedundantNameQualifier
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable UnusedParameter.Local
// ReSharper disable RedundantUsingDirective
#endregion
namespace AI
{
using System.Collections.Generic;
[global::Bond.Attribute("ContextContract", "Emit")]
[global::Bond.Attribute("PseudoType", "JSMap")]
[global::Bond.Schema]
[System.CodeDom.Compiler.GeneratedCode("gbc", "0.10.1.0")]
public partial class ContextTagKeys
{
[global::Bond.Attribute("Description", "Application version. Information in the application context fields is always about the application that is sending the telemetry.")]
[global::Bond.Attribute("MaxStringLength", "1024")]
[global::Bond.Id(10)]
public string ApplicationVersion { get; set; }
[global::Bond.Attribute("Description", "Unique client device id. Computer name in most cases.")]
[global::Bond.Attribute("MaxStringLength", "1024")]
[global::Bond.Id(100)]
public string DeviceId { get; set; }
[global::Bond.Attribute("Description", "Device locale using <language>-<REGION> pattern, following RFC 5646. Example 'en-US'.")]
[global::Bond.Attribute("MaxStringLength", "64")]
[global::Bond.Id(115)]
public string DeviceLocale { get; set; }
[global::Bond.Attribute("Description", "Model of the device the end user of the application is using. Used for client scenarios. If this field is empty then it is derived from the user agent.")]
[global::Bond.Attribute("MaxStringLength", "256")]
[global::Bond.Id(120)]
public string DeviceModel { get; set; }
[global::Bond.Attribute("Description", "Client device OEM name taken from the browser.")]
[global::Bond.Attribute("MaxStringLength", "256")]
[global::Bond.Id(130)]
public string DeviceOEMName { get; set; }
[global::Bond.Attribute("Description", "Operating system name and version of the device the end user of the application is using. If this field is empty then it is derived from the user agent. Example 'Windows 10 Pro 10.0.10586.0'")]
[global::Bond.Attribute("MaxStringLength", "256")]
[global::Bond.Id(140)]
public string DeviceOSVersion { get; set; }
[global::Bond.Attribute("Description", "The type of the device the end user of the application is using. Used primarily to distinguish JavaScript telemetry from server side telemetry. Examples: 'PC', 'Phone', 'Browser'. 'PC' is the default value.")]
[global::Bond.Attribute("MaxStringLength", "64")]
[global::Bond.Id(160)]
public string DeviceType { get; set; }
[global::Bond.Attribute("Description", "The IP address of the client device. IPv4 and IPv6 are supported. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.")]
[global::Bond.Attribute("MaxStringLength", "46")]
[global::Bond.Id(200)]
public string LocationIp { get; set; }
[global::Bond.Attribute("Description", "The country of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.")]
[global::Bond.Attribute("MaxStringLength", "256")]
[global::Bond.Id(201)]
public string LocationCountry { get; set; }
[global::Bond.Attribute("Description", "The province/state of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.")]
[global::Bond.Attribute("MaxStringLength", "256")]
[global::Bond.Id(202)]
public string LocationProvince { get; set; }
[global::Bond.Attribute("Description", "The city of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.")]
[global::Bond.Attribute("MaxStringLength", "256")]
[global::Bond.Id(203)]
public string LocationCity { get; set; }
[global::Bond.Attribute("Description", "A unique identifier for the operation instance. The operation.id is created by either a request or a page view. All other telemetry sets this to the value for the containing request or page view. Operation.id is used for finding all the telemetry items for a specific operation instance.")]
[global::Bond.Attribute("MaxStringLength", "128")]
[global::Bond.Id(300)]
public string OperationId { get; set; }
[global::Bond.Attribute("Description", "The name (group) of the operation. The operation.name is created by either a request or a page view. All other telemetry items set this to the value for the containing request or page view. Operation.name is used for finding all the telemetry items for a group of operations (i.e. 'GET Home/Index').")]
[global::Bond.Attribute("MaxStringLength", "1024")]
[global::Bond.Id(305)]
public string OperationName { get; set; }
[global::Bond.Attribute("Description", "The unique identifier of the telemetry item's immediate parent.")]
[global::Bond.Attribute("MaxStringLength", "128")]
[global::Bond.Id(310)]
public string OperationParentId { get; set; }
[global::Bond.Attribute("Description", "Name of synthetic source. Some telemetry from the application may represent a synthetic traffic. It may be web crawler indexing the web site, site availability tests or traces from diagnostic libraries like Application Insights SDK itself.")]
[global::Bond.Attribute("MaxStringLength", "1024")]
[global::Bond.Id(320)]
public string OperationSyntheticSource { get; set; }
[global::Bond.Attribute("Description", "The correlation vector is a light weight vector clock which can be used to identify and order related events across clients and services.")]
[global::Bond.Attribute("MaxStringLength", "64")]
[global::Bond.Id(330)]
public string OperationCorrelationVector { get; set; }
[global::Bond.Attribute("Description", "Session ID - the instance of the user's interaction with the app. Information in the session context fields is always about the end user. When telemetry is sent from a service, the session context is about the user that initiated the operation in the service.")]
[global::Bond.Attribute("MaxStringLength", "64")]
[global::Bond.Id(400)]
public string SessionId { get; set; }
[global::Bond.Attribute("Description", "Boolean value indicating whether the session identified by ai.session.id is first for the user or not.")]
[global::Bond.Attribute("MaxStringLength", "5")]
[global::Bond.Attribute("Question", "Should it be marked as JSType-bool for breeze?")]
[global::Bond.Id(405)]
public string SessionIsFirst { get; set; }
[global::Bond.Attribute("Description", "In multi-tenant applications this is the account ID or name which the user is acting with. Examples may be subscription ID for Azure portal or blog name blogging platform.")]
[global::Bond.Attribute("MaxStringLength", "1024")]
[global::Bond.Id(505)]
public string UserAccountId { get; set; }
[global::Bond.Attribute("Description", "Anonymous user id. Represents the end user of the application. When telemetry is sent from a service, the user context is about the user that initiated the operation in the service.")]
[global::Bond.Attribute("MaxStringLength", "128")]
[global::Bond.Id(515)]
public string UserId { get; set; }
[global::Bond.Attribute("Description", "Authenticated user id. The opposite of ai.user.id, this represents the user with a friendly name. Since it's PII information it is not collected by default by most SDKs.")]
[global::Bond.Attribute("MaxStringLength", "1024")]
[global::Bond.Id(525)]
public string UserAuthUserId { get; set; }
[global::Bond.Attribute("Description", "Name of the role the application is a part of. Maps directly to the role name in azure.")]
[global::Bond.Attribute("MaxStringLength", "256")]
[global::Bond.Id(705)]
public string CloudRole { get; set; }
[global::Bond.Attribute("Description", "Name of the instance where the application is running. Computer name for on-premisis, instance name for Azure.")]
[global::Bond.Attribute("MaxStringLength", "256")]
[global::Bond.Id(715)]
public string CloudRoleInstance { get; set; }
[global::Bond.Attribute("Description", "SDK version. See https://github.com/Microsoft/ApplicationInsights-Home/blob/master/SDK-AUTHORING.md#sdk-version-specification for information.")]
[global::Bond.Attribute("MaxStringLength", "64")]
[global::Bond.Id(1000)]
public string InternalSdkVersion { get; set; }
[global::Bond.Attribute("Description", "Agent version. Used to indicate the version of StatusMonitor installed on the computer if it is used for data collection.")]
[global::Bond.Attribute("MaxStringLength", "64")]
[global::Bond.Id(1001)]
public string InternalAgentVersion { get; set; }
[global::Bond.Attribute("Description", "This is the node name used for billing purposes. Use it to override the standard detection of nodes.")]
[global::Bond.Attribute("MaxStringLength", "256")]
[global::Bond.Id(1002)]
public string InternalNodeName { get; set; }
public ContextTagKeys()
: this("AI.ContextTagKeys", "ContextTagKeys")
{}
protected ContextTagKeys(string fullName, string name)
{
ApplicationVersion = "ai.application.ver";
DeviceId = "ai.device.id";
DeviceLocale = "ai.device.locale";
DeviceModel = "ai.device.model";
DeviceOEMName = "ai.device.oemName";
DeviceOSVersion = "ai.device.osVersion";
DeviceType = "ai.device.type";
LocationIp = "ai.location.ip";
LocationCountry = "ai.location.country";
LocationProvince = "ai.location.province";
LocationCity = "ai.location.city";
OperationId = "ai.operation.id";
OperationName = "ai.operation.name";
OperationParentId = "ai.operation.parentId";
OperationSyntheticSource = "ai.operation.syntheticSource";
OperationCorrelationVector = "ai.operation.correlationVector";
SessionId = "ai.session.id";
SessionIsFirst = "ai.session.isFirst";
UserAccountId = "ai.user.accountId";
UserId = "ai.user.id";
UserAuthUserId = "ai.user.authUserId";
CloudRole = "ai.cloud.role";
CloudRoleInstance = "ai.cloud.roleInstance";
InternalSdkVersion = "ai.internal.sdkVersion";
InternalAgentVersion = "ai.internal.agentVersion";
InternalNodeName = "ai.internal.nodeName";
}
}
} // AI
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Klaus Potzesny (mailto:[email protected])
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Reflection;
using System.IO;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Visitors;
using MigraDoc.Rendering.Resources;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
namespace MigraDoc.Rendering
{
/// <summary>
/// Provides the functionality to convert MigraDoc documents into PDF.
/// </summary>
[Obsolete("Use class PdfDocumentRenderer.")] // DELETE: 8/06
public class PdfPrinter
{
/// <summary>
/// Initializes a new instance of the PdfPrinter class.
/// </summary>
public PdfPrinter()
{
}
/// <summary>
/// Set the MigraDoc document to be rendered by this printer.
/// </summary>
public Document Document
{
set
{
this.document = null;
value.BindToRenderer(this);
this.document = value;
}
}
Document document;
/// <summary>
/// Gets or sets a document renderer.
/// </summary>
/// <remarks>
/// A document renderer is automatically created and prepared
/// when printing before this property was set.
/// </remarks>
public DocumentRenderer DocumentRenderer
{
get { return this.documentRenderer; }
set { this.documentRenderer = value; }
}
DocumentRenderer documentRenderer;
void PrepareDocumentRenderer()
{
if (this.document == null)
throw new InvalidOperationException(Messages.PropertyNotSetBefore("DocumentRenderer", MethodInfo.GetCurrentMethod().Name));
this.documentRenderer = new DocumentRenderer(this.document);
this.documentRenderer.WorkingDirectory = this.workingDirectory;
this.documentRenderer.PrepareDocument();
}
/// <summary>
/// Prints a PDF document containing all pages of the document.
/// </summary>
public void PrintDocument()
{
if (this.documentRenderer == null)
PrepareDocumentRenderer();
if (this.pdfDocument == null)
{
this.pdfDocument = new PdfDocument();
this.pdfDocument.Info.Creator = VersionInfo.Creator;
}
WriteDocumentInformation();
PrintPages(1, this.documentRenderer.FormattedDocument.PageCount);
}
/// <summary>
/// Saves the PDF document to the specified path. If a file already exists, it will be overwritten.
/// </summary>
public void Save(string path)
{
if (path == null)
throw new ArgumentNullException("path");
else if (path == "")
throw new ArgumentException("PDF file Path must not be empty");
if (this.workingDirectory != null)
Path.Combine(this.workingDirectory, path);
this.pdfDocument.Save(path);
}
/// <summary>
/// Saves the PDF document to the specified stream.
/// </summary>
public void Save(Stream stream, bool closeStream)
{
this.pdfDocument.Save(stream, closeStream);
}
/// <summary>
/// Prints the spcified page range.
/// </summary>
/// <param name="startPage">The first page to print.</param>
/// <param name="endPage">The last page to print</param>
public void PrintPages(int startPage, int endPage)
{
if (startPage < 1)
throw new ArgumentOutOfRangeException("startPage");
if (endPage > this.documentRenderer.FormattedDocument.PageCount)
throw new ArgumentOutOfRangeException("endPage");
if (this.documentRenderer == null)
PrepareDocumentRenderer();
if (this.pdfDocument == null)
{
this.pdfDocument = new PdfDocument();
this.pdfDocument.Info.Creator = VersionInfo.Creator;
}
this.documentRenderer.printDate = DateTime.Now;
for (int pageNr = startPage; pageNr <= endPage; ++pageNr)
{
PdfPage pdfPage = this.pdfDocument.AddPage();
PageInfo pageInfo = this.documentRenderer.FormattedDocument.GetPageInfo(pageNr);
pdfPage.Width = pageInfo.Width;
pdfPage.Height = pageInfo.Height;
pdfPage.Orientation = pageInfo.Orientation;
this.documentRenderer.RenderPage(XGraphics.FromPdfPage(pdfPage), pageNr);
}
}
/// <summary>
/// Gets or sets a working directory for the printing process.
/// </summary>
public string WorkingDirectory
{
get { return this.workingDirectory; }
set { this.workingDirectory = value; }
}
string workingDirectory;
/// <summary>
/// Gets or sets the PDF document to render on.
/// </summary>
/// <remarks>A PDF document in memory is automatically created when printing before this property was set.</remarks>
public PdfDocument PdfDocument
{
get { return this.pdfDocument; }
set { this.pdfDocument = value; }
}
/// <summary>
/// Writes document information like author and subject to the PDF document.
/// </summary>
private void WriteDocumentInformation()
{
if (!this.document.IsNull("Info"))
{
DocumentInfo docInfo = this.document.Info;
PdfDocumentInformation pdfInfo = this.pdfDocument.Info;
if (!docInfo.IsNull("Author"))
pdfInfo.Author = docInfo.Author;
if (!docInfo.IsNull("Keywords"))
pdfInfo.Keywords = docInfo.Keywords;
if (!docInfo.IsNull("Subject"))
pdfInfo.Subject = docInfo.Subject;
if (!docInfo.IsNull("Title"))
pdfInfo.Title = docInfo.Title;
}
}
PdfDocument pdfDocument;
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Contoso.Core.JavaScriptInjectionWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
//
// System.Xml.XmlSchemaDatatypeTests.cs
//
// Author:
// Atsushi Enomoto <[email protected]>
// Wojciech Kotlarski <[email protected]>
// Andres G. Aragoneses <[email protected]>
//
// (C) 2002 Atsushi Enomoto
// (C) 2012 7digital Media Ltd.
//
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Collections.Generic;
using NUnit.Framework;
using QName = System.Xml.XmlQualifiedName;
using SimpleType = System.Xml.Schema.XmlSchemaSimpleType;
using SimpleRest = System.Xml.Schema.XmlSchemaSimpleTypeRestriction;
using AssertType = NUnit.Framework.Assert;
namespace MonoTests.System.Xml
{
[TestFixture]
public class XmlSchemaDatatypeTests
{
private XmlSchema GetSchema (string path)
{
return XmlSchema.Read (new XmlTextReader (path), null);
}
private XmlQualifiedName QName (string name, string ns)
{
return new XmlQualifiedName (name, ns);
}
private void AssertDatatype (XmlSchema schema, int index,
XmlTokenizedType tokenizedType, Type type, string rawValue, object parsedValue)
{
XmlSchemaElement element = schema.Items [index] as XmlSchemaElement;
XmlSchemaDatatype dataType = element.ElementType as XmlSchemaDatatype;
Assert.AreEqual (tokenizedType, dataType.TokenizedType, "#1");
Assert.AreEqual (type, dataType.ValueType, "#2");
Assert.AreEqual (parsedValue, dataType.ParseValue (rawValue, null, null), "#3");
}
[Test]
[Ignore ("The behavior has been inconsistent between versions, so it is not worthy of testing.")]
// Note that it could also apply to BaseTypeName (since if
// it is xs:anyType and BaseType is empty, BaseTypeName
// should be xs:anyType).
public void TestAnyType ()
{
XmlSchema schema = GetSchema ("Test/XmlFiles/xsd/datatypesTest.xsd");
schema.Compile (null);
XmlSchemaElement any = schema.Elements [QName ("e00", "urn:bar")] as XmlSchemaElement;
XmlSchemaComplexType cType = any.ElementType as XmlSchemaComplexType;
Assert.AreEqual (typeof (XmlSchemaComplexType), cType.GetType (), "#1");
Assert.IsNotNull (cType, "#2");
Assert.AreEqual (XmlQualifiedName.Empty, cType.QualifiedName, "#3");
Assert.IsNull (cType.BaseSchemaType, "#4"); // In MS.NET 2.0 its null. In 1.1 it is not null.
Assert.IsNotNull (cType.ContentTypeParticle, "#5");
}
[Test]
public void TestAll ()
{
XmlSchema schema = GetSchema ("Test/XmlFiles/xsd/datatypesTest.xsd");
schema.Compile (null);
AssertDatatype (schema, 1, XmlTokenizedType.CDATA, typeof (string), " f o o ", " f o o ");
AssertDatatype (schema, 2, XmlTokenizedType.CDATA, typeof (string), " f o o ", " f o o ");
// token shouldn't allow " f o o "
AssertDatatype (schema, 3, XmlTokenizedType.CDATA, typeof (string), "f o o", "f o o");
// language seems to be checked strictly
AssertDatatype (schema, 4, XmlTokenizedType.CDATA, typeof (string), "x-foo", "x-foo");
// NMTOKEN shouldn't allow " f o o "
// AssertDatatype (schema, 5, XmlTokenizedType.NMTOKEN, typeof (string), "foo", "foo");
// AssertDatatype (schema, 6, XmlTokenizedType.NMTOKEN, typeof (string []), "f o o", new string [] {"f", "o", "o"});
}
[Test]
public void AnyUriRelativePath ()
{
XmlValidatingReader vr = new XmlValidatingReader (
new XmlTextReader (
// relative path value that contains ':' should be still valid.
"<root>../copy/myserver/</root>",
XmlNodeType.Document, null));
vr.Schemas.Add (XmlSchema.Read (
new XmlTextReader ("<xs:schema xmlns:xs='"
+ XmlSchema.Namespace +
"'><xs:element name='root' type='xs:anyURI' /></xs:schema>",
XmlNodeType.Document, null), null));
vr.Read ();
vr.Read ();
vr.Read ();
}
[Test]
#if !NET_2_0
[Category ("NotDotNet")]
#endif
public void AnyUriRelativePathContainsColon ()
{
XmlValidatingReader vr = new XmlValidatingReader (
new XmlTextReader (
// relative path value that contains ':' should be still valid.
"<root>../copy/myserver/c:/foo</root>",
XmlNodeType.Document, null));
vr.Schemas.Add (XmlSchema.Read (
new XmlTextReader ("<xs:schema xmlns:xs='"
+ XmlSchema.Namespace +
"'><xs:element name='root' type='xs:anyURI' /></xs:schema>",
XmlNodeType.Document, null), null));
vr.Read ();
vr.Read ();
vr.Read ();
}
string [] allTypes = new string [] {
"string", "boolean", "float", "double", "decimal",
"duration", "dateTime", "time", "date", "gYearMonth",
"gYear", "gMonthDay", "gDay", "gMonth", "hexBinary",
"base64Binary", "anyURI", "QName", "NOTATION",
"normalizedString", "token", "language", "IDREFS",
"ENTITIES", "NMTOKEN", "NMTOKENS", "Name", "NCName",
"ID", "IDREF", "ENTITY", "integer",
"nonPositiveInteger", "negativeInteger", "long",
"int", "short", "byte", "nonNegativeInteger",
"unsignedLong", "unsignedInt", "unsignedShort",
"unsignedByte", "positiveInteger"
};
XmlSchemaSet allWrappers;
void SetupSimpleTypeWrappers ()
{
XmlSchema schema = new XmlSchema ();
List<QName> qnames = new List<QName> ();
foreach (string name in allTypes) {
SimpleType st = new SimpleType ();
st.Name = "x-" + name;
SimpleRest r = new SimpleRest ();
st.Content = r;
QName qname = new QName (name, XmlSchema.Namespace);
r.BaseTypeName = qname;
qnames.Add (qname);
schema.Items.Add (st);
}
XmlSchemaSet sset = new XmlSchemaSet ();
sset.Add (schema);
sset.Compile ();
allWrappers = sset;
}
XmlSchemaDatatype GetDatatype (string name)
{
return (allWrappers.GlobalTypes [new QName ("x-" + name,
String.Empty)] as SimpleType).Datatype;
}
string [] GetDerived (string target)
{
XmlSchemaDatatype strType = GetDatatype (target);
List<string> results = new List<string> ();
foreach (string name in allTypes) {
if (name == target)
continue;
XmlSchemaDatatype deriv = GetDatatype (name);
if (deriv.IsDerivedFrom (strType))
results.Add (name);
else Console.Error.WriteLine (deriv.GetType () + " is not derived from " + strType.GetType ());
}
return results.ToArray ();
}
[Test]
public void IsDerivedFrom ()
{
SetupSimpleTypeWrappers ();
// Funky, but XmlSchemaDatatype.IsDerivedFrom() is
// documented to always return false, but actually
// matches the same type - which could be guessed that
// this method is used only to detect user-defined
// simpleType derivation.
foreach (string b in allTypes)
foreach (string d in allTypes)
AssertType.AreEqual (b == d, GetDatatype (d).IsDerivedFrom (GetDatatype (b)), b);
AssertType.IsFalse (GetDatatype ("string").IsDerivedFrom (null), "null arg");
}
[Test]
public void ChangeType_StringTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype;
Assert.IsTrue (datatype != null);
Assert.AreEqual (XmlTypeCode.String, datatype.TypeCode);
Assert.AreEqual (typeof(string), datatype.ValueType);
Assert.AreEqual ("test", datatype.ChangeType("test", typeof(string)));
}
[Test]
public void ChangeType_StringToObjectTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype;
Assert.IsTrue (datatype != null);
Assert.AreEqual (XmlTypeCode.String, datatype.TypeCode);
Assert.AreEqual (typeof(string), datatype.ValueType);
Assert.AreEqual ("test", datatype.ChangeType("test", typeof(object)));
}
[Test]
public void ChangeType_IntegerTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Integer).Datatype;
Assert.IsTrue (datatype != null);
Assert.AreEqual (XmlTypeCode.Integer, datatype.TypeCode);
Assert.AreEqual (typeof(decimal), datatype.ValueType);
Assert.AreEqual (300, datatype.ChangeType("300", typeof(int)));
}
[Test]
public void ChangeType_FromDateTimeTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime).Datatype;
Assert.IsTrue (datatype != null);
Assert.AreEqual (XmlTypeCode.DateTime, datatype.TypeCode);
Assert.AreEqual (typeof(DateTime), datatype.ValueType);
DateTime date = new DateTime (2012, 06, 27, 0, 0, 0, DateTimeKind.Utc);
Assert.AreEqual ("2012-06-27T00:00:00Z", datatype.ChangeType(date, typeof(string)));
}
[Test]
public void ChangeType_FromTimeSpanTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DayTimeDuration).Datatype;
Assert.IsTrue (datatype != null);
Assert.AreEqual (XmlTypeCode.DayTimeDuration, datatype.TypeCode);
Assert.AreEqual (typeof(TimeSpan), datatype.ValueType);
TimeSpan span = new TimeSpan(1, 2, 3);
Assert.AreEqual ("PT1H2M3S", datatype.ChangeType(span, typeof(string)));
}
[Test]
public void ChangeType_ToDateTimeTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime).Datatype;
Assert.IsTrue (datatype != null);
Assert.AreEqual (XmlTypeCode.DateTime, datatype.TypeCode);
Assert.AreEqual (typeof(DateTime), datatype.ValueType);
DateTime date = new DateTime (2012, 06, 27, 0, 0, 0, DateTimeKind.Utc);
Assert.AreEqual (date, datatype.ChangeType("2012-06-27T00:00:00Z", typeof(DateTime)));
}
[Test]
public void ChangeType_ToTimeSpanTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DayTimeDuration).Datatype;
Assert.IsTrue (datatype != null);
Assert.AreEqual (XmlTypeCode.DayTimeDuration, datatype.TypeCode);
Assert.AreEqual (typeof(TimeSpan), datatype.ValueType);
TimeSpan span = new TimeSpan(1, 2, 3);
Assert.AreEqual (span, datatype.ChangeType("PT1H2M3S", typeof(TimeSpan)));
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ChangeType_NullValueArgumentInFromStringTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Integer).Datatype;
datatype.ChangeType(null, typeof(string));
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ChangeType_NullValueArgumentInToStringTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Integer).Datatype;
datatype.ChangeType(null, typeof(int));
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ChangeType_NullTargetArgumentInFromStringTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Integer).Datatype;
datatype.ChangeType("100", null);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ChangeType_NullNamespaceResolverArgumentInFromStringTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Integer).Datatype;
datatype.ChangeType("100", typeof(string), null);
}
[Test]
[Category("NotWorking")]
[ExpectedException (typeof(InvalidCastException))]
public void InvalidCastExceptionTest()
{
XmlSchemaDatatype datatype = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime).Datatype;
Assert.IsTrue (datatype != null);
Assert.AreEqual (XmlTypeCode.DateTime, datatype.TypeCode);
Assert.AreEqual (typeof(DateTime), datatype.ValueType);
datatype.ChangeType(300, typeof (int));
}
[Test]
public void Bug12469 ()
{
Dictionary<string, string> validValues = new Dictionary<string, string> {
{"string", "abc"},
{"normalizedString", "abc"},
{"token", "abc"},
{"language", "en"},
{"Name", "abc"},
{"NCName", "abc"},
{"ID", "abc"},
{"ENTITY", "abc"},
{"NMTOKEN", "abc"},
{"boolean", "true"},
{"decimal", "1"},
{"integer", "1"},
{"nonPositiveInteger", "0"},
{"negativeInteger", "-1"},
{"long", "9223372036854775807"},
{"int", "2147483647"},
{"short", "32767"},
{"byte", "127"},
{"nonNegativeInteger", "0"},
{"unsignedLong", "18446744073709551615"},
{"unsignedInt", "4294967295"},
{"unsignedShort", "65535"},
{"unsignedByte", "255"},
{"positiveInteger", "1"},
{"float", "1.1"},
{"double", "1.1"},
{"time", "00:00:00"},
{"date", "1999-12-31"},
{"dateTime", "1999-12-31T00:00:00.000"},
{"duration", "P1Y2M3DT10H30M"},
{"gYearMonth", "1999-01"},
{"gYear", "1999"},
{"gMonthDay", "--12-31"},
{"gMonth", "--12"},
{"gDay", "---31"},
{"base64Binary", "AbCd eFgH IjKl 019+"},
{"hexBinary", "0123456789ABCDEF"},
{"anyURI", "https://www.server.com"},
{"QName", "xml:abc"},
};
// FIXME: implement validation
Dictionary<string, string> invalidValues = new Dictionary<string, string> {
{"Name", "***"},
{"NCName", "a::"},
{"ID", "123"},
{"ENTITY", "***"},
{"NMTOKEN", "***"},
{"boolean", "ABC"},
{"decimal", "1A"},
{"integer", "1.5"},
{"nonPositiveInteger", "5"},
{"negativeInteger", "10"},
{"long", "999999999999999999999999999999999999999"},
{"int", "999999999999999999999999999999999999999"},
{"short", "32768"},
{"byte", "128"},
{"nonNegativeInteger", "-1"},
{"unsignedLong", "-1"},
{"unsignedInt", "-1"},
{"unsignedShort", "-1"},
{"unsignedByte", "-1"},
{"positiveInteger", "0"},
{"float", "1.1x"},
{"double", "1.1x"},
{"time", "0"},
{"date", "1"},
{"dateTime", "2"},
{"duration", "P1"},
{"gYearMonth", "1999"},
{"gYear", "-1"},
{"gMonthDay", "-12-31"},
{"gMonth", "-12"},
{"gDay", "--31"},
{"base64Binary", "####"},
{"hexBinary", "G"},
// anyURI passes everything (as long as I observed)
{"QName", "::"},
};
const string schemaTemplate = @"
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' elementFormDefault='qualified'>
<xs:element name='EL'>
<xs:complexType>
<xs:attribute name='attr' type='xs:{0}' use='required' />
</xs:complexType>
</xs:element>
</xs:schema>";
const string documentTemplate = @"<EL attr='{0}' />";
foreach (var type in validValues.Keys) {
try {
var schema = string.Format (schemaTemplate, type);
var document = string.Format (documentTemplate, validValues[type]);
var schemaSet = new XmlSchemaSet ();
using (var reader = new StringReader (schema))
schemaSet.Add (XmlSchema.Read (reader, null));
schemaSet.Compile ();
var doc = new XmlDocument ();
using (var reader = new StringReader (document))
doc.Load (reader);
doc.Schemas = schemaSet;
doc.Validate (null);
// FIXME: implement validation
/*
if (!invalidValues.ContainsKey (type))
continue;
try {
doc = new XmlDocument ();
document = string.Format (documentTemplate, invalidValues [type]);
using (var reader = new StringReader (document))
doc.Load (reader);
doc.Schemas = schemaSet;
doc.Validate (null);
Assert.Fail (string.Format ("Failed to invalidate {0} for {1}", document, type));
} catch (XmlSchemaException) {
}
*/
} catch (Exception) {
Console.Error.WriteLine (type);
throw;
}
}
}
}
}
| |
/*
* 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:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A user or group that can log in xapi
/// First published in XenServer 5.5.
/// </summary>
public partial class Subject : XenObject<Subject>
{
#region Constructors
public Subject()
{
}
public Subject(string uuid,
string subject_identifier,
Dictionary<string, string> other_config,
List<XenRef<Role>> roles)
{
this.uuid = uuid;
this.subject_identifier = subject_identifier;
this.other_config = other_config;
this.roles = roles;
}
/// <summary>
/// Creates a new Subject from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Subject(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Subject from a Proxy_Subject.
/// </summary>
/// <param name="proxy"></param>
public Subject(Proxy_Subject proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Subject.
/// </summary>
public override void UpdateFrom(Subject update)
{
uuid = update.uuid;
subject_identifier = update.subject_identifier;
other_config = update.other_config;
roles = update.roles;
}
internal void UpdateFrom(Proxy_Subject proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
subject_identifier = proxy.subject_identifier == null ? null : proxy.subject_identifier;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
roles = proxy.roles == null ? null : XenRef<Role>.Create(proxy.roles);
}
public Proxy_Subject ToProxy()
{
Proxy_Subject result_ = new Proxy_Subject();
result_.uuid = uuid ?? "";
result_.subject_identifier = subject_identifier ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.roles = roles == null ? new string[] {} : Helper.RefListToStringArray(roles);
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Subject
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("subject_identifier"))
subject_identifier = Marshalling.ParseString(table, "subject_identifier");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("roles"))
roles = Marshalling.ParseSetRef<Role>(table, "roles");
}
public bool DeepEquals(Subject other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._subject_identifier, other._subject_identifier) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._roles, other._roles);
}
internal static List<Subject> ProxyArrayToObjectList(Proxy_Subject[] input)
{
var result = new List<Subject>();
foreach (var item in input)
result.Add(new Subject(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Subject server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given subject.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_subject">The opaque_ref of the given subject</param>
public static Subject get_record(Session session, string _subject)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.subject_get_record(session.opaque_ref, _subject);
else
return new Subject(session.XmlRpcProxy.subject_get_record(session.opaque_ref, _subject ?? "").parse());
}
/// <summary>
/// Get a reference to the subject instance with the specified UUID.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Subject> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.subject_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Subject>.Create(session.XmlRpcProxy.subject_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new subject instance, and return its handle.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Subject> create(Session session, Subject _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.subject_create(session.opaque_ref, _record);
else
return XenRef<Subject>.Create(session.XmlRpcProxy.subject_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new subject instance, and return its handle.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, Subject _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_subject_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_subject_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified subject instance.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_subject">The opaque_ref of the given subject</param>
public static void destroy(Session session, string _subject)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.subject_destroy(session.opaque_ref, _subject);
else
session.XmlRpcProxy.subject_destroy(session.opaque_ref, _subject ?? "").parse();
}
/// <summary>
/// Destroy the specified subject instance.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_subject">The opaque_ref of the given subject</param>
public static XenRef<Task> async_destroy(Session session, string _subject)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_subject_destroy(session.opaque_ref, _subject);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_subject_destroy(session.opaque_ref, _subject ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given subject.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_subject">The opaque_ref of the given subject</param>
public static string get_uuid(Session session, string _subject)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.subject_get_uuid(session.opaque_ref, _subject);
else
return session.XmlRpcProxy.subject_get_uuid(session.opaque_ref, _subject ?? "").parse();
}
/// <summary>
/// Get the subject_identifier field of the given subject.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_subject">The opaque_ref of the given subject</param>
public static string get_subject_identifier(Session session, string _subject)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.subject_get_subject_identifier(session.opaque_ref, _subject);
else
return session.XmlRpcProxy.subject_get_subject_identifier(session.opaque_ref, _subject ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given subject.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_subject">The opaque_ref of the given subject</param>
public static Dictionary<string, string> get_other_config(Session session, string _subject)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.subject_get_other_config(session.opaque_ref, _subject);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.subject_get_other_config(session.opaque_ref, _subject ?? "").parse());
}
/// <summary>
/// Get the roles field of the given subject.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_subject">The opaque_ref of the given subject</param>
public static List<XenRef<Role>> get_roles(Session session, string _subject)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.subject_get_roles(session.opaque_ref, _subject);
else
return XenRef<Role>.Create(session.XmlRpcProxy.subject_get_roles(session.opaque_ref, _subject ?? "").parse());
}
/// <summary>
/// This call adds a new role to a subject
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_subject">The opaque_ref of the given subject</param>
/// <param name="_role">The unique role reference</param>
public static void add_to_roles(Session session, string _subject, string _role)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.subject_add_to_roles(session.opaque_ref, _subject, _role);
else
session.XmlRpcProxy.subject_add_to_roles(session.opaque_ref, _subject ?? "", _role ?? "").parse();
}
/// <summary>
/// This call removes a role from a subject
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_subject">The opaque_ref of the given subject</param>
/// <param name="_role">The unique role reference in the subject's roles field</param>
public static void remove_from_roles(Session session, string _subject, string _role)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.subject_remove_from_roles(session.opaque_ref, _subject, _role);
else
session.XmlRpcProxy.subject_remove_from_roles(session.opaque_ref, _subject ?? "", _role ?? "").parse();
}
/// <summary>
/// This call returns a list of permission names given a subject
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_subject">The opaque_ref of the given subject</param>
public static string[] get_permissions_name_label(Session session, string _subject)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.subject_get_permissions_name_label(session.opaque_ref, _subject);
else
return (string [])session.XmlRpcProxy.subject_get_permissions_name_label(session.opaque_ref, _subject ?? "").parse();
}
/// <summary>
/// Return a list of all the subjects known to the system.
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Subject>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.subject_get_all(session.opaque_ref);
else
return XenRef<Subject>.Create(session.XmlRpcProxy.subject_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the subject Records at once, in a single XML RPC call
/// First published in XenServer 5.5.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Subject>, Subject> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.subject_get_all_records(session.opaque_ref);
else
return XenRef<Subject>.Create<Proxy_Subject>(session.XmlRpcProxy.subject_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// the subject identifier, unique in the external directory service
/// </summary>
public virtual string subject_identifier
{
get { return _subject_identifier; }
set
{
if (!Helper.AreEqual(value, _subject_identifier))
{
_subject_identifier = value;
NotifyPropertyChanged("subject_identifier");
}
}
}
private string _subject_identifier = "";
/// <summary>
/// additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// the roles associated with this subject
/// First published in XenServer 5.6.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Role>))]
public virtual List<XenRef<Role>> roles
{
get { return _roles; }
set
{
if (!Helper.AreEqual(value, _roles))
{
_roles = value;
NotifyPropertyChanged("roles");
}
}
}
private List<XenRef<Role>> _roles = new List<XenRef<Role>>() {new XenRef<Role>("OpaqueRef:0165f154-ba3e-034e-6b27-5d271af109ba")};
}
}
| |
//
// Copyright (C) 2009 Amr Hassan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Xml;
using System.Collections.Generic;
namespace UB.LastFM.Services
{
public class Tag : Base, System.IEquatable<Tag>, IHasWeeklyArtistCharts, IHasURL
{
/// <summary>
/// The tag name.
/// </summary>
public string Name {get; private set;}
public Tag(string name, Session session)
:base(session)
{
Name = name;
}
internal override RequestParameters getParams ()
{
RequestParameters p = new RequestParameters();
p["tag"] = this.Name;
return p;
}
/// <summary>
/// String representation of the object.
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public override string ToString ()
{
return this.Name;
}
/// <summary>
/// Returns similar tags.
/// </summary>
/// <returns>
/// A <see cref="Tag"/>
/// </returns>
public Tag[] GetSimilar()
{
XmlDocument doc = request("tag.getSimilar");
List<Tag> list = new List<Tag>();
foreach(string name in extractAll(doc, "name"))
list.Add(new Tag(name, Session));
return list.ToArray();
}
/// <summary>
/// Returns the top albums tagged with this tag.
/// </summary>
/// <returns>
/// A <see cref="TopAlbum"/>
/// </returns>
public TopAlbum[] GetTopAlbums()
{
XmlDocument doc = request("tag.getTopAlbums");
List<TopAlbum> list = new List<TopAlbum>();
foreach(XmlNode n in doc.GetElementsByTagName("album"))
{
Album album = new Album(extract(n, "name", 1), extract(n, "name"), Session);
int count = Int32.Parse(extract(n, "tagcount"));
list.Add(new TopAlbum(album, count));
}
return list.ToArray();
}
/// <summary>
/// Returns the top artists tagged with this tag.
/// </summary>
/// <returns>
/// A <see cref="TopArtist"/>
/// </returns>
public TopArtist[] GetTopArtists()
{
XmlDocument doc = request("tag.getTopArtists");
List<TopArtist> list = new List<TopArtist>();
foreach(XmlNode node in doc.GetElementsByTagName("artist"))
{
Artist artist = new Artist(extract(node, "name"), Session);
int count = int.Parse(extract(node, "tagcount"));
list.Add(new TopArtist(artist, count));
}
return list.ToArray();
}
/// <summary>
/// Returns the top tracks tagged with this track.
/// </summary>
/// <returns>
/// A <see cref="TopTrack"/>
/// </returns>
public TopTrack[] GetTopTracks()
{
XmlDocument doc = request("tag.getTopTracks");
List<TopTrack> list = new List<TopTrack>();
foreach(XmlNode n in doc.GetElementsByTagName("track"))
{
int weight = int.Parse(extract(n, "tagcount"));
Track track = new Track(extract(n, "name", 1), extract(n, "name"), Session);
list.Add(new TopTrack(track, weight));
}
return list.ToArray();
}
/// <summary>
/// Check to see if this object equals another.
/// </summary>
/// <param name="tag">
/// A <see cref="Tag"/>
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public bool Equals(Tag tag)
{
if (tag.Name == this.Name)
return true;
else
return false;
}
/// <summary>
/// Search for tags by name.
/// </summary>
/// <param name="name">
/// A <see cref="System.String"/>
/// </param>
/// <param name="session">
/// A <see cref="Session"/>
/// </param>
/// <returns>
/// A <see cref="TagSearch"/>
/// </returns>
public static TagSearch Search(string name, Session session)
{
return new TagSearch(name, session);
}
/// <summary>
/// Returns the available weekly chart time spans (weeks) for this tag.
/// </summary>
/// <returns>
/// A <see cref="WeeklyChartTimeSpan"/>
/// </returns>
public WeeklyChartTimeSpan[] GetWeeklyChartTimeSpans()
{
XmlDocument doc = request("tag.getWeeklyChartList");
List<WeeklyChartTimeSpan> list = new List<WeeklyChartTimeSpan>();
foreach(XmlNode node in doc.GetElementsByTagName("chart"))
{
long lfrom = long.Parse(node.Attributes[0].InnerText);
long lto = long.Parse(node.Attributes[1].InnerText);
DateTime from = Utilities.TimestampToDateTime(lfrom, DateTimeKind.Utc);
DateTime to = Utilities.TimestampToDateTime(lto, DateTimeKind.Utc);
list.Add(new WeeklyChartTimeSpan(from, to));
}
return list.ToArray();
}
/// <summary>
/// Returns the latest weekly artist chart.
/// </summary>
/// <returns>
/// A <see cref="WeeklyArtistChart"/>
/// </returns>
public WeeklyArtistChart GetWeeklyArtistChart()
{
XmlDocument doc = request("tag.getWeeklyArtistChart");
XmlNode n = doc.GetElementsByTagName("weeklyartistchart")[0];
DateTime nfrom = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[1].InnerText), DateTimeKind.Utc);
DateTime nto = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[2].InnerText), DateTimeKind.Utc);
WeeklyArtistChart chart = new WeeklyArtistChart(new WeeklyChartTimeSpan(nfrom, nto));
foreach(XmlNode node in doc.GetElementsByTagName("artist"))
{
int rank = Int32.Parse(node.Attributes[0].InnerText);
int playcount = Int32.Parse(extract(node, "playcount"));
WeeklyArtistChartItem item =
new WeeklyArtistChartItem(new Artist(extract(node, "name"), Session),
rank, playcount, new WeeklyChartTimeSpan(nfrom, nto));
chart.Add(item);
}
return chart;
}
/// <summary>
/// Returns the weekly artist chart for a specified time span (week).
/// </summary>
/// <param name="span">
/// A <see cref="WeeklyChartTimeSpan"/>
/// </param>
/// <returns>
/// A <see cref="WeeklyArtistChart"/>
/// </returns>
public WeeklyArtistChart GetWeeklyArtistChart(WeeklyChartTimeSpan span)
{
RequestParameters p = getParams();
p["from"] = Utilities.DateTimeToUTCTimestamp(span.From).ToString();
p["to"] = Utilities.DateTimeToUTCTimestamp(span.To).ToString();
XmlDocument doc = request("tag.getWeeklyArtistChart", p);
XmlNode n = doc.GetElementsByTagName("weeklyartistchart")[0];
DateTime nfrom = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[1].InnerText), DateTimeKind.Utc);
DateTime nto = Utilities.TimestampToDateTime(Int64.Parse(n.Attributes[2].InnerText), DateTimeKind.Utc);
WeeklyArtistChart chart = new WeeklyArtistChart(new WeeklyChartTimeSpan(nfrom, nto));
foreach(XmlNode node in doc.GetElementsByTagName("artist"))
{
int rank = Int32.Parse(node.Attributes[0].InnerText);
int playcount = Int32.Parse(extract(node, "playcount"));
WeeklyArtistChartItem item =
new WeeklyArtistChartItem(new Artist(extract(node, "name"), Session),
rank, playcount, new WeeklyChartTimeSpan(nfrom, nto));
chart.Add(item);
}
return chart;
}
/// <summary>
/// Returns the Last.fm page of this object.
/// </summary>
/// <param name="language">
/// A <see cref="SiteLanguage"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public string GetURL(SiteLanguage language)
{
string domain = getSiteDomain(language);
return "http://" + domain + "/tag/" + urlSafe(Name);
}
/// <summary>
/// The object's Last.fm page url.
/// </summary>
public string URL
{ get { return GetURL(SiteLanguage.English); } }
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// 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.Models
{
using System.Linq;
/// <summary>
/// Resource usage statistics for a job.
/// </summary>
public partial class JobStatistics
{
/// <summary>
/// Initializes a new instance of the JobStatistics class.
/// </summary>
public JobStatistics() { }
/// <summary>
/// Initializes a new instance of the JobStatistics class.
/// </summary>
/// <param name="url">The URL of the statistics.</param>
/// <param name="startTime">The start time of the time range covered
/// by the statistics.</param>
/// <param name="lastUpdateTime">The time at which the statistics were
/// last updated. All statistics are limited to the range between
/// startTime and lastUpdateTime.</param>
/// <param name="userCPUTime">The total user mode CPU time (summed
/// across all cores and all compute nodes) consumed by all tasks in
/// the job.</param>
/// <param name="kernelCPUTime">The total kernel mode CPU time (summed
/// across all cores and all compute nodes) consumed by all tasks in
/// the job.</param>
/// <param name="wallClockTime">The total wall clock time of all tasks
/// in the job.</param>
/// <param name="readIOps">The total number of disk read operations
/// made by all tasks in the job.</param>
/// <param name="writeIOps">The total number of disk write operations
/// made by all tasks in the job.</param>
/// <param name="readIOGiB">The total gibibytes read from disk by all
/// tasks in the job.</param>
/// <param name="writeIOGiB">The total gibibytes written to disk by
/// all tasks in the job.</param>
/// <param name="numSucceededTasks">The total number of tasks
/// successfully completed in the job during the given time
/// range.</param>
/// <param name="numFailedTasks">The total number of tasks in the job
/// that failed during the given time range.</param>
/// <param name="numTaskRetries">The total number of retries on all
/// the tasks in the job during the given time range.</param>
/// <param name="waitTime">The total wait time of all tasks in the
/// job.</param>
public JobStatistics(string url, System.DateTime startTime, System.DateTime lastUpdateTime, System.TimeSpan userCPUTime, System.TimeSpan kernelCPUTime, System.TimeSpan wallClockTime, long readIOps, long writeIOps, double readIOGiB, double writeIOGiB, long numSucceededTasks, long numFailedTasks, long numTaskRetries, System.TimeSpan waitTime)
{
Url = url;
StartTime = startTime;
LastUpdateTime = lastUpdateTime;
UserCPUTime = userCPUTime;
KernelCPUTime = kernelCPUTime;
WallClockTime = wallClockTime;
ReadIOps = readIOps;
WriteIOps = writeIOps;
ReadIOGiB = readIOGiB;
WriteIOGiB = writeIOGiB;
NumSucceededTasks = numSucceededTasks;
NumFailedTasks = numFailedTasks;
NumTaskRetries = numTaskRetries;
WaitTime = waitTime;
}
/// <summary>
/// Gets or sets the URL of the statistics.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "url")]
public string Url { get; set; }
/// <summary>
/// Gets or sets the start time of the time range covered by the
/// statistics.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "startTime")]
public System.DateTime StartTime { get; set; }
/// <summary>
/// Gets or sets the time at which the statistics were last updated.
/// All statistics are limited to the range between startTime and
/// lastUpdateTime.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "lastUpdateTime")]
public System.DateTime LastUpdateTime { get; set; }
/// <summary>
/// Gets or sets the total user mode CPU time (summed across all cores
/// and all compute nodes) consumed by all tasks in the job.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "userCPUTime")]
public System.TimeSpan UserCPUTime { get; set; }
/// <summary>
/// Gets or sets the total kernel mode CPU time (summed across all
/// cores and all compute nodes) consumed by all tasks in the job.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "kernelCPUTime")]
public System.TimeSpan KernelCPUTime { get; set; }
/// <summary>
/// Gets or sets the total wall clock time of all tasks in the job.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "wallClockTime")]
public System.TimeSpan WallClockTime { get; set; }
/// <summary>
/// Gets or sets the total number of disk read operations made by all
/// tasks in the job.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "readIOps")]
public long ReadIOps { get; set; }
/// <summary>
/// Gets or sets the total number of disk write operations made by all
/// tasks in the job.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "writeIOps")]
public long WriteIOps { get; set; }
/// <summary>
/// Gets or sets the total gibibytes read from disk by all tasks in
/// the job.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "readIOGiB")]
public double ReadIOGiB { get; set; }
/// <summary>
/// Gets or sets the total gibibytes written to disk by all tasks in
/// the job.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "writeIOGiB")]
public double WriteIOGiB { get; set; }
/// <summary>
/// Gets or sets the total number of tasks successfully completed in
/// the job during the given time range.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "numSucceededTasks")]
public long NumSucceededTasks { get; set; }
/// <summary>
/// Gets or sets the total number of tasks in the job that failed
/// during the given time range.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "numFailedTasks")]
public long NumFailedTasks { get; set; }
/// <summary>
/// Gets or sets the total number of retries on all the tasks in the
/// job during the given time range.
/// </summary>
[Newtonsoft.Json.JsonProperty(PropertyName = "numTaskRetries")]
public long NumTaskRetries { get; set; }
/// <summary>
/// Gets or sets the total wait time of all tasks in the job.
/// </summary>
/// <remarks>
/// The wait time for a task is defined as the elapsed time between
/// the creation of the task and the start of task execution. (If the
/// task is retried due to failures, the wait time is the time to the
/// most recent task execution.)
/// </remarks>
[Newtonsoft.Json.JsonProperty(PropertyName = "waitTime")]
public System.TimeSpan WaitTime { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Url == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "Url");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Actions.Calls;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
namespace IronPython.Runtime {
public static partial class Converter {
#region Conversion Sites
private static readonly CallSite<Func<CallSite, object, int>> _intSite = MakeExplicitConvertSite<int>();
private static readonly CallSite<Func<CallSite, object, double>> _doubleSite = MakeExplicitConvertSite<double>();
private static readonly CallSite<Func<CallSite, object, Complex>> _complexSite = MakeExplicitConvertSite<Complex>();
private static readonly CallSite<Func<CallSite, object, BigInteger>> _bigIntSite = MakeExplicitConvertSite<BigInteger>();
private static readonly CallSite<Func<CallSite, object, string>> _stringSite = MakeExplicitConvertSite<string>();
private static readonly CallSite<Func<CallSite, object, bool>> _boolSite = MakeExplicitConvertSite<bool>();
private static readonly CallSite<Func<CallSite, object, char>> _charSite = MakeImplicitConvertSite<char>();
private static readonly CallSite<Func<CallSite, object, char>> _explicitCharSite = MakeExplicitConvertSite<char>();
private static readonly CallSite<Func<CallSite, object, IEnumerable>> _ienumerableSite = MakeImplicitConvertSite<IEnumerable>();
private static readonly CallSite<Func<CallSite, object, IEnumerator>> _ienumeratorSite = MakeImplicitConvertSite<IEnumerator>();
private static readonly Dictionary<Type, CallSite<Func<CallSite, object, object>>> _siteDict = new Dictionary<Type, CallSite<Func<CallSite, object, object>>>();
private static readonly CallSite<Func<CallSite, object, byte>> _byteSite = MakeExplicitConvertSite<byte>();
private static readonly CallSite<Func<CallSite, object, sbyte>> _sbyteSite = MakeExplicitConvertSite<sbyte>();
private static readonly CallSite<Func<CallSite, object, short>> _int16Site = MakeExplicitConvertSite<short>();
private static readonly CallSite<Func<CallSite, object, ushort>> _uint16Site = MakeExplicitConvertSite<ushort>();
private static readonly CallSite<Func<CallSite, object, uint>> _uint32Site = MakeExplicitConvertSite<uint>();
private static readonly CallSite<Func<CallSite, object, long>> _int64Site = MakeExplicitConvertSite<long>();
private static readonly CallSite<Func<CallSite, object, ulong>> _uint64Site = MakeExplicitConvertSite<ulong>();
private static readonly CallSite<Func<CallSite, object, decimal>> _decimalSite = MakeExplicitConvertSite<decimal>();
private static readonly CallSite<Func<CallSite, object, float>> _floatSite = MakeExplicitConvertSite<float>();
private static readonly CallSite<Func<CallSite, object, object>>
_tryByteSite = MakeExplicitTrySite<byte>(),
_trySByteSite = MakeExplicitTrySite<sbyte>(),
_tryInt16Site = MakeExplicitTrySite<short>(),
_tryInt32Site = MakeExplicitTrySite<int>(),
_tryInt64Site = MakeExplicitTrySite<long>(),
_tryUInt16Site = MakeExplicitTrySite<ushort>(),
_tryUInt32Site = MakeExplicitTrySite<uint>(),
_tryUInt64Site = MakeExplicitTrySite<ulong>(),
_tryDoubleSite = MakeExplicitTrySite<double>(),
_tryCharSite = MakeExplicitTrySite<char>(),
_tryBigIntegerSite = MakeExplicitTrySite<BigInteger>(),
_tryComplexSite = MakeExplicitTrySite<Complex>(),
_tryStringSite = MakeExplicitTrySite<string>();
private static CallSite<Func<CallSite, object, T>> MakeImplicitConvertSite<T>() {
return MakeConvertSite<T>(ConversionResultKind.ImplicitCast);
}
private static CallSite<Func<CallSite, object, T>> MakeExplicitConvertSite<T>() {
return MakeConvertSite<T>(ConversionResultKind.ExplicitCast);
}
private static CallSite<Func<CallSite, object, T>> MakeConvertSite<T>(ConversionResultKind kind) {
return CallSite<Func<CallSite, object, T>>.Create(
DefaultContext.DefaultPythonContext.Convert(
typeof(T),
kind
)
);
}
private static CallSite<Func<CallSite, object, object>> MakeExplicitTrySite<T>() {
return MakeTrySite<T>(ConversionResultKind.ExplicitTry);
}
private static CallSite<Func<CallSite, object, object>> MakeTrySite<T>(ConversionResultKind kind) {
return CallSite<Func<CallSite, object, object>>.Create(
DefaultContext.DefaultPythonContext.Convert(
typeof(T),
kind
)
);
}
#endregion
#region Conversion entry points
public static int ConvertToInt32(object value) { return _intSite.Target(_intSite, value); }
public static string ConvertToString(object value) { return _stringSite.Target(_stringSite, value); }
public static BigInteger ConvertToBigInteger(object value) { return _bigIntSite.Target(_bigIntSite, value); }
public static double ConvertToDouble(object value) { return _doubleSite.Target(_doubleSite, value); }
public static Complex ConvertToComplex(object value) { return _complexSite.Target(_complexSite, value); }
public static bool ConvertToBoolean(object value) { return _boolSite.Target(_boolSite, value); }
public static long ConvertToInt64(object value) { return _int64Site.Target(_int64Site, value); }
public static byte ConvertToByte(object value) { return _byteSite.Target(_byteSite, value); }
public static sbyte ConvertToSByte(object value) { return _sbyteSite.Target(_sbyteSite, value); }
public static short ConvertToInt16(object value) { return _int16Site.Target(_int16Site, value); }
public static ushort ConvertToUInt16(object value) { return _uint16Site.Target(_uint16Site, value); }
public static uint ConvertToUInt32(object value) { return _uint32Site.Target(_uint32Site, value); }
public static ulong ConvertToUInt64(object value) { return _uint64Site.Target(_uint64Site, value); }
public static float ConvertToSingle(object value) { return _floatSite.Target(_floatSite, value); }
public static decimal ConvertToDecimal(object value) { return _decimalSite.Target(_decimalSite, value); }
public static char ConvertToChar(object value) { return _charSite.Target(_charSite, value); }
internal static bool TryConvertToByte(object value, out byte result) {
object res = _tryByteSite.Target(_tryByteSite, value);
if (res != null) {
result = (byte)res;
return true;
}
result = default(byte);
return false;
}
internal static bool TryConvertToSByte(object value, out sbyte result) {
object res = _trySByteSite.Target(_trySByteSite, value);
if (res != null) {
result = (sbyte)res;
return true;
}
result = default(sbyte);
return false;
}
internal static bool TryConvertToInt16(object value, out short result) {
object res = _tryInt16Site.Target(_tryInt16Site, value);
if (res != null) {
result = (short)res;
return true;
}
result = default(short);
return false;
}
internal static bool TryConvertToInt32(object value, out int result) {
object res = _tryInt32Site.Target(_tryInt32Site, value);
if (res != null) {
result = (int)res;
return true;
}
result = default(int);
return false;
}
internal static bool TryConvertToInt64(object value, out long result) {
object res = _tryInt64Site.Target(_tryInt64Site, value);
if (res != null) {
result = (long)res;
return true;
}
result = default(long);
return false;
}
internal static bool TryConvertToUInt16(object value, out ushort result) {
object res = _tryUInt16Site.Target(_tryUInt16Site, value);
if (res != null) {
result = (ushort)res;
return true;
}
result = default(ushort);
return false;
}
internal static bool TryConvertToUInt32(object value, out uint result) {
object res = _tryUInt32Site.Target(_tryUInt32Site, value);
if (res != null) {
result = (uint)res;
return true;
}
result = default(uint);
return false;
}
internal static bool TryConvertToUInt64(object value, out ulong result) {
object res = _tryUInt64Site.Target(_tryUInt64Site, value);
if (res != null) {
result = (ulong)res;
return true;
}
result = default(ulong);
return false;
}
internal static bool TryConvertToDouble(object value, out double result) {
object res = _tryDoubleSite.Target(_tryDoubleSite, value);
if (res != null) {
result = (double)res;
return true;
}
result = default(double);
return false;
}
internal static bool TryConvertToBigInteger(object value, out BigInteger result) {
object res = _tryBigIntegerSite.Target(_tryBigIntegerSite, value);
if (res != null) {
result = (BigInteger)res;
return true;
}
result = default(BigInteger);
return false;
}
internal static bool TryConvertToComplex(object value, out Complex result) {
object res = _tryComplexSite.Target(_tryComplexSite, value);
if (res != null) {
result = (Complex)res;
return true;
}
result = default(Complex);
return false;
}
#nullable enable
internal static bool TryConvertToString(object? value, [NotNullWhen(true)] out string? result) {
object res = _tryStringSite.Target(_tryStringSite, value);
if (res != null) {
result = (string)res;
return true;
}
result = default(string);
return false;
}
#nullable restore
internal static bool TryConvertToChar(object value, out char result) {
object res = _tryCharSite.Target(_tryCharSite, value);
if (res != null) {
result = (char)res;
return true;
}
result = default;
return false;
}
#endregion
internal static char ExplicitConvertToChar(object value) {
return _explicitCharSite.Target(_explicitCharSite, value);
}
public static T Convert<T>(object value) {
return (T)Convert(value, typeof(T));
}
internal static bool TryConvert<T>(object value, out T result) {
try {
result = Convert<T>(value);
return true;
} catch {
result = default;
return false;
}
}
/// <summary>
/// General conversion routine TryConvert - tries to convert the object to the desired type.
/// Try to avoid using this method, the goal is to ultimately remove it!
/// </summary>
internal static bool TryConvert(object value, Type to, out object result) {
try {
result = Convert(value, to);
return true;
} catch {
result = default(object);
return false;
}
}
internal static object Convert(object value, Type to) {
CallSite<Func<CallSite, object, object>> site;
lock (_siteDict) {
if (!_siteDict.TryGetValue(to, out site)) {
_siteDict[to] = site = CallSite<Func<CallSite, object, object>>.Create(
DefaultContext.DefaultPythonContext.ConvertRetObject(
to,
ConversionResultKind.ExplicitCast
)
);
}
}
object res = site.Target(site, value);
if (to.IsValueType && res == null &&
(!to.IsGenericType || to.GetGenericTypeDefinition() != typeof(Nullable<>))) {
throw MakeTypeError(to, value);
}
return res;
}
/// <summary>
/// This function tries to convert an object to IEnumerator, or wraps it into an adapter
/// Do not use this function directly. It is only meant to be used by Ops.GetEnumerator.
/// </summary>
internal static bool TryConvertToIEnumerator(object o, out IEnumerator e) {
try {
e = _ienumeratorSite.Target(_ienumeratorSite, o);
return e != null;
} catch {
e = null;
return false;
}
}
/// <summary>
/// This function tries to convert an object to IEnumerator, or wraps it into an adapter
/// Do not use this function directly. It is only meant to be used by Ops.GetEnumerator.
/// </summary>
internal static IEnumerator ConvertToIEnumerator(object o) {
return _ienumeratorSite.Target(_ienumeratorSite, o);
}
public static IEnumerable ConvertToIEnumerable(object o) {
return _ienumerableSite.Target(_ienumerableSite, o);
}
/// <summary>
/// Attempts to convert value into a index usable for slicing and return the integer
/// value. If the conversion fails false is returned.
///
/// If throwOverflowError is true then BigInteger's outside the normal range of integers will
/// result in an OverflowError.
/// </summary>
internal static bool TryConvertToIndex(object value, out int index, bool throwOverflowError = true)
=> TryGetInt(value, out index, throwOverflowError, value)
|| PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, value, "__index__", out object res)
&& TryGetInt(res, out index, throwOverflowError, value);
/// <summary>
/// Attempts to convert value into an index usable for slicing and return the integer or BigInteger
/// value. If the conversion fails false is returned.
/// </summary>
internal static bool TryConvertToIndex(object value, out object index) {
index = ConvertToSliceIndexHelper(value);
if (index == null) {
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, value, "__index__", out object res)) {
index = ConvertToSliceIndexHelper(res);
}
}
return index != null;
}
public static int ConvertToIndex(object value, bool throwOverflowError = false) {
if (TryGetInt(value, out int res, throwOverflowError, value)) {
return res;
}
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, value, "__index__", out object index)) {
if (TryGetInt(index, out res, throwOverflowError, value)) {
return res;
}
throw PythonOps.TypeError("__index__ returned non-int (type {0})", PythonOps.GetPythonTypeName(index));
}
throw PythonOps.TypeError("expected integer value, got {0}", PythonOps.GetPythonTypeName(value));
}
private static bool TryGetInt(object o, out int value, bool throwOverflowError, object original) {
if (o is int i) {
value = i;
} else {
BigInteger bi;
if (o is BigInteger) {
bi = (BigInteger)o;
} else if (o is Extensible<BigInteger> ebi) {
bi = ebi.Value;
} else {
value = default;
return false;
}
if (bi.AsInt32(out value)) return true;
if (throwOverflowError) {
throw PythonOps.OverflowError("cannot fit '{0}' into an index-sized integer", PythonOps.GetPythonTypeName(original));
}
Debug.Assert(bi != 0);
value = bi > 0 ? int.MaxValue : int.MinValue;
}
return true;
}
private static object ConvertToSliceIndexHelper(object value) {
if (value is int) return value;
if (value is BigInteger) {
return value;
} else if (value is Extensible<BigInteger> ebi) {
return ebi.Value;
}
return null;
}
internal static Exception CannotConvertOverflow(string name, object value) {
return PythonOps.OverflowError("Cannot convert {0}({1}) to {2}", PythonOps.GetPythonTypeName(value), value, name);
}
private static Exception MakeTypeError(Type expectedType, object o) {
return MakeTypeError(DynamicHelpers.GetPythonTypeFromType(expectedType).Name.ToString(), o);
}
private static Exception MakeTypeError(string expectedType, object o) {
return PythonOps.TypeErrorForTypeMismatch(expectedType, o);
}
#region Cached Type instances
private static readonly Type StringType = typeof(string);
private static readonly Type Int32Type = typeof(int);
private static readonly Type DoubleType = typeof(double);
private static readonly Type DecimalType = typeof(decimal);
private static readonly Type Int64Type = typeof(long);
private static readonly Type UInt64Type = typeof(ulong);
private static readonly Type CharType = typeof(char);
private static readonly Type SingleType = typeof(float);
private static readonly Type BooleanType = typeof(bool);
private static readonly Type BigIntegerType = typeof(BigInteger);
private static readonly Type ComplexType = typeof(Complex);
private static readonly Type DelegateType = typeof(Delegate);
private static readonly Type IEnumerableType = typeof(IEnumerable);
private static readonly Type TypeType = typeof(Type);
private static readonly Type NullableOfTType = typeof(Nullable<>);
private static readonly Type IListOfTType = typeof(IList<>);
private static readonly Type IDictOfTType = typeof(IDictionary<,>);
private static readonly Type IEnumerableOfTType = typeof(IEnumerable<>);
private static readonly Type IListOfObjectType = typeof(IList<object>);
private static readonly Type IEnumerableOfObjectType = typeof(IEnumerable<object>);
private static readonly Type IDictionaryOfObjectType = typeof(IDictionary<object, object>);
#endregion
#region Entry points called from the generated code
public static object ConvertToReferenceType(object fromObject, RuntimeTypeHandle typeHandle) {
if (fromObject == null) return null;
return Convert(fromObject, Type.GetTypeFromHandle(typeHandle));
}
public static object ConvertToNullableType(object fromObject, RuntimeTypeHandle typeHandle) {
if (fromObject == null) return null;
return Convert(fromObject, Type.GetTypeFromHandle(typeHandle));
}
public static object ConvertToValueType(object fromObject, RuntimeTypeHandle typeHandle) {
if (fromObject == null) throw PythonOps.InvalidType(fromObject, typeHandle);
return Convert(fromObject, Type.GetTypeFromHandle(typeHandle));
}
public static Type ConvertToType(object value) {
if (value == null) return null;
if (value is Type typeVal) return typeVal;
if (value is PythonType pythonTypeVal) return pythonTypeVal.UnderlyingSystemType;
if (value is TypeGroup typeCollision) {
if (typeCollision.TryGetNonGenericType(out Type nonGenericType)) {
return nonGenericType;
}
}
throw MakeTypeError("Type", value);
}
public static object ConvertToDelegate(object value, Type to) {
if (value == null) return null;
return DefaultContext.DefaultCLS.LanguageContext.DelegateCreator.GetDelegate(value, to);
}
#endregion
public static bool CanConvertFrom(Type fromType, Type toType, NarrowingLevel allowNarrowing) {
ContractUtils.RequiresNotNull(fromType, nameof(fromType));
ContractUtils.RequiresNotNull(toType, nameof(toType));
if (toType == fromType) return true;
if (toType.IsAssignableFrom(fromType)) return true;
#if FEATURE_COM
if (fromType.IsCOMObject && toType.IsInterface) return true; // A COM object could be cast to any interface
#endif
if (HasImplicitNumericConversion(fromType, toType)) return true;
// Handling the hole that Type is the only object that we 'box'
if (toType == TypeType &&
(typeof(PythonType).IsAssignableFrom(fromType) ||
typeof(TypeGroup).IsAssignableFrom(fromType))) return true;
// Support extensible types with simple implicit conversions to their base types
if (typeof(Extensible<BigInteger>).IsAssignableFrom(fromType) && CanConvertFrom(BigIntegerType, toType, allowNarrowing)) {
return true;
}
if (typeof(ExtensibleString).IsAssignableFrom(fromType) && CanConvertFrom(StringType, toType, allowNarrowing)) {
return true;
}
if (typeof(Extensible<double>).IsAssignableFrom(fromType) && CanConvertFrom(DoubleType, toType, allowNarrowing)) {
return true;
}
if (typeof(Extensible<Complex>).IsAssignableFrom(fromType) && CanConvertFrom(ComplexType, toType, allowNarrowing)) {
return true;
}
#if FEATURE_CUSTOM_TYPE_DESCRIPTOR
// try available type conversions...
object[] tcas = toType.GetCustomAttributes(typeof(TypeConverterAttribute), true);
foreach (TypeConverterAttribute tca in tcas) {
TypeConverter tc = GetTypeConverter(tca);
if (tc == null) continue;
if (tc.CanConvertFrom(fromType)) {
return true;
}
}
#endif
//!!!do user-defined implicit conversions here
if (allowNarrowing == PythonNarrowing.None) return false;
return HasNarrowingConversion(fromType, toType, allowNarrowing);
}
#if FEATURE_CUSTOM_TYPE_DESCRIPTOR
private static TypeConverter GetTypeConverter(TypeConverterAttribute tca) {
try {
ConstructorInfo ci = Type.GetType(tca.ConverterTypeName).GetConstructor(ReflectionUtils.EmptyTypes);
if (ci != null) return ci.Invoke(ArrayUtils.EmptyObjects) as TypeConverter;
} catch (TargetInvocationException) {
}
return null;
}
#endif
private static bool HasImplicitNumericConversion(Type fromType, Type toType) {
if (fromType.IsEnum) return false;
if (fromType == typeof(BigInteger)) {
if (toType == typeof(double)) return true;
if (toType == typeof(Complex)) return true;
return false;
}
if (fromType == typeof(bool)) {
if (toType == typeof(int)) return true;
return HasImplicitNumericConversion(typeof(int), toType);
}
switch (fromType.GetTypeCode()) {
case TypeCode.SByte:
switch (toType.GetTypeCode()) {
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Byte:
switch (toType.GetTypeCode()) {
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Int16:
switch (toType.GetTypeCode()) {
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.UInt16:
switch (toType.GetTypeCode()) {
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Int32:
switch (toType.GetTypeCode()) {
case TypeCode.Int64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.UInt32:
switch (toType.GetTypeCode()) {
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Int64:
switch (toType.GetTypeCode()) {
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.UInt64:
switch (toType.GetTypeCode()) {
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Char:
switch (toType.GetTypeCode()) {
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
if (toType == BigIntegerType) return true;
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Single:
switch (toType.GetTypeCode()) {
case TypeCode.Double:
return true;
default:
if (toType == ComplexType) return true;
return false;
}
case TypeCode.Double:
switch (toType.GetTypeCode()) {
default:
if (toType == ComplexType) return true;
return false;
}
default:
return false;
}
}
public static Candidate PreferConvert(Type t1, Type t2) {
if (t1 == typeof(bool) && t2 == typeof(int)) return Candidate.Two;
if (t1 == typeof(decimal) && t2 == typeof(BigInteger)) return Candidate.Two;
//if (t1 == typeof(int) && t2 == typeof(BigInteger)) return Candidate.Two;
switch (t1.GetTypeCode()) {
case TypeCode.SByte:
switch (t2.GetTypeCode()) {
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return Candidate.Two;
default:
return Candidate.Equivalent;
}
case TypeCode.Int16:
switch (t2.GetTypeCode()) {
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return Candidate.Two;
default:
return Candidate.Equivalent;
}
case TypeCode.Int32:
switch (t2.GetTypeCode()) {
case TypeCode.UInt32:
case TypeCode.UInt64:
return Candidate.Two;
default:
return Candidate.Equivalent;
}
case TypeCode.Int64:
switch (t2.GetTypeCode()) {
case TypeCode.UInt64:
return Candidate.Two;
default:
return Candidate.Equivalent;
}
}
return Candidate.Equivalent;
}
private static bool HasNarrowingConversion(Type fromType, Type toType, NarrowingLevel allowNarrowing) {
if (allowNarrowing == PythonNarrowing.IndexOperator) {
if (toType == CharType && fromType == StringType) return true;
if (toType == StringType && fromType == CharType) return true;
//if (toType == Int32Type && fromType == BigIntegerType) return true;
//if (IsIntegral(fromType) && IsIntegral(toType)) return true;
//Check if there is an implicit convertor defined on fromType to toType
if (HasImplicitConversion(fromType, toType)) {
return true;
}
}
if (toType == DoubleType || toType == SingleType) {
if (IsNumeric(fromType) && fromType != ComplexType) return true;
}
if (toType.IsArray) {
return typeof(PythonTuple).IsAssignableFrom(fromType);
}
if (allowNarrowing == PythonNarrowing.IndexOperator) {
if (IsNumeric(fromType) && IsNumeric(toType)) {
if (fromType != typeof(float) && fromType != typeof(double) && fromType != typeof(decimal) && fromType != typeof(Complex)) {
return true;
}
}
if (fromType == typeof(bool) && IsNumeric(toType)) return true;
if (toType == CharType && fromType == StringType) return true;
if (toType == Int32Type && fromType == BooleanType) return true;
// Everything can convert to Boolean in Python
if (toType == BooleanType) return true;
if (DelegateType.IsAssignableFrom(toType) && IsPythonType(fromType)) return true;
if (IEnumerableType == toType && IsPythonType(fromType)) return true;
if (toType == typeof(IEnumerator)) {
if (IsPythonType(fromType)) return true;
} else if (toType.IsGenericType) {
Type genTo = toType.GetGenericTypeDefinition();
if (genTo == IEnumerableOfTType) {
return IEnumerableOfObjectType.IsAssignableFrom(fromType) ||
IEnumerableType.IsAssignableFrom(fromType);
} else if (genTo == typeof(System.Collections.Generic.IEnumerator<>)) {
if (IsPythonType(fromType)) return true;
}
}
}
if (allowNarrowing == PythonNarrowing.All) {
//__int__, __float__; __long__ is obsolete
if (IsNumeric(fromType) && IsNumeric(toType)) {
if ((toType == Int32Type || toType == BigIntegerType) &&
(fromType == DoubleType || typeof(Extensible<double>).IsAssignableFrom(fromType))) return false;
return true;
}
if (toType == Int32Type && HasPythonProtocol(fromType, "__int__")) return true;
if (toType == DoubleType && HasPythonProtocol(fromType, "__float__")) return true;
if (toType == BigIntegerType && HasPythonProtocol(fromType, "__int__")) return true;
}
if (toType.IsGenericType) {
Type genTo = toType.GetGenericTypeDefinition();
if (genTo == IListOfTType) {
return IListOfObjectType.IsAssignableFrom(fromType);
} else if (genTo == NullableOfTType) {
if (fromType == typeof(DynamicNull) || CanConvertFrom(fromType, toType.GetGenericArguments()[0], allowNarrowing)) {
return true;
}
} else if (genTo == IDictOfTType) {
return IDictionaryOfObjectType.IsAssignableFrom(fromType);
}
}
if (fromType == BigIntegerType && toType == Int64Type) return true;
if (fromType == BigIntegerType && toType == UInt64Type) return true;
if (toType.IsEnum && fromType == Enum.GetUnderlyingType(toType)) return true;
return false;
}
internal static bool HasImplicitConversion(Type fromType, Type toType) {
return
HasImplicitConversionWorker(fromType, fromType, toType) ||
HasImplicitConversionWorker(toType, fromType, toType);
}
private static bool HasImplicitConversionWorker(Type lookupType, Type fromType, Type toType) {
while (lookupType != null) {
foreach (MethodInfo method in lookupType.GetMethods()) {
if (method.Name == "op_Implicit" &&
method.GetParameters()[0].ParameterType.IsAssignableFrom(fromType) &&
toType.IsAssignableFrom(method.ReturnType)) {
return true;
}
}
lookupType = lookupType.BaseType;
}
return false;
}
/// <summary>
/// Converts a value to int ignoring floats
/// </summary>
public static int? ImplicitConvertToInt32(object o) {
if (o is int i32) {
return i32;
} else if (o is BigInteger bi) {
if (bi.AsInt32(out int res)) {
return res;
}
} else if (o is Extensible<BigInteger>) {
if (Converter.TryConvertToInt32(o, out int res)) {
return res;
}
}
if (!(o is double) && !(o is float) && !(o is Extensible<double>)) {
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, o, "__int__", out object objres)) {
if (objres is int res) {
return res;
}
}
}
return null;
}
internal static bool IsNumeric(Type t) {
if (t.IsEnum) return false;
switch (t.GetTypeCode()) {
case TypeCode.DateTime:
case TypeCode.DBNull:
case TypeCode.Char:
case TypeCode.Empty:
case TypeCode.String:
case TypeCode.Boolean:
return false;
case TypeCode.Object:
return t == BigIntegerType || t == ComplexType;
default:
return true;
}
}
internal static bool IsFloatingPoint(Type t) {
switch (t.GetTypeCode()) {
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.Decimal:
return true;
case TypeCode.Object:
return t == ComplexType;
default:
return false;
}
}
internal static bool IsInteger(Type t) {
return IsNumeric(t) && !IsFloatingPoint(t);
}
private static bool IsPythonType(Type t) {
return t.FullName.StartsWith("IronPython.", StringComparison.Ordinal); //!!! this and the check below are hacks
}
private static bool HasPythonProtocol(Type t, string name) {
if (t.FullName.StartsWith(NewTypeMaker.TypePrefix, StringComparison.Ordinal)) return true;
PythonType dt = DynamicHelpers.GetPythonTypeFromType(t);
if (dt == null) return false;
return dt.TryResolveSlot(DefaultContext.Default, name, out _);
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace ASC.Mail.Net.SIP.Proxy
{
#region usings
using System;
using Message;
using Stack;
#endregion
/// <summary>
/// This class represents B2BUA call.
/// </summary>
public class SIP_B2BUA_Call
{
#region Members
private readonly string m_CallID = "";
private readonly SIP_B2BUA m_pOwner;
private readonly DateTime m_StartTime;
private bool m_IsTerminated;
private SIP_Dialog m_pCallee;
private SIP_Dialog m_pCaller;
#endregion
#region Properties
/// <summary>
/// Gets call start time.
/// </summary>
public DateTime StartTime
{
get { return m_StartTime; }
}
/// <summary>
/// Gets current call ID.
/// </summary>
public string CallID
{
get { return m_CallID; }
}
/// <summary>
/// Gets caller SIP dialog.
/// </summary>
public SIP_Dialog CallerDialog
{
get { return m_pCaller; }
}
/// <summary>
/// Gets callee SIP dialog.
/// </summary>
public SIP_Dialog CalleeDialog
{
get { return m_pCallee; }
}
/// <summary>
/// Gets if call has timed out and needs to be terminated.
/// </summary>
public bool IsTimedOut
{
// TODO:
get { return false; }
}
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="owner">Owner B2BUA server.</param>
/// <param name="caller">Caller side dialog.</param>
/// <param name="callee">Callee side dialog.</param>
internal SIP_B2BUA_Call(SIP_B2BUA owner, SIP_Dialog caller, SIP_Dialog callee)
{
m_pOwner = owner;
m_pCaller = caller;
m_pCallee = callee;
m_StartTime = DateTime.Now;
m_CallID = Guid.NewGuid().ToString().Replace("-", "");
//m_pCaller.RequestReceived += new SIP_RequestReceivedEventHandler(m_pCaller_RequestReceived);
//m_pCaller.Terminated += new EventHandler(m_pCaller_Terminated);
//m_pCallee.RequestReceived += new SIP_RequestReceivedEventHandler(m_pCallee_RequestReceived);
//m_pCallee.Terminated += new EventHandler(m_pCallee_Terminated);
}
#endregion
#region Methods
/// <summary>
/// Terminates call.
/// </summary>
public void Terminate()
{
if (m_IsTerminated)
{
return;
}
m_IsTerminated = true;
m_pOwner.RemoveCall(this);
if (m_pCaller != null)
{
//m_pCaller.Terminate();
m_pCaller.Dispose();
m_pCaller = null;
}
if (m_pCallee != null)
{
//m_pCallee.Terminate();
m_pCallee.Dispose();
m_pCallee = null;
}
m_pOwner.OnCallTerminated(this);
}
#endregion
#region Utility methods
/// <summary>
/// Is called when caller sends new request.
/// </summary>
/// <param name="e">Event data.</param>
private void m_pCaller_RequestReceived(SIP_RequestReceivedEventArgs e)
{
// TODO: If we get UPDATE, but callee won't support it ? generate INVITE instead ?
/*
SIP_Request request = m_pCallee.CreateRequest(e.Request.RequestLine.Method);
CopyMessage(e.Request,request,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Max-Forwards:","Allow:","Require:","Supported:"});
// Remove our Authentication header if it's there.
foreach(SIP_SingleValueHF<SIP_t_Credentials> header in request.ProxyAuthorization.HeaderFields){
try{
Auth_HttpDigest digest = new Auth_HttpDigest(header.ValueX.AuthData,request.RequestLine.Method);
if(m_pOwner.Stack.Realm == digest.Realm){
request.ProxyAuthorization.Remove(header);
}
}
catch{
// We don't care errors here. This can happen if remote server xxx auth method here and
// we don't know how to parse it, so we leave it as is.
}
}
SIP_ClientTransaction clientTransaction = m_pCallee.CreateTransaction(request);
clientTransaction.ResponseReceived += new EventHandler<SIP_ResponseReceivedEventArgs>(m_pCallee_ResponseReceived);
clientTransaction.Tag = e.ServerTransaction;
clientTransaction.Start();*/
}
/// <summary>
/// This method is called when caller dialog has terminated, normally this happens
/// when dialog gets BYE request.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pCaller_Terminated(object sender, EventArgs e)
{
Terminate();
}
/// <summary>
/// This method is called when callee dialog client transaction receives response.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pCallee_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e)
{
SIP_ServerTransaction serverTransaction = (SIP_ServerTransaction) e.ClientTransaction.Tag;
//SIP_Response response = serverTransaction.Request.CreateResponse(e.Response.StatusCode_ReasonPhrase);
//CopyMessage(e.Response,response,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Allow:","Supported:"});
//serverTransaction.SendResponse(response);
}
/// <summary>
/// Is called when callee sends new request.
/// </summary>
/// <param name="e">Event data.</param>
private void m_pCallee_RequestReceived(SIP_RequestReceivedEventArgs e)
{
/*
SIP_Request request = m_pCaller.CreateRequest(e.Request.RequestLine.Method);
CopyMessage(e.Request,request,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Max-Forwards:","Allow:","Require:","Supported:"});
// Remove our Authentication header if it's there.
foreach(SIP_SingleValueHF<SIP_t_Credentials> header in request.ProxyAuthorization.HeaderFields){
try{
Auth_HttpDigest digest = new Auth_HttpDigest(header.ValueX.AuthData,request.RequestLine.Method);
if(m_pOwner.Stack.Realm == digest.Realm){
request.ProxyAuthorization.Remove(header);
}
}
catch{
// We don't care errors here. This can happen if remote server xxx auth method here and
// we don't know how to parse it, so we leave it as is.
}
}
SIP_ClientTransaction clientTransaction = m_pCaller.CreateTransaction(request);
clientTransaction.ResponseReceived += new EventHandler<SIP_ResponseReceivedEventArgs>(m_pCaller_ResponseReceived);
clientTransaction.Tag = e.ServerTransaction;
clientTransaction.Start();*/
}
/// <summary>
/// This method is called when callee dialog has terminated, normally this happens
/// when dialog gets BYE request.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pCallee_Terminated(object sender, EventArgs e)
{
Terminate();
}
/// <summary>
/// This method is called when caller dialog client transaction receives response.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pCaller_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e)
{
SIP_ServerTransaction serverTransaction = (SIP_ServerTransaction) e.ClientTransaction.Tag;
//SIP_Response response = serverTransaction.Request.CreateResponse(e.Response.StatusCode_ReasonPhrase);
//CopyMessage(e.Response,response,new string[]{"Via:","Call-Id:","To:","From:","CSeq:","Contact:","Route:","Record-Route:","Allow:","Supported:"});
//serverTransaction.SendResponse(response);
}
/*
/// <summary>
/// Transfers call to specified recipient.
/// </summary>
/// <param name="to">Address where to transfer call.</param>
public void CallTransfer(string to)
{
throw new NotImplementedException();
}*/
/// <summary>
/// Copies header fileds from 1 message to antother.
/// </summary>
/// <param name="source">Source message.</param>
/// <param name="destination">Destination message.</param>
/// <param name="exceptHeaders">Header fields not to copy.</param>
private void CopyMessage(SIP_Message source, SIP_Message destination, string[] exceptHeaders)
{
foreach (SIP_HeaderField headerField in source.Header)
{
bool copy = true;
foreach (string h in exceptHeaders)
{
if (h.ToLower() == headerField.Name.ToLower())
{
copy = false;
break;
}
}
if (copy)
{
destination.Header.Add(headerField.Name, headerField.Value);
}
}
destination.Data = source.Data;
}
#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 log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BasicInventoryAccessModule")]
public class BasicInventoryAccessModule : INonSharedRegionModule, IInventoryAccessModule
{
protected bool m_Enabled = false;
protected Scene m_Scene;
protected IUserManagement m_UserManagement;
private string m_ThisGatekeeper = "";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public bool CoalesceMultipleObjectsToInventory { get; set; }
protected IUserManagement UserManagementModule
{
get
{
if (m_UserManagement == null)
m_UserManagement = m_Scene.RequestModuleInterface<IUserManagement>();
return m_UserManagement;
}
}
#region INonSharedRegionModule
public virtual string Name
{
get { return "BasicInventoryAccessModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public virtual void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scene = scene;
scene.RegisterModuleInterface<IInventoryAccessModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
}
public virtual void Close()
{
if (!m_Enabled)
return;
}
public virtual void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryAccessModule", "");
if (name == Name)
{
m_Enabled = true;
InitialiseCommon(source);
m_log.InfoFormat("[INVENTORY ACCESS MODULE]: {0} enabled.", Name);
}
}
IConfig hgModuleConfig = source.Configs["HGInventoryAccessModule"];
if (hgModuleConfig != null)
{
m_ThisGatekeeper = Util.GetConfigVarFromSections<string>(source, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "HGInventoryAccessModule" }, String.Empty);
// Legacy. Remove soon!
m_ThisGatekeeper = hgModuleConfig.GetString("Gatekeeper", m_ThisGatekeeper);
}
}
public virtual void PostInitialise()
{
}
public virtual void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
public virtual void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scene = null;
}
/// <summary>
/// Common module config for both this and descendant classes.
/// </summary>
/// <param name="source"></param>
protected virtual void InitialiseCommon(IConfigSource source)
{
IConfig inventoryConfig = source.Configs["Inventory"];
if (inventoryConfig != null)
CoalesceMultipleObjectsToInventory
= inventoryConfig.GetBoolean("CoalesceMultipleObjectsToInventory", true);
else
CoalesceMultipleObjectsToInventory = true;
}
protected virtual void OnNewClient(IClientAPI client)
{
client.OnCreateNewInventoryItem += CreateNewInventoryItem;
}
#endregion INonSharedRegionModule
#region Inventory Access
public virtual bool CanGetAgentInventoryItem(IClientAPI remoteClient, UUID itemID, UUID requestID)
{
InventoryItemBase assetRequestItem = GetItem(remoteClient.AgentId, itemID);
if (assetRequestItem == null)
{
ILibraryService lib = m_Scene.RequestModuleInterface<ILibraryService>();
if (lib != null)
assetRequestItem = lib.LibraryRootFolder.FindItem(itemID);
if (assetRequestItem == null)
return false;
}
// At this point, we need to apply perms
// only to notecards and scripts. All
// other asset types are always available
//
if (assetRequestItem.AssetType == (int)AssetType.LSLText)
{
if (!m_Scene.Permissions.CanViewScript(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to view script", false);
return false;
}
}
else if (assetRequestItem.AssetType == (int)AssetType.Notecard)
{
if (!m_Scene.Permissions.CanViewNotecard(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to view notecard", false);
return false;
}
}
if (assetRequestItem.AssetID != requestID)
{
m_log.WarnFormat(
"[INVENTORY ACCESS MODULE]: {0} requested asset {1} from item {2} but this does not match item's asset {3}",
Name, requestID, itemID, assetRequestItem.AssetID);
return false;
}
return true;
}
/// <summary>
/// Capability originating call to update the asset of an item in an agent's inventory
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemID"></param>
/// <param name="data"></param>
/// <returns></returns>
public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data)
{
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = m_Scene.InventoryService.GetItem(item);
if (item.Owner != remoteClient.AgentId)
return UUID.Zero;
if (item != null)
{
if ((InventoryType)item.InvType == InventoryType.Notecard)
{
if (!m_Scene.Permissions.CanEditNotecard(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to edit notecard", false);
return UUID.Zero;
}
remoteClient.SendAlertMessage("Notecard saved");
}
else if ((InventoryType)item.InvType == InventoryType.LSL)
{
if (!m_Scene.Permissions.CanEditScript(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to edit script", false);
return UUID.Zero;
}
remoteClient.SendAlertMessage("Script saved");
}
AssetBase asset =
CreateAsset(item.Name, item.Description, (sbyte)item.AssetType, data, remoteClient.AgentId.ToString());
item.AssetID = asset.FullID;
m_Scene.AssetService.Store(asset);
m_Scene.InventoryService.UpdateItem(item);
// remoteClient.SendInventoryItemCreateUpdate(item);
return (asset.FullID);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ACCESS MODULE]: Could not find item {0} for caps inventory update",
itemID);
}
return UUID.Zero;
}
public virtual List<InventoryItemBase> CopyToInventory(
DeRezAction action, UUID folderID,
List<SceneObjectGroup> objectGroups, IClientAPI remoteClient, bool asAttachment)
{
List<InventoryItemBase> copiedItems = new List<InventoryItemBase>();
Dictionary<UUID, List<SceneObjectGroup>> bundlesToCopy = new Dictionary<UUID, List<SceneObjectGroup>>();
if (CoalesceMultipleObjectsToInventory)
{
// The following code groups the SOG's by owner. No objects
// belonging to different people can be coalesced, for obvious
// reasons.
foreach (SceneObjectGroup g in objectGroups)
{
if (!bundlesToCopy.ContainsKey(g.OwnerID))
bundlesToCopy[g.OwnerID] = new List<SceneObjectGroup>();
bundlesToCopy[g.OwnerID].Add(g);
}
}
else
{
// If we don't want to coalesce then put every object in its own bundle.
foreach (SceneObjectGroup g in objectGroups)
{
List<SceneObjectGroup> bundle = new List<SceneObjectGroup>();
bundle.Add(g);
bundlesToCopy[g.UUID] = bundle;
}
}
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Copying {0} object bundles to folder {1} action {2} for {3}",
// bundlesToCopy.Count, folderID, action, remoteClient.Name);
// Each iteration is really a separate asset being created,
// with distinct destinations as well.
foreach (List<SceneObjectGroup> bundle in bundlesToCopy.Values)
copiedItems.Add(CopyBundleToInventory(action, folderID, bundle, remoteClient, asAttachment));
return copiedItems;
}
/// <summary>
/// Create a new inventory item. Called when the client creates a new item directly within their
/// inventory (e.g. by selecting a context inventory menu option).
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="transactionID"></param>
/// <param name="folderID"></param>
/// <param name="callbackID"></param>
/// <param name="description"></param>
/// <param name="name"></param>
/// <param name="invType"></param>
/// <param name="type"></param>
/// <param name="wearableType"></param>
/// <param name="nextOwnerMask"></param>
public void CreateNewInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID,
uint callbackID, string description, string name, sbyte invType,
sbyte assetType,
byte wearableType, uint nextOwnerMask, int creationDate)
{
m_log.DebugFormat("[INVENTORY ACCESS MODULE]: Received request to create inventory item {0} in folder {1}", name, folderID);
if (!m_Scene.Permissions.CanCreateUserInventory(invType, remoteClient.AgentId))
return;
if (transactionID == UUID.Zero)
{
ScenePresence presence;
if (m_Scene.TryGetScenePresence(remoteClient.AgentId, out presence))
{
byte[] data = null;
if (invType == (sbyte)InventoryType.Landmark && presence != null)
{
string suffix = string.Empty, prefix = string.Empty;
string strdata = GenerateLandmark(presence, out prefix, out suffix);
data = Encoding.ASCII.GetBytes(strdata);
name = prefix + name;
description += suffix;
}
AssetBase asset = m_Scene.CreateAsset(name, description, assetType, data, remoteClient.AgentId);
m_Scene.AssetService.Store(asset);
m_Scene.CreateNewInventoryItem(
remoteClient, remoteClient.AgentId.ToString(), string.Empty, folderID,
name, description, 0, callbackID, asset, invType, nextOwnerMask, creationDate);
}
else
{
m_log.ErrorFormat(
"[INVENTORY ACCESS MODULE]: ScenePresence for agent uuid {0} unexpectedly not found in CreateNewInventoryItem",
remoteClient.AgentId);
}
}
else
{
IAgentAssetTransactions agentTransactions = m_Scene.AgentTransactionsModule;
if (agentTransactions != null)
{
agentTransactions.HandleItemCreationFromTransaction(
remoteClient, transactionID, folderID, callbackID, description,
name, invType, assetType, wearableType, nextOwnerMask);
}
}
}
public virtual bool IsForeignUser(UUID userID, out string assetServerURL)
{
assetServerURL = string.Empty;
return false;
}
public virtual SceneObjectGroup RezObject(
IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart,
UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment)
{
// m_log.DebugFormat("[INVENTORY ACCESS MODULE]: RezObject for {0}, item {1}", remoteClient.Name, itemID);
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = m_Scene.InventoryService.GetItem(item);
if (item == null)
{
m_log.WarnFormat(
"[INVENTORY ACCESS MODULE]: Could not find item {0} for {1} in RezObject()",
itemID, remoteClient.Name);
return null;
}
item.Owner = remoteClient.AgentId;
return RezObject(
remoteClient, item, item.AssetID,
RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection,
RezSelected, RemoveItem, fromTaskID, attachment);
}
public virtual SceneObjectGroup RezObject(
IClientAPI remoteClient, InventoryItemBase item, UUID assetID, Vector3 RayEnd, Vector3 RayStart,
UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment)
{
AssetBase rezAsset = m_Scene.AssetService.Get(assetID.ToString());
if (rezAsset == null)
{
if (item != null)
{
m_log.WarnFormat(
"[InventoryAccessModule]: Could not find asset {0} for item {1} {2} for {3} in RezObject()",
assetID, item.Name, item.ID, remoteClient.Name);
}
else
{
m_log.WarnFormat(
"[INVENTORY ACCESS MODULE]: Could not find asset {0} for {1} in RezObject()",
assetID, remoteClient.Name);
}
return null;
}
SceneObjectGroup group = null;
List<SceneObjectGroup> objlist;
List<Vector3> veclist;
Vector3 bbox;
float offsetHeight;
byte bRayEndIsIntersection = (byte)(RayEndIsIntersection ? 1 : 0);
Vector3 pos;
bool single = m_Scene.GetObjectsToRez(rezAsset.Data, attachment, out objlist, out veclist, out bbox, out offsetHeight);
if (single)
{
pos = m_Scene.GetNewRezLocation(
RayStart, RayEnd, RayTargetID, Quaternion.Identity,
BypassRayCast, bRayEndIsIntersection, true, bbox, false);
pos.Z += offsetHeight;
}
else
{
pos = m_Scene.GetNewRezLocation(RayStart, RayEnd,
RayTargetID, Quaternion.Identity,
BypassRayCast, bRayEndIsIntersection, true,
bbox, false);
pos -= bbox / 2;
}
if (item != null && !DoPreRezWhenFromItem(remoteClient, item, objlist, pos, veclist, attachment))
return null;
for (int i = 0; i < objlist.Count; i++)
{
group = objlist[i];
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Preparing to rez {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}",
// group.Name, group.LocalId, group.UUID,
// group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask,
// remoteClient.Name);
// Vector3 storedPosition = group.AbsolutePosition;
if (group.UUID == UUID.Zero)
{
m_log.Debug("[INVENTORY ACCESS MODULE]: Object has UUID.Zero! Position 3");
}
// if this was previously an attachment and is now being rezzed,
// save the old attachment info.
if (group.IsAttachment == false && group.RootPart.Shape.State != 0)
{
group.RootPart.AttachedPos = group.AbsolutePosition;
group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint;
}
if (item == null)
{
// Change ownership. Normally this is done in DoPreRezWhenFromItem(), but in this case we must do it here.
foreach (SceneObjectPart part in group.Parts)
{
// Make the rezzer the owner, as this is not necessarily set correctly in the serialized asset.
part.LastOwnerID = part.OwnerID;
part.OwnerID = remoteClient.AgentId;
}
}
if (!attachment)
{
// If it's rezzed in world, select it. Much easier to
// find small items.
//
foreach (SceneObjectPart part in group.Parts)
{
part.CreateSelected = true;
}
}
group.ResetIDs();
if (attachment)
{
group.RootPart.Flags |= PrimFlags.Phantom;
group.IsAttachment = true;
}
// If we're rezzing an attachment then don't ask
// AddNewSceneObject() to update the client since
// we'll be doing that later on. Scheduling more than
// one full update during the attachment
// process causes some clients to fail to display the
// attachment properly.
m_Scene.AddNewSceneObject(group, true, false);
// if attachment we set it's asset id so object updates
// can reflect that, if not, we set it's position in world.
if (!attachment)
{
group.ScheduleGroupForFullUpdate();
group.AbsolutePosition = pos + veclist[i];
}
group.SetGroup(remoteClient.ActiveGroupId, remoteClient);
if (!attachment)
{
SceneObjectPart rootPart = group.RootPart;
if (rootPart.Shape.PCode == (byte)PCode.Prim)
group.ClearPartAttachmentData();
// Fire on_rez
group.CreateScriptInstances(0, true, m_Scene.DefaultScriptEngine, 1);
rootPart.ParentGroup.ResumeScripts();
rootPart.ScheduleFullUpdate();
}
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Rezzed {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}",
// group.Name, group.LocalId, group.UUID,
// group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask,
// remoteClient.Name);
}
if (item != null)
DoPostRezWhenFromItem(item, attachment);
return group;
}
public virtual void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver)
{
}
/// <summary>
/// Add relevant permissions for an object to the item.
/// </summary>
/// <param name="item"></param>
/// <param name="so"></param>
/// <param name="objsForEffectivePermissions"></param>
/// <param name="remoteClient"></param>
/// <returns></returns>
protected InventoryItemBase AddPermissions(
InventoryItemBase item, SceneObjectGroup so, List<SceneObjectGroup> objsForEffectivePermissions,
IClientAPI remoteClient)
{
uint effectivePerms = (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify | PermissionMask.Move | PermissionMask.Export) | 7;
uint allObjectsNextOwnerPerms = 0x7fffffff;
uint allObjectsEveryOnePerms = 0x7fffffff;
uint allObjectsGroupPerms = 0x7fffffff;
foreach (SceneObjectGroup grp in objsForEffectivePermissions)
{
effectivePerms &= grp.GetEffectivePermissions();
allObjectsNextOwnerPerms &= grp.RootPart.NextOwnerMask;
allObjectsEveryOnePerms &= grp.RootPart.EveryoneMask;
allObjectsGroupPerms &= grp.RootPart.GroupMask;
}
effectivePerms |= (uint)PermissionMask.Move;
//PermissionsUtil.LogPermissions(item.Name, "Before AddPermissions", item.BasePermissions, item.CurrentPermissions, item.NextPermissions);
if (remoteClient != null && (remoteClient.AgentId != so.RootPart.OwnerID) && m_Scene.Permissions.PropagatePermissions())
{
uint perms = effectivePerms;
PermissionsUtil.ApplyFoldedPermissions(effectivePerms, ref perms);
item.BasePermissions = perms & allObjectsNextOwnerPerms;
item.CurrentPermissions = item.BasePermissions;
item.NextPermissions = perms & allObjectsNextOwnerPerms;
item.EveryOnePermissions = allObjectsEveryOnePerms & allObjectsNextOwnerPerms;
item.GroupPermissions = allObjectsGroupPerms & allObjectsNextOwnerPerms;
// apply next owner perms on rez
item.CurrentPermissions |= SceneObjectGroup.SLAM;
}
else
{
item.BasePermissions = effectivePerms;
item.CurrentPermissions = effectivePerms;
item.NextPermissions = allObjectsNextOwnerPerms & effectivePerms;
item.EveryOnePermissions = allObjectsEveryOnePerms & effectivePerms;
item.GroupPermissions = allObjectsGroupPerms & effectivePerms;
item.CurrentPermissions &=
((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify |
(uint)PermissionMask.Move |
(uint)PermissionMask.Export |
7); // Preserve folded permissions
}
//PermissionsUtil.LogPermissions(item.Name, "After AddPermissions", item.BasePermissions, item.CurrentPermissions, item.NextPermissions);
return item;
}
protected void AddUserData(SceneObjectGroup sog)
{
UserManagementModule.AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData);
foreach (SceneObjectPart sop in sog.Parts)
UserManagementModule.AddUser(sop.CreatorID, sop.CreatorData);
}
/// <summary>
/// Copy a bundle of objects to inventory. If there is only one object, then this will create an object
/// item. If there are multiple objects then these will be saved as a single coalesced item.
/// </summary>
/// <param name="action"></param>
/// <param name="folderID"></param>
/// <param name="objlist"></param>
/// <param name="remoteClient"></param>
/// <param name="asAttachment">Should be true if the bundle is being copied as an attachment. This prevents
/// attempted serialization of any script state which would abort any operating scripts.</param>
/// <returns>The inventory item created by the copy</returns>
protected InventoryItemBase CopyBundleToInventory(
DeRezAction action, UUID folderID, List<SceneObjectGroup> objlist, IClientAPI remoteClient,
bool asAttachment)
{
CoalescedSceneObjects coa = new CoalescedSceneObjects(UUID.Zero);
// Dictionary<UUID, Vector3> originalPositions = new Dictionary<UUID, Vector3>();
Dictionary<SceneObjectGroup, KeyframeMotion> group2Keyframe = new Dictionary<SceneObjectGroup, KeyframeMotion>();
foreach (SceneObjectGroup objectGroup in objlist)
{
if (objectGroup.RootPart.KeyframeMotion != null)
{
objectGroup.RootPart.KeyframeMotion.Pause();
group2Keyframe.Add(objectGroup, objectGroup.RootPart.KeyframeMotion);
objectGroup.RootPart.KeyframeMotion = null;
}
// Vector3 inventoryStoredPosition = new Vector3
// (((objectGroup.AbsolutePosition.X > (int)Constants.RegionSize)
// ? 250
// : objectGroup.AbsolutePosition.X)
// ,
// (objectGroup.AbsolutePosition.Y > (int)Constants.RegionSize)
// ? 250
// : objectGroup.AbsolutePosition.Y,
// objectGroup.AbsolutePosition.Z);
//
// originalPositions[objectGroup.UUID] = objectGroup.AbsolutePosition;
//
// objectGroup.AbsolutePosition = inventoryStoredPosition;
// Make sure all bits but the ones we want are clear
// on take.
// This will be applied to the current perms, so
// it will do what we want.
objectGroup.RootPart.NextOwnerMask &=
((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify |
(uint)PermissionMask.Export);
objectGroup.RootPart.NextOwnerMask |=
(uint)PermissionMask.Move;
coa.Add(objectGroup);
}
string itemXml;
// If we're being called from a script, then trying to serialize that same script's state will not complete
// in any reasonable time period. Therefore, we'll avoid it. The worst that can happen is that if
// the client/server crashes rather than logging out normally, the attachment's scripts will resume
// without state on relog. Arguably, this is what we want anyway.
if (objlist.Count > 1)
itemXml = CoalescedSceneObjectsSerializer.ToXml(coa, !asAttachment);
else
itemXml = SceneObjectSerializer.ToOriginalXmlFormat(objlist[0], !asAttachment);
// // Restore the position of each group now that it has been stored to inventory.
// foreach (SceneObjectGroup objectGroup in objlist)
// objectGroup.AbsolutePosition = originalPositions[objectGroup.UUID];
InventoryItemBase item = CreateItemForObject(action, remoteClient, objlist[0], folderID);
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Created item is {0}",
// item != null ? item.ID.ToString() : "NULL");
if (item == null)
return null;
item.CreatorId = objlist[0].RootPart.CreatorID.ToString();
item.CreatorData = objlist[0].RootPart.CreatorData;
if (objlist.Count > 1)
{
item.Flags = (uint)InventoryItemFlags.ObjectHasMultipleItems;
// If the objects have different creators then don't specify a creator at all
foreach (SceneObjectGroup objectGroup in objlist)
{
if ((objectGroup.RootPart.CreatorID.ToString() != item.CreatorId)
|| (objectGroup.RootPart.CreatorData.ToString() != item.CreatorData))
{
item.CreatorId = UUID.Zero.ToString();
item.CreatorData = string.Empty;
break;
}
}
}
else
{
item.SaleType = objlist[0].RootPart.ObjectSaleType;
item.SalePrice = objlist[0].RootPart.SalePrice;
}
AssetBase asset = CreateAsset(
objlist[0].GetPartName(objlist[0].RootPart.LocalId),
objlist[0].GetPartDescription(objlist[0].RootPart.LocalId),
(sbyte)AssetType.Object,
Utils.StringToBytes(itemXml),
objlist[0].OwnerID.ToString());
m_Scene.AssetService.Store(asset);
item.AssetID = asset.FullID;
if (DeRezAction.SaveToExistingUserInventoryItem == action)
{
m_Scene.InventoryService.UpdateItem(item);
}
else
{
item.CreationDate = Util.UnixTimeSinceEpoch();
item.Description = asset.Description;
item.Name = asset.Name;
item.AssetType = asset.Type;
AddPermissions(item, objlist[0], objlist, remoteClient);
m_Scene.AddInventoryItem(item);
if (remoteClient != null && item.Owner == remoteClient.AgentId)
{
remoteClient.SendInventoryItemCreateUpdate(item, 0);
}
else
{
ScenePresence notifyUser = m_Scene.GetScenePresence(item.Owner);
if (notifyUser != null)
{
notifyUser.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
}
}
}
// Restore KeyframeMotion
foreach (SceneObjectGroup objectGroup in group2Keyframe.Keys)
{
objectGroup.RootPart.KeyframeMotion = group2Keyframe[objectGroup];
objectGroup.RootPart.KeyframeMotion.Start();
}
// This is a hook to do some per-asset post-processing for subclasses that need that
if (remoteClient != null)
ExportAsset(remoteClient.AgentId, asset.FullID);
return item;
}
/// <summary>
/// Create an item using details for the given scene object.
/// </summary>
/// <param name="action"></param>
/// <param name="remoteClient"></param>
/// <param name="so"></param>
/// <param name="folderID"></param>
/// <returns></returns>
protected InventoryItemBase CreateItemForObject(
DeRezAction action, IClientAPI remoteClient, SceneObjectGroup so, UUID folderID)
{
// Get the user info of the item destination
//
UUID userID = UUID.Zero;
if (action == DeRezAction.Take || action == DeRezAction.TakeCopy ||
action == DeRezAction.SaveToExistingUserInventoryItem)
{
// Take or take copy require a taker
// Saving changes requires a local user
//
if (remoteClient == null)
return null;
userID = remoteClient.AgentId;
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is {1} {2}",
// action, remoteClient.Name, userID);
}
else if (so.RootPart.OwnerID == so.RootPart.GroupID)
{
// Group owned objects go to the last owner before the object was transferred.
userID = so.RootPart.LastOwnerID;
}
else
{
// Other returns / deletes go to the object owner
//
userID = so.RootPart.OwnerID;
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is object owner {1}",
// action, userID);
}
if (userID == UUID.Zero) // Can't proceed
{
return null;
}
// If we're returning someone's item, it goes back to the
// owner's Lost And Found folder.
// Delete is treated like return in this case
// Deleting your own items makes them go to trash
//
InventoryFolderBase folder = null;
InventoryItemBase item = null;
if (DeRezAction.SaveToExistingUserInventoryItem == action)
{
item = new InventoryItemBase(so.RootPart.FromUserInventoryItemID, userID);
item = m_Scene.InventoryService.GetItem(item);
//item = userInfo.RootFolder.FindItem(
// objectGroup.RootPart.FromUserInventoryItemID);
if (null == item)
{
m_log.DebugFormat(
"[INVENTORY ACCESS MODULE]: Object {0} {1} scheduled for save to inventory has already been deleted.",
so.Name, so.UUID);
return null;
}
}
else
{
// Folder magic
//
if (action == DeRezAction.Delete)
{
// Deleting someone else's item
//
if (remoteClient == null ||
so.OwnerID != remoteClient.AgentId)
{
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
}
else
{
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
}
}
else if (action == DeRezAction.Return)
{
// Dump to lost + found unconditionally
//
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
}
if (folderID == UUID.Zero && folder == null)
{
if (action == DeRezAction.Delete)
{
// Deletes go to trash by default
//
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
}
else
{
if (remoteClient == null || so.RootPart.OwnerID != remoteClient.AgentId)
{
// Taking copy of another person's item. Take to
// Objects folder.
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.Object);
so.FromFolderID = UUID.Zero;
}
else
{
// Catch all. Use lost & found
//
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
}
}
}
// Override and put into where it came from, if it came
// from anywhere in inventory and the owner is taking it back.
//
if (action == DeRezAction.Take || action == DeRezAction.TakeCopy)
{
if (so.FromFolderID != UUID.Zero && so.RootPart.OwnerID == remoteClient.AgentId)
{
InventoryFolderBase f = new InventoryFolderBase(so.FromFolderID, userID);
folder = m_Scene.InventoryService.GetFolder(f);
if (folder.Type == 14 || folder.Type == 16)
{
// folder.Type = 6;
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.Object);
}
}
}
if (folder == null) // None of the above
{
folder = new InventoryFolderBase(folderID);
if (folder == null) // Nowhere to put it
{
return null;
}
}
item = new InventoryItemBase();
item.ID = UUID.Random();
item.InvType = (int)InventoryType.Object;
item.Folder = folder.ID;
item.Owner = userID;
}
return item;
}
protected virtual void ExportAsset(UUID agentID, UUID assetID)
{
// nothing to do here
}
protected virtual string GenerateLandmark(ScenePresence presence, out string prefix, out string suffix)
{
if (m_ThisGatekeeper != String.Empty)
{
if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(presence.UUID))
prefix = "HG ";
else
prefix = string.Empty;
suffix = " @ " + m_ThisGatekeeper;
Vector3 pos = presence.AbsolutePosition;
return String.Format("Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}\ngatekeeper {5}\n",
presence.Scene.RegionInfo.RegionID,
pos.X, pos.Y, pos.Z,
presence.RegionHandle,
m_ThisGatekeeper);
}
else
{
prefix = string.Empty;
suffix = string.Empty;
Vector3 pos = presence.AbsolutePosition;
return String.Format("Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}\n",
presence.Scene.RegionInfo.RegionID,
pos.X, pos.Y, pos.Z,
presence.RegionHandle);
}
}
/// <summary>
/// Do post-rez processing when the object comes from an item.
/// </summary>
/// <param name="item"></param>
/// <param name="isAttachment"></param>
private void DoPostRezWhenFromItem(InventoryItemBase item, bool isAttachment)
{
if (!m_Scene.Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
{
// If this is done on attachments, no
// copy ones will be lost, so avoid it
//
if (!isAttachment)
{
List<UUID> uuids = new List<UUID>();
uuids.Add(item.ID);
m_Scene.InventoryService.DeleteItems(item.Owner, uuids);
}
}
}
}
/// <summary>
/// Do pre-rez processing when the object comes from an item.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="item"></param>
/// <param name="objlist"></param>
/// <param name="pos"></param>
/// <param name="veclist">
/// List of vector position adjustments for a coalesced objects. For ordinary objects
/// this list will contain just Vector3.Zero. The order of adjustments must match the order of objlist
/// </param>
/// <param name="isAttachment"></param>
/// <returns>true if we can processed with rezzing, false if we need to abort</returns>
private bool DoPreRezWhenFromItem(
IClientAPI remoteClient, InventoryItemBase item, List<SceneObjectGroup> objlist,
Vector3 pos, List<Vector3> veclist, bool isAttachment)
{
UUID fromUserInventoryItemId = UUID.Zero;
// If we have permission to copy then link the rezzed object back to the user inventory
// item that it came from. This allows us to enable 'save object to inventory'
if (!m_Scene.Permissions.BypassPermissions())
{
if ((item.CurrentPermissions & (uint)PermissionMask.Copy)
== (uint)PermissionMask.Copy && (item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0)
{
fromUserInventoryItemId = item.ID;
}
}
else
{
if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0)
{
// Brave new fullperm world
fromUserInventoryItemId = item.ID;
}
}
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup g = objlist[i];
if (!m_Scene.Permissions.CanRezObject(
g.PrimCount, remoteClient.AgentId, pos + veclist[i])
&& !isAttachment)
{
// The client operates in no fail mode. It will
// have already removed the item from the folder
// if it's no copy.
// Put it back if it's not an attachment
//
if (((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) && (!isAttachment))
remoteClient.SendBulkUpdateInventory(item);
ILandObject land = m_Scene.LandChannel.GetLandObject(pos.X, pos.Y);
remoteClient.SendAlertMessage(string.Format(
"Can't rez object '{0}' at <{1:F3}, {2:F3}, {3:F3}> on parcel '{4}' in region {5}.",
item.Name, pos.X, pos.Y, pos.Z, land != null ? land.LandData.Name : "Unknown", m_Scene.Name));
return false;
}
}
for (int i = 0; i < objlist.Count; i++)
{
SceneObjectGroup so = objlist[i];
SceneObjectPart rootPart = so.RootPart;
// Since renaming the item in the inventory does not
// affect the name stored in the serialization, transfer
// the correct name from the inventory to the
// object itself before we rez.
//
// Only do these for the first object if we are rezzing a coalescence.
if (i == 0)
{
rootPart.Name = item.Name;
rootPart.Description = item.Description;
rootPart.ObjectSaleType = item.SaleType;
rootPart.SalePrice = item.SalePrice;
}
so.FromFolderID = item.Folder;
// m_log.DebugFormat(
// "[INVENTORY ACCESS MODULE]: rootPart.OwnedID {0}, item.Owner {1}, item.CurrentPermissions {2:X}",
// rootPart.OwnerID, item.Owner, item.CurrentPermissions);
if ((rootPart.OwnerID != item.Owner) || (item.CurrentPermissions & SceneObjectGroup.SLAM) != 0)
{
//Need to kill the for sale here
rootPart.ObjectSaleType = 0;
rootPart.SalePrice = 10;
}
foreach (SceneObjectPart part in so.Parts)
{
part.FromUserInventoryItemID = fromUserInventoryItemId;
part.ApplyPermissionsOnRez(item, true, m_Scene);
}
rootPart.TrimPermissions();
if (isAttachment)
so.FromItemID = item.ID;
}
return true;
}
#endregion Inventory Access
#region Misc
protected virtual InventoryItemBase GetItem(UUID agentID, UUID itemID)
{
IInventoryService invService = m_Scene.RequestModuleInterface<IInventoryService>();
InventoryItemBase item = new InventoryItemBase(itemID, agentID);
item = invService.GetItem(item);
if (item != null && item.CreatorData != null && item.CreatorData != string.Empty)
UserManagementModule.AddUser(item.CreatorIdAsUuid, item.CreatorData);
return item;
}
/// <summary>
/// Create a new asset data structure.
/// </summary>
/// <param name="name"></param>
/// <param name="description"></param>
/// <param name="invType"></param>
/// <param name="assetType"></param>
/// <param name="data"></param>
/// <returns></returns>
private AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, string creatorID)
{
AssetBase asset = new AssetBase(UUID.Random(), name, assetType, creatorID);
asset.Description = description;
asset.Data = (data == null) ? new byte[1] : data;
return asset;
}
#endregion Misc
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Yxorp.Core
{
public class SecureServerSocket
{
private readonly X509Certificate2 _certificate;
//private readonly IPAddress _serverIpAddress;
private readonly SslStream _sslStream;
private static readonly byte[] CrlfBytes = Encoding.ASCII.GetBytes("\r\n");
private static readonly byte[] EndBytes = Encoding.ASCII.GetBytes("\r\n\r\n");
private readonly Socket _socketToServer;
public SecureServerSocket(Socket socket, X509Certificate2 certificate)
{
Initializer.Logger.Trace($"{socket.Handle}|Begin");
_certificate = certificate;
_socketToServer = socket;
var networkStream = new NetworkStream(_socketToServer);
_sslStream = new SslStream(networkStream,
false,
(sender, cert, chain, errors) => true,
null);
}
public IntPtr Handle => _socketToServer.Handle;
public void AuthenticateAsClient()
{
Initializer.Logger.Trace($"{Handle}|Begin");
// Maybe specify in config which SslProtocol is wanted?
_sslStream.AuthenticateAsClient(((IPEndPoint)_socketToServer.RemoteEndPoint).Address.ToString(),
new X509Certificate2Collection { _certificate },
SslProtocols.Default,
false);
Initializer.Logger.Trace("{0}|_sslStream.SslProtocol={1}", Handle, _sslStream.SslProtocol);
Initializer.Logger.Trace($"{Handle}|End");
}
internal void BeginWrite(byte[] buffer, ServerStateObject state)
{
Initializer.Logger.Trace($"{state.ServerSocket.Handle}|Begin");
Initializer.Logger.Debug($"{state.ServerSocket.Handle}|Received request from {state.ClientSocket.Handle}");
try
{
state.ServerSocket._sslStream.BeginWrite(buffer,
0,
buffer.Length,
WriteCallback,
state);
}
catch (IOException ex)
{
Initializer.Logger.Error(ex);
state.ClientSocket.Close();
}
}
private static void WriteCallback(IAsyncResult asyncResult)
{
Initializer.Logger.Trace("Begin");
var state = (ServerStateObject)asyncResult.AsyncState;
state.ServerSocket._sslStream.EndWrite(asyncResult);
state.ResponseInfo = new ResponseInfo();
state.ServerSocket._sslStream.BeginRead(state.ServerBuffer, 0, state.ServerBuffer.Length, ReadCallback, state);
Initializer.Logger.Trace("{0}|End", state.ServerSocket.Handle);
}
public void Close()
{
_socketToServer.Disconnect(true);
_sslStream.Close();
_sslStream.Dispose();
}
private static void ReadCallback(IAsyncResult asyncResult)
{
ServerStateObject state;
if (!TryGetState(asyncResult, out state))
return;
Initializer.Logger.Trace($"{state.ServerSocket.Handle}|Begin");
int numberOfBytesRead;
if (!TryEndRead(state, asyncResult, out numberOfBytesRead))
return;
// Reading Zero Bytes
// Many stream-oriented objects (including sockets) will signal the end of the stream by
// returning 0 bytes in response to a Read operation.
// This means that the remote side of the connection has gracefully closed the connection,
// and the socket should be closed.
// The zero-length read must be treated as a special case; if it is not,
// the receiving code usually enters an infinite loop attempting to read more data.
// A zero-length read is not an error condition; it merely means that the socket has been disconnected.
// http://blog.stephencleary.com/2009/06/using-socket-as-connected-socket.html
if (numberOfBytesRead == 0)
{
Close(state);
return;
}
state.ServerBuffer.AddToEndOf(ref state.AllServerData, numberOfBytesRead);
if (state.ResponseInfo.StatusLine.Length == 0)
state.ResponseInfo.StatusLine = GetStatusline(state.AllServerData);
if (state.ResponseInfo.StatusLine.Length > 0 && state.ResponseInfo.HeaderString.Length == 0)
state.ResponseInfo.HeaderString = GetHeaders(state.AllServerData);
var endBytesAreSent = state.AllServerData.EndBytesAreSent();
if (endBytesAreSent || state.AllResponseContentReceived)
{
state.ClientSocket.BeginWrite(state.AllServerData, new ClientStateObject(state.ClientSocket, state.ServerSocket));
state.ResponseInfo = new ResponseInfo();
}
else
{
state.ServerSocket.BeginRead(state);
}
Initializer.Logger.Trace($"{state.ServerSocket.Handle}|End");
}
private static string GetHeaders(byte[] data)
{
var headerEndIndex = data.LocateFirst(EndBytes);
if (headerEndIndex <= 0)
return string.Empty;
var statusLineIndex = data.LocateFirst(CrlfBytes);
var headerLength = headerEndIndex - statusLineIndex;
return Encoding.UTF8.GetString(data,
statusLineIndex,
headerLength);
}
private static string GetStatusline(byte[] allServerData)
{
var requestLineIndex = allServerData.LocateFirst(CrlfBytes);
return requestLineIndex > 0
? Encoding.UTF8.GetString(allServerData, 0, requestLineIndex)
: string.Empty;
}
private static void Close(ServerStateObject state)
{
Initializer.Logger.Info("{0}|Connection was closed by server", state.ServerSocket.Handle);
state.ServerSocket._sslStream.Close();
}
private static bool TryEndRead(ServerStateObject state, IAsyncResult asyncResult, out int numberOfBytesRead)
{
Initializer.Logger.Debug("state.ServerSocket._socketToServer.ReceiveBufferSize={0}", state.ServerSocket._socketToServer.ReceiveBufferSize);
numberOfBytesRead = -1;
try
{
numberOfBytesRead = state.ServerSocket._sslStream.EndRead(asyncResult);
Initializer.Logger.Info("{0}|numberOfBytesRead={1}", state.ServerSocket.Handle, numberOfBytesRead);
var response = Encoding.UTF8.GetString(state.ServerBuffer, 0, numberOfBytesRead);
//Initializer.Logger.Info("{0}|Server wrote to buffer='{1}'", state.ServerSocket.Handle, response);
return true;
}
catch (Exception ex)
{
Initializer.Logger.Debug("RequestHandler.ReadCallback - EndRead error");
Initializer.Logger.Error(ex);
return false;
}
}
internal void BeginRead(ServerStateObject state)
{
Initializer.Logger.Trace("Begin");
state.ServerSocket._sslStream.BeginRead(state.ServerBuffer, 0, state.ServerBuffer.Length, ReadCallback, state);
Initializer.Logger.Trace("End");
}
private static bool TryGetState(IAsyncResult asyncResult, out ServerStateObject state)
{
state = null;
try
{
state = (ServerStateObject)asyncResult.AsyncState;
return true;
}
catch (IOException ex)
{
switch (ex.Message)
{
case "Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.":
Initializer.Logger.Warn(ex, "I don't know what to do?! (1)");
return false;
default:
Initializer.Logger.Error(ex, "Unknown AuthenticationException");
throw;
}
}
catch (Exception ex)
{
Initializer.Logger.Error(ex, "Get ServerStateObject from AsyncState failed.");
return false;
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=TextDecorationCollectionConverter.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: TextDecorationCollectionConverter class
//
// History:
// 2/23/2004: Garyyang Created the file
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
using System.Security;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows
{
/// <summary>
/// TypeConverter for TextDecorationCollection
/// </summary>
public sealed class TextDecorationCollectionConverter : TypeConverter
{
/// <summary>
/// CanConvertTo method
/// </summary>
/// <param name="context"> ITypeDescriptorContext </param>
/// <param name="destinationType"> Type to convert to </param>
/// <returns> false will always be returned because TextDecorations cannot be converted to any other type. </returns>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor))
{
return true;
}
// return false for any other target type. Don't call base.CanConvertTo() because it would be confusing
// in some cases. For example, for destination typeof(String), base convertor just converts the TDC to the
// string full name of the type.
return false;
}
/// <summary>
/// CanConvertFrom
/// </summary>
/// <param name="context"> ITypeDescriptorContext </param>
/// <param name="sourceType">Type to convert to </param>
/// <returns> true if it can convert from sourceType to TextDecorations, false otherwise </returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return false;
}
/// <summary>
/// ConvertFrom
/// </summary>
/// <param name="context"> ITypeDescriptorContext </param>
/// <param name="culture"> CultureInfo </param>
/// <param name="input"> The input object to be converted to TextDecorations </param>
/// <returns> the converted value of the input object </returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object input)
{
if (input == null)
{
throw GetConvertFromException(input);
}
string value = input as string;
if (null == value)
{
throw new ArgumentException(SR.Get(SRID.General_BadType, "ConvertFrom"), "input");
}
return ConvertFromString(value);
}
/// <summary>
/// ConvertFromString
/// </summary>
/// <param name="text"> The string to be converted into TextDecorationCollection object </param>
/// <returns> the converted value of the string flag </returns>
/// <remarks>
/// The text parameter can be either string "None" or a combination of the predefined
/// TextDecoration names delimited by commas (,). One or more blanks spaces can precede
/// or follow each text decoration name or comma. There can't be duplicate TextDecoration names in the
/// string. The operation is case-insensitive.
/// </remarks>
public static new TextDecorationCollection ConvertFromString(string text)
{
if (text == null)
{
return null;
}
TextDecorationCollection textDecorations = new TextDecorationCollection();
// Flags indicating which Predefined textDecoration has alrady been added.
byte MatchedTextDecorationFlags = 0;
// Start from the 1st non-whitespace character
// Negative index means error is encountered
int index = AdvanceToNextNonWhiteSpace(text, 0);
while (index >= 0 && index < text.Length)
{
if (Match(None, text, index))
{
// Matched "None" in the input
index = AdvanceToNextNonWhiteSpace(text, index + None.Length);
if (textDecorations.Count > 0 || index < text.Length)
{
// Error: "None" can only be specified by its own
index = -1;
}
}
else
{
// Match the input with one of the predefined text decoration names
int i;
for(i = 0;
i < TextDecorationNames.Length
&& !Match(TextDecorationNames[i], text, index);
i++
);
if (i < TextDecorationNames.Length)
{
// Found a match within the predefined names
if ((MatchedTextDecorationFlags & (1 << i)) > 0)
{
// Error: The matched value is duplicated.
index = -1;
}
else
{
// Valid match. Add to the collection and remember that this text decoration
// has been added
textDecorations.Add(PredefinedTextDecorations[i]);
MatchedTextDecorationFlags |= (byte)(1 << i);
// Advance to the start of next name
index = AdvanceToNextNameStart(text, index + TextDecorationNames[i].Length);
}
}
else
{
// Error: no match found in the predefined names
index = -1;
}
}
}
if (index < 0)
{
throw new ArgumentException(SR.Get(SRID.InvalidTextDecorationCollectionString, text));
}
return textDecorations;
}
/// <summary>
/// ConvertTo
/// </summary>
/// <param name="context"> ITypeDescriptorContext </param>
/// <param name="culture"> CultureInfo </param>
/// <param name="value"> the object to be converted to another type </param>
/// <param name="destinationType"> The destination type of the conversion </param>
/// <returns> null will always be returned because TextDecorations cannot be converted to any other type. </returns>
///<SecurityNote>
/// Critical: calls InstanceDescriptor ctor which LinkDemands
/// PublicOK: can only make an InstanceDescriptor for TextDecoration, not an arbitrary class
///</SecurityNote>
[SecurityCritical]
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor) && value is IEnumerable<TextDecoration>)
{
ConstructorInfo ci = typeof(TextDecorationCollection).GetConstructor(
new Type[]{typeof(IEnumerable<TextDecoration>)}
);
return new InstanceDescriptor(ci, new object[]{value});
}
// Pass unhandled cases to base class (which will throw exceptions for null value or destinationType.)
return base.ConvertTo(context, culture, value, destinationType);
}
//---------------------------------
// Private methods
//---------------------------------
/// <summary>
/// Match the input against a predefined pattern from certain index onwards
/// </summary>
private static bool Match(string pattern, string input, int index)
{
int i = 0;
for (;
i < pattern.Length
&& index + i < input.Length
&& pattern[i] == Char.ToUpperInvariant(input[index + i]);
i++) ;
return (i == pattern.Length);
}
/// <summary>
/// Advance to the start of next name
/// </summary>
private static int AdvanceToNextNameStart(string input, int index)
{
// Two names must be seperated by a comma and optionally spaces
int separator = AdvanceToNextNonWhiteSpace(input, index);
int nextNameStart;
if (separator >= input.Length)
{
// reach the end
nextNameStart = input.Length;
}
else
{
if (input[separator] == Separator)
{
nextNameStart = AdvanceToNextNonWhiteSpace(input, separator + 1);
if (nextNameStart >= input.Length)
{
// Error: Separator is at the end of the input
nextNameStart = -1;
}
}
else
{
// Error: There is a non-whitespace, non-separator character following
// the matched value
nextNameStart = -1;
}
}
return nextNameStart;
}
/// <summary>
/// Advance to the next non-whitespace character
/// </summary>
private static int AdvanceToNextNonWhiteSpace(string input, int index)
{
for (; index < input.Length && Char.IsWhiteSpace(input[index]); index++) ;
return (index > input.Length) ? input.Length : index;
}
//---------------------------------
// Private members
//---------------------------------
//
// Predefined valid names for TextDecorations
// Names should be normalized to be upper case
//
private const string None = "NONE";
private const char Separator = ',';
private static readonly string[] TextDecorationNames = new string[] {
"OVERLINE",
"BASELINE",
"UNDERLINE",
"STRIKETHROUGH"
};
// Predefined TextDecorationCollection values. It should match
// the TextDecorationNames array
private static readonly TextDecorationCollection[] PredefinedTextDecorations =
new TextDecorationCollection[] {
TextDecorations.OverLine,
TextDecorations.Baseline,
TextDecorations.Underline,
TextDecorations.Strikethrough
};
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using ChartDirector;
namespace CSharpChartExplorer
{
public partial class FrmXYZoomScroll : Form
{
// XY data points for the chart
private double[] dataX0;
private double[] dataY0;
private double[] dataX1;
private double[] dataY1;
private double[] dataX2;
private double[] dataY2;
public FrmXYZoomScroll()
{
InitializeComponent();
}
private void FrmXYZoomScroll_Load(object sender, EventArgs e)
{
// Load the data
loadData();
// Trigger the ViewPortChanged event to draw the chart
winChartViewer1.updateViewPort(true, true);
// Draw the full thumbnail chart for the ViewPortControl
drawFullChart(viewPortControl1, winChartViewer1);
}
//
// Load the data
//
private void loadData()
{
//
// For simplicity, in this demo, we just use hard coded data.
//
dataX0 = new double[] { 10, 15, 6, -12, 14, -8, 13, -3, 16, 12, 10.5, -7, 3, -10, -5, 2, 5 };
dataY0 = new double[] {130, 150, 80, 110, -110, -105, -130, -15, -170, 125, 125, 60, 25, 150,
150, 15, 120};
dataX1 = new double[] { 6, 7, -4, 3.5, 7, 8, -9, -10, -12, 11, 8, -3, -2, 8, 4, -15, 15 };
dataY1 = new double[] {65, -40, -40, 45, -70, -80, 80, 10, -100, 105, 60, 50, 20, 170, -25, 50,
75};
dataX2 = new double[] { -10, -12, 11, 8, 6, 12, -4, 3.5, 7, 8, -9, 3, -13, 16, -7.5, -10, -15 };
dataY2 = new double[] {65, -80, -40, 45, -70, -80, 80, 90, -100, 105, 60, -75, -150, -40, 120,
-50, -30};
}
//
// The ViewPortChanged event handler. This event occurs if the user scrolls or zooms in
// or out the chart by dragging or clicking on the chart. It can also be triggered by
// calling WinChartViewer.updateViewPort.
//
private void winChartViewer1_ViewPortChanged(object sender, WinViewPortEventArgs e)
{
// In addition to updating the chart, we may also need to update other controls that
// changes based on the view port.
updateControls(winChartViewer1);
// Update the chart if necessary
if (e.NeedUpdateChart)
drawChart(winChartViewer1);
// Update the image map if necessary
if (e.NeedUpdateImageMap)
updateImageMap(winChartViewer1);
}
//
// Update controls when the view port changed
//
private void updateControls(WinChartViewer viewer)
{
// Synchronize the zoom bar value with the view port width/height
zoomBar.Value = (int)Math.Round(Math.Min(viewer.ViewPortWidth, viewer.ViewPortHeight) *
zoomBar.Maximum);
}
//
// Draw the chart and display it in the given viewer
//
private void drawChart(WinChartViewer viewer)
{
// Create an XYChart object 500 x 480 pixels in size, with the same background color
// as the container
XYChart c = new XYChart(500, 480, Chart.CColor(BackColor));
// Set the plotarea at (50, 40) and of size 400 x 400 pixels. Use light grey (c0c0c0)
// horizontal and vertical grid lines. Set 4 quadrant coloring, where the colors of
// the quadrants alternate between lighter and deeper grey (dddddd/eeeeee).
c.setPlotArea(50, 40, 400, 400, -1, -1, -1, 0xc0c0c0, 0xc0c0c0
).set4QBgColor(0xdddddd, 0xeeeeee, 0xdddddd, 0xeeeeee, 0x000000);
// Enable clipping mode to clip the part of the data that is outside the plot area.
c.setClipping();
// Set 4 quadrant mode, with both x and y axes symetrical around the origin
c.setAxisAtOrigin(Chart.XYAxisAtOrigin, Chart.XAxisSymmetric + Chart.YAxisSymmetric);
// Add a legend box at (450, 40) (top right corner of the chart) with vertical layout
// and 8 pts Arial Bold font. Set the background color to semi-transparent grey.
LegendBox b = c.addLegend(450, 40, true, "Arial Bold", 8);
b.setAlignment(Chart.TopRight);
b.setBackground(0x40dddddd);
// Add a titles to axes
c.xAxis().setTitle("Alpha Index");
c.yAxis().setTitle("Beta Index");
// Set axes width to 2 pixels
c.xAxis().setWidth(2);
c.yAxis().setWidth(2);
// The default ChartDirector settings has a denser y-axis grid spacing and less-dense
// x-axis grid spacing. In this demo, we want the tick spacing to be symmetrical.
// We use around 50 pixels between major ticks and 25 pixels between minor ticks.
c.xAxis().setTickDensity(50, 25);
c.yAxis().setTickDensity(50, 25);
//
// In this example, we represent the data by scatter points. If you want to represent
// the data by somethings else (lines, bars, areas, floating boxes, etc), just modify
// the code below to use the layer type of your choice.
//
// Add scatter layer, using 11 pixels red (ff33333) X shape symbols
c.addScatterLayer(dataX0, dataY0, "Group A", Chart.Cross2Shape(), 11, 0xff3333);
// Add scatter layer, using 11 pixels green (33ff33) circle symbols
c.addScatterLayer(dataX1, dataY1, "Group B", Chart.CircleShape, 11, 0x33ff33);
// Add scatter layer, using 11 pixels blue (3333ff) triangle symbols
c.addScatterLayer(dataX2, dataY2, "Group C", Chart.TriangleSymbol, 11, 0x3333ff);
//
// In this example, we have not explicitly configured the full x and y range. In this case, the
// first time syncLinearAxisWithViewPort is called, ChartDirector will auto-scale the axis and
// assume the resulting range is the full range. In subsequent calls, ChartDirector will set the
// axis range based on the view port and the full range.
//
viewer.syncLinearAxisWithViewPort("x", c.xAxis());
viewer.syncLinearAxisWithViewPort("y", c.yAxis());
// We need to update the track line too. If the mouse is moving on the chart (eg. if
// the user drags the mouse on the chart to scroll it), the track line will be updated
// in the MouseMovePlotArea event. Otherwise, we need to update the track line here.
if ((!viewer.IsInMouseMoveEvent) && viewer.IsMouseOnPlotArea)
crossHair(c, viewer.PlotAreaMouseX, viewer.PlotAreaMouseY);
// Set the chart image to the WinChartViewer
viewer.Chart = c;
}
//
// Draw the full thumbnail chart and display it in the given ViewPortControl
//
private void drawFullChart(WinViewPortControl vpc, WinChartViewer viewer)
{
// Create an XYChart object of the same size as the Viewport Control
XYChart c = new XYChart(viewPortControl1.ClientSize.Width, viewPortControl1.ClientSize.Height);
// Set the plotarea to cover the entire chart. Disable grid lines by setting their colors
// to transparent. Set 4 quadrant coloring, where the colors of the quadrants alternate
// between lighter and deeper grey (dddddd/eeeeee).
c.setPlotArea(0, 0, c.getWidth() - 1, c.getHeight() - 1, -1, -1, 0xff0000, Chart.Transparent,
Chart.Transparent).set4QBgColor(0xdddddd, 0xeeeeee, 0xdddddd, 0xeeeeee, 0x000000);
// Set 4 quadrant mode, with both x and y axes symetrical around the origin
c.setAxisAtOrigin(Chart.XYAxisAtOrigin, Chart.XAxisSymmetric + Chart.YAxisSymmetric);
// The x and y axis scales reflect the full range of the view port
c.xAxis().setLinearScale(viewer.getValueAtViewPort("x", 0), viewer.getValueAtViewPort("x", 1),
Chart.NoValue);
c.yAxis().setLinearScale(viewer.getValueAtViewPort("y", 0), viewer.getValueAtViewPort("y", 1),
Chart.NoValue);
// Add scatter layer, using 3 pixels red (ff33333) X shape symbols
c.addScatterLayer(dataX0, dataY0, "Group A", Chart.Cross2Shape(), 3, 0xff3333, 0xff3333);
// Add scatter layer, using 3 pixels green (33ff33) circle symbols
c.addScatterLayer(dataX1, dataY1, "Group B", Chart.CircleShape, 3, 0x33ff33, 0x33ff33);
// Add scatter layer, using 3 pixels blue (3333ff) triangle symbols
c.addScatterLayer(dataX2, dataY2, "Group C", Chart.TriangleSymbol, 3, 0x3333ff, 0x3333ff);
// Set the chart image to the WinChartViewer
vpc.Chart = c;
}
//
// Update the image map
//
private void updateImageMap(WinChartViewer viewer)
{
// Include tool tip for the chart
if (viewer.ImageMap == null)
{
viewer.ImageMap = viewer.Chart.getHTMLImageMap("clickable", "",
"title='[{dataSetName}] Alpha = {x}, Beta = {value}'");
}
}
//
// ClickHotSpot event handler. In this demo, we just display the hot spot parameters in a pop up
// dialog.
//
private void winChartViewer1_ClickHotSpot(object sender, WinHotSpotEventArgs e)
{
// We show the pop up dialog only when the mouse action is not in zoom-in or zoom-out mode.
if ((winChartViewer1.MouseUsage != WinChartMouseUsage.ZoomIn)
&& (winChartViewer1.MouseUsage != WinChartMouseUsage.ZoomOut))
new ParamViewer().Display(sender, e);
}
//
// Pointer (Drag to Scroll) button event handler
//
private void pointerPB_CheckedChanged(object sender, EventArgs e)
{
if (((RadioButton)sender).Checked)
winChartViewer1.MouseUsage = WinChartMouseUsage.ScrollOnDrag;
}
//
// Zoom In button event handler
//
private void zoomInPB_CheckedChanged(object sender, EventArgs e)
{
if (((RadioButton)sender).Checked)
winChartViewer1.MouseUsage = WinChartMouseUsage.ZoomIn;
}
//
// Zoom Out button event handler
//
private void zoomOutPB_CheckedChanged(object sender, EventArgs e)
{
if (((RadioButton)sender).Checked)
winChartViewer1.MouseUsage = WinChartMouseUsage.ZoomOut;
}
//
// Save button event handler
//
private void savePB_Click(object sender, EventArgs e)
{
// The standard Save File dialog
SaveFileDialog fileDlg = new SaveFileDialog();
fileDlg.Filter = "PNG (*.png)|*.png|JPG (*.jpg)|*.jpg|GIF (*.gif)|*.gif|BMP (*.bmp)|*.bmp|" +
"SVG (*.svg)|*.svg|PDF (*.pdf)|*.pdf";
fileDlg.FileName = "chartdirector_demo";
if (fileDlg.ShowDialog() != DialogResult.OK)
return;
// Save the chart
if (null != winChartViewer1.Chart)
winChartViewer1.Chart.makeChart(fileDlg.FileName);
}
//
// ValueChanged event handler for zoomBar. Zoom in around the center point and try to
// maintain the aspect ratio
//
private void zoomBar_ValueChanged(object sender, EventArgs e)
{
if (!winChartViewer1.IsInViewPortChangedEvent)
{
//Remember the center point
double centerX = winChartViewer1.ViewPortLeft + winChartViewer1.ViewPortWidth / 2;
double centerY = winChartViewer1.ViewPortTop + winChartViewer1.ViewPortHeight / 2;
//Aspect ratio and zoom factor
double aspectRatio = winChartViewer1.ViewPortWidth / winChartViewer1.ViewPortHeight;
double zoomTo = ((double)zoomBar.Value) / zoomBar.Maximum;
//Zoom while respecting the aspect ratio
winChartViewer1.ViewPortWidth = zoomTo * Math.Max(1, aspectRatio);
winChartViewer1.ViewPortHeight = zoomTo * Math.Max(1, 1 / aspectRatio);
//Adjust ViewPortLeft and ViewPortTop to keep center point unchanged
winChartViewer1.ViewPortLeft = centerX - winChartViewer1.ViewPortWidth / 2;
winChartViewer1.ViewPortTop = centerY - winChartViewer1.ViewPortHeight / 2;
//update the chart, but no need to update the image map yet, as the chart is still
//zooming and is unstable
winChartViewer1.updateViewPort(true, false);
}
}
//
// Draw track cursor when mouse is moving over plotarea, and update image map if necessary
//
private void winChartViewer1_MouseMovePlotArea(object sender, MouseEventArgs e)
{
WinChartViewer viewer = (WinChartViewer)sender;
// Draw crosshair track cursor
crossHair((XYChart)viewer.Chart, viewer.PlotAreaMouseX, viewer.PlotAreaMouseY);
viewer.updateDisplay();
// Hide the track cursor when the mouse leaves the plot area
viewer.removeDynamicLayer("MouseLeavePlotArea");
// Update image map if necessary. If the mouse is still dragging, the chart is still
// updating and not confirmed, so there is no need to set up the image map.
if (!viewer.IsMouseDragging)
updateImageMap(viewer);
}
//
// Draw cross hair cursor with axis labels
//
private void crossHair(XYChart c, int mouseX, int mouseY)
{
// Clear the current dynamic layer and get the DrawArea object to draw on it.
DrawArea d = c.initDynamicLayer();
// The plot area object
PlotArea plotArea = c.getPlotArea();
// Draw a vertical line and a horizontal line as the cross hair
d.vline(plotArea.getTopY(), plotArea.getBottomY(), mouseX, d.dashLineColor(0x000000, 0x0101));
d.hline(plotArea.getLeftX(), plotArea.getRightX(), mouseY, d.dashLineColor(0x000000, 0x0101));
// Draw y-axis label
string label = "<*block,bgColor=FFFFDD,margin=3,edgeColor=000000*>" + c.formatValue(c.getYValue(
mouseY, c.yAxis()), "{value|P4}") + "<*/*>";
TTFText t = d.text(label, "Arial Bold", 8);
t.draw(plotArea.getLeftX() - 5, mouseY, 0x000000, Chart.Right);
// Draw x-axis label
label = "<*block,bgColor=FFFFDD,margin=3,edgeColor=000000*>" + c.formatValue(c.getXValue(mouseX),
"{value|P4}") + "<*/*>";
t = d.text(label, "Arial Bold", 8);
t.draw(mouseX, plotArea.getBottomY() + 5, 0x000000, Chart.Top);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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 LSL_Float = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLFloat;
using LSL_Integer = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLInteger;
using LSL_Key = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using LSL_List = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.list;
using LSL_Rotation = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Quaternion;
using LSL_String = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using LSL_Vector = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Vector3;
namespace Aurora.ScriptEngine.AuroraDotNetEngine.APIs.Interfaces
{
public interface ILSL_Api
{
void state(string newState);
LSL_Integer llAbs(int i);
LSL_Float llAcos(double val);
DateTime llAddToLandBanList(string avatar, double hours);
DateTime llAddToLandPassList(string avatar, double hours);
DateTime llAdjustSoundVolume(double volume);
void llAllowInventoryDrop(int add);
LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b);
void llApplyImpulse(LSL_Vector force, int local);
void llApplyRotationalImpulse(LSL_Vector force, int local);
LSL_Float llAsin(double val);
LSL_Float llAtan2(double x, double y);
void llAttachToAvatar(int attachment);
LSL_Key llAvatarOnSitTarget();
LSL_Key llAvatarOnLinkSitTarget();
LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up);
LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, LSL_Float angle);
LSL_Integer llBase64ToInteger(string str);
LSL_String llBase64ToString(string str);
void llBreakAllLinks();
void llBreakLink(int linknum);
LSL_Integer llCeil(double f);
void llClearCameraParams();
LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face);
DateTime llCloseRemoteDataChannel(object channel);
LSL_Float llCloud(LSL_Vector offset);
void llCollisionFilter(string name, string id, int accept);
void llCollisionSound(string impact_sound, double impact_volume);
void llCollisionSprite(string impact_sprite);
LSL_Float llCos(double f);
DateTime llCreateLink(string target, int parent);
LSL_List llCSV2List(string src);
LSL_List llDeleteSubList(LSL_List src, int start, int end);
LSL_String llDeleteSubString(string src, int start, int end);
void llDetachFromAvatar();
LSL_Vector llDetectedGrab(int number);
LSL_Integer llDetectedGroup(int number);
LSL_Key llDetectedKey(int number);
LSL_Integer llDetectedLinkNumber(int number);
LSL_String llDetectedName(int number);
LSL_Key llDetectedOwner(int number);
LSL_Vector llDetectedPos(int number);
LSL_Rotation llDetectedRot(int number);
LSL_Integer llDetectedType(int number);
LSL_Vector llDetectedTouchBinormal(int index);
LSL_Integer llDetectedTouchFace(int index);
LSL_Vector llDetectedTouchNormal(int index);
LSL_Vector llDetectedTouchPos(int index);
LSL_Vector llDetectedTouchST(int index);
LSL_Vector llDetectedTouchUV(int index);
LSL_Vector llDetectedVel(int number);
DateTime llDialog(string avatar, string message, LSL_List buttons, int chat_channel);
void llDie();
LSL_String llDumpList2String(LSL_List src, string seperator);
LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir);
DateTime llEjectFromLand(string pest);
DateTime llEmail(string address, string subject, string message);
LSL_String llEscapeURL(string url);
LSL_Rotation llEuler2Rot(LSL_Vector v);
LSL_Float llFabs(double f);
LSL_Integer llFloor(double f);
void llForceMouselook(int mouselook);
LSL_Float llFrand(double mag);
LSL_Vector llGetAccel();
LSL_Integer llGetAgentInfo(string id);
LSL_String llGetAgentLanguage(string id);
LSL_List llGetAgentList(LSL_Integer scope, LSL_List options);
LSL_Vector llGetAgentSize(string id);
LSL_Float llGetAlpha(int face);
LSL_Float llGetAndResetTime();
LSL_String llGetAnimation(string id);
LSL_List llGetAnimationList(string id);
LSL_Integer llGetAttached();
LSL_List llGetBoundingBox(string obj);
LSL_Vector llGetCameraPos();
LSL_Rotation llGetCameraRot();
LSL_Vector llGetCenterOfMass();
LSL_Vector llGetColor(int face);
LSL_String llGetCreator();
LSL_String llGetDate();
LSL_Float llGetEnergy();
LSL_Vector llGetForce();
LSL_Integer llGetFreeMemory();
LSL_Integer llGetFreeURLs();
LSL_Vector llGetGeometricCenter();
LSL_Float llGetGMTclock();
LSL_String llGetHTTPHeader(LSL_Key request_id, string header);
LSL_Key llGetInventoryCreator(string item);
LSL_Key llGetInventoryKey(string name);
LSL_String llGetInventoryName(int type, int number);
LSL_Integer llGetInventoryNumber(int type);
LSL_Integer llGetInventoryPermMask(string item, int mask);
LSL_Integer llGetInventoryType(string name);
LSL_Key llGenerateKey();
LSL_Key llGetKey();
LSL_Key llGetLandOwnerAt(LSL_Vector pos);
LSL_Key llGetLinkKey(int linknum);
LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules);
LSL_String llGetLinkName(int linknum);
LSL_Integer llGetLinkNumber();
LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules);
LSL_Integer llGetListEntryType(LSL_List src, int index);
LSL_Integer llGetListLength(LSL_List src);
LSL_Vector llGetLocalPos();
LSL_Rotation llGetLocalRot();
LSL_Float llGetMass();
LSL_Float llGetMassMKS();
void llGetNextEmail(string address, string subject);
LSL_Key llGetNotecardLine(string name, int line);
LSL_Key llGetNumberOfNotecardLines(string name);
LSL_Integer llGetNumberOfPrims();
LSL_Integer llGetNumberOfSides();
LSL_String llGetObjectDesc();
LSL_List llGetObjectDetails(string id, LSL_List args);
LSL_Float llGetObjectMass(string id);
LSL_String llGetObjectName();
LSL_Integer llGetObjectPermMask(int mask);
LSL_Integer llGetObjectPrimCount(string object_id);
LSL_Vector llGetOmega();
LSL_Key llGetOwner();
LSL_Key llGetOwnerKey(string id);
LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param);
LSL_Integer llGetParcelFlags(LSL_Vector pos);
LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide);
LSL_String llGetParcelMusicURL();
LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide);
LSL_List llGetParcelPrimOwners(LSL_Vector pos);
LSL_Integer llGetPermissions();
LSL_Key llGetPermissionsKey();
LSL_Vector llGetPos();
LSL_List llGetPrimitiveParams(LSL_List rules);
LSL_Integer llGetRegionAgentCount();
LSL_Vector llGetRegionCorner();
LSL_Integer llGetRegionFlags();
LSL_Float llGetRegionFPS();
LSL_String llGetRegionName();
LSL_Float llGetRegionTimeDilation();
LSL_Vector llGetRootPosition();
LSL_Rotation llGetRootRotation();
LSL_Rotation llGetRot();
LSL_Vector llGetScale();
LSL_String llGetScriptName();
LSL_Integer llGetScriptState(string name);
LSL_String llGetSimulatorHostname();
LSL_Integer llGetSPMaxMemory();
LSL_Integer llGetStartParameter();
LSL_Integer llGetStatus(int status);
LSL_String llGetSubString(string src, int start, int end);
LSL_Vector llGetSunDirection();
LSL_String llGetTexture(int face);
LSL_Vector llGetTextureOffset(int face);
LSL_Float llGetTextureRot(int side);
LSL_Vector llGetTextureScale(int side);
LSL_Float llGetTime();
LSL_Float llGetTimeOfDay();
LSL_String llGetTimestamp();
LSL_Vector llGetTorque();
LSL_Integer llGetUnixTime();
LSL_Integer llGetUsedMemory();
LSL_Vector llGetVel();
LSL_Float llGetWallclock();
DateTime llGiveInventory(string destination, string inventory);
void llGiveInventoryList(string destination, string category, LSL_List inventory);
LSL_Integer llGiveMoney(string destination, int amount);
void llGodLikeRezObject(string inventory, LSL_Vector pos);
LSL_Float llGround(LSL_Vector offset);
LSL_Vector llGroundContour(LSL_Vector offset);
LSL_Vector llGroundNormal(LSL_Vector offset);
void llGroundRepel(double height, int water, double tau);
LSL_Vector llGroundSlope(LSL_Vector offset);
LSL_String llHTTPRequest(string url, LSL_List parameters, string body);
void llHTTPResponse(LSL_Key id, int status, string body);
LSL_String llInsertString(string dst, int position, string src);
DateTime llInstantMessage(string user, string message);
LSL_String llIntegerToBase64(int number);
LSL_String llKey2Name(string id);
void llLinkParticleSystem(int linknum, LSL_List rules);
void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot);
LSL_String llList2CSV(LSL_List src);
LSL_Float llList2Float(LSL_List src, int index);
LSL_Integer llList2Integer(LSL_List src, int index);
LSL_Key llList2Key(LSL_List src, int index);
LSL_List llList2List(LSL_List src, int start, int end);
LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride);
LSL_Rotation llList2Rot(LSL_List src, int index);
LSL_String llList2String(LSL_List src, int index);
LSL_Vector llList2Vector(LSL_List src, int index);
LSL_Integer llListen(int channelID, string name, string ID, string msg);
void llListenControl(int number, int active);
void llListenRemove(int number);
LSL_Integer llListFindList(LSL_List src, LSL_List test);
LSL_List llListInsertList(LSL_List dest, LSL_List src, int start);
LSL_List llListRandomize(LSL_List src, int stride);
LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end);
LSL_List llListSort(LSL_List src, int stride, int ascending);
LSL_Float llListStatistics(int operation, LSL_List src);
DateTime llLoadURL(string avatar_id, string message, string url);
LSL_Float llLog(double val);
LSL_Float llLog10(double val);
void llLookAt(LSL_Vector target, double strength, double damping);
void llLoopSound(string sound, double volume);
void llLoopSoundMaster(string sound, double volume);
void llLoopSoundSlave(string sound, double volume);
DateTime llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture,
LSL_Vector offset);
DateTime llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture,
LSL_Vector offset);
DateTime llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce,
string texture, LSL_Vector offset, double bounce_offset);
DateTime llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture,
LSL_Vector offset);
LSL_Integer llManageEstateAccess(LSL_Integer action, LSL_String avatar);
DateTime llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at);
LSL_String llMD5String(string src, int nonce);
LSL_String llSHA1String(string src);
void llMessageLinked(int linknum, int num, string str, string id);
void llMinEventDelay(double delay);
void llModifyLand(int action, int brush);
LSL_Integer llModPow(int a, int b, int c);
void llMoveToTarget(LSL_Vector target, double tau);
DateTime llOffsetTexture(double u, double v, int face);
DateTime llOpenRemoteDataChannel();
LSL_Integer llOverMyLand(string id);
void llOwnerSay(string msg);
DateTime llParcelMediaCommandList(LSL_List commandList);
LSL_List llParcelMediaQuery(LSL_List aList);
LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers);
LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers);
void llParticleSystem(LSL_List rules);
void llPassCollisions(int pass);
void llPassTouches(int pass);
void llPlaySound(string sound, double volume);
void llPlaySoundSlave(string sound, double volume);
void llPointAt(LSL_Vector pos);
LSL_Float llPow(double fbase, double fexponent);
DateTime llPreloadSound(string sound);
void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local);
DateTime llRefreshPrimURL();
void llRegionSay(int channelID, string text);
void llRegionSayTo(LSL_Key toID, int channelID, string text);
void llReleaseCamera(string avatar);
void llReleaseControls();
void llReleaseURL(string url);
DateTime llRemoteDataReply(string channel, string message_id, string sdata, int idata);
void llRemoteDataSetRegion();
DateTime llRemoteLoadScript(string target, string name, int running, int start_param);
DateTime llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param);
DateTime llRemoveFromLandBanList(string avatar);
DateTime llRemoveFromLandPassList(string avatar);
void llRemoveInventory(string item);
void llRemoveVehicleFlags(int flags);
LSL_String llRequestAgentData(string id, int data);
LSL_Key llRequestInventoryData(string name);
void llRequestPermissions(string agent, int perm);
LSL_String llRequestSecureURL();
LSL_Key llRequestSimulatorData(string simulator, int data);
LSL_Key llRequestURL();
DateTime llResetLandBanList();
DateTime llResetLandPassList();
void llResetOtherScript(string name);
void llResetScript();
void llResetTime();
DateTime llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param);
DateTime llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param);
LSL_Float llRot2Angle(LSL_Rotation rot);
LSL_Vector llRot2Axis(LSL_Rotation rot);
LSL_Vector llRot2Euler(LSL_Rotation r);
LSL_Vector llRot2Fwd(LSL_Rotation r);
LSL_Vector llRot2Left(LSL_Rotation r);
LSL_Vector llRot2Up(LSL_Rotation r);
DateTime llRotateTexture(double rotation, int face);
LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end);
void llRotLookAt(LSL_Rotation target, double strength, double damping);
LSL_Integer llRotTarget(LSL_Rotation rot, double error);
void llRotTargetRemove(int number);
LSL_Integer llRound(double f);
LSL_Integer llSameGroup(string agent);
void llSay(int channelID, object text);
DateTime llScaleTexture(double u, double v, int face);
LSL_Integer llScriptDanger(LSL_Vector pos);
void llScriptProfiler(LSL_Integer profilerFlags);
LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata);
void llSensor(string name, string id, int type, double range, double arc);
void llSensorRemove();
void llSensorRepeat(string name, string id, int type, double range, double arc, double rate);
void llSetAlpha(double alpha, int face);
void llSetAngularVelocity(LSL_Vector force, LSL_Integer local);
void llSetBuoyancy(double buoyancy);
void llSetCameraAtOffset(LSL_Vector offset);
void llSetCameraEyeOffset(LSL_Vector offset);
void llSetCameraParams(LSL_List rules);
void llSetClickAction(int action);
void llSetColor(LSL_Vector color, int face);
void llSetContentType(LSL_Key id, LSL_Integer type);
void llSetDamage(double damage);
void llSetForce(LSL_Vector force, int local);
void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local);
void llSetHoverHeight(double height, int water, double tau);
void llSetInventoryPermMask(string item, int mask, int value);
void llSetKeyframedMotion(LSL_List keyframes, LSL_List options);
void llSetLinkAlpha(int linknumber, double alpha, int face);
void llSetLinkColor(int linknumber, LSL_Vector color, int face);
LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules);
void llSetLinkPrimitiveParams(int linknumber, LSL_List rules);
DateTime llSetLinkTexture(int linknumber, string texture, int face);
void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length,
double rate);
DateTime llSetLocalRot(LSL_Rotation rot);
LSL_Integer llSetMemoryLimit(LSL_Integer limit);
LSL_Integer llGetMemoryLimit();
void llSetObjectDesc(string desc);
void llSetObjectName(string name);
void llSetObjectPermMask(int mask, int value);
DateTime llSetParcelMusicURL(string url);
void llSetPayPrice(int price, LSL_List quick_pay_buttons);
DateTime llSetPos(LSL_Vector pos);
void llSetPrimitiveParams(LSL_List rules);
void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at);
void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules);
DateTime llSetPrimURL(string url);
LSL_Integer llSetRegionPos(LSL_Vector pos);
void llSetRemoteScriptAccessPin(int pin);
DateTime llSetRot(LSL_Rotation rot);
void llSetScale(LSL_Vector scale);
void llSetScriptState(string name, int run);
void llSetSitText(string text);
void llSetSoundQueueing(int queue);
void llSetSoundRadius(double radius);
void llSetStatus(int status, int value);
void llSetText(string text, LSL_Vector color, LSL_Float alpha);
DateTime llSetTexture(string texture, int face);
void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetTimerEvent(double sec);
void llSetTorque(LSL_Vector torque, int local);
void llSetTouchText(string text);
void llSetVehicleFlags(int flags);
void llSetVehicleFloatParam(int param, LSL_Float value);
void llSetVehicleRotationParam(int param, LSL_Rotation rot);
void llSetVehicleType(int type);
void llSetVehicleVectorParam(int param, LSL_Vector vec);
void llSetVelocity(LSL_Vector force, LSL_Integer local);
void llShout(int channelID, string text);
LSL_Float llSin(double f);
void llSitTarget(LSL_Vector offset, LSL_Rotation rot);
DateTime llSleep(double sec);
void llSound(string sound, double volume, int queue, int loop);
void llSoundPreload(string sound);
LSL_Float llSqrt(double f);
void llStartAnimation(string anim);
void llStopAnimation(string anim);
void llStopHover();
void llStopLookAt();
void llStopMoveToTarget();
void llStopPointAt();
void llStopSound();
LSL_Integer llStringLength(string str);
LSL_String llStringToBase64(string str);
LSL_String llStringTrim(string src, int type);
LSL_Integer llSubStringIndex(string source, string pattern);
void llTakeCamera(string avatar);
void llTakeControls(int controls, int accept, int pass_on);
LSL_Float llTan(double f);
LSL_Integer llTarget(LSL_Vector position, LSL_Float range);
void llTargetOmega(LSL_Vector axis, LSL_Float spinrate, LSL_Float gain);
void llTargetRemove(int number);
void llTeleportAgent(LSL_Key avatar, LSL_String landmark, LSL_Vector position, LSL_Vector look_at);
void llTeleportAgentGlobalCoords(LSL_Key agent, LSL_Vector global_coordinates,
LSL_Vector region_coordinates, LSL_Vector look_at);
DateTime llTeleportAgentHome(LSL_Key agent);
DateTime llTextBox(string avatar, string message, int chat_channel);
LSL_String llToLower(string source);
LSL_String llToUpper(string source);
LSL_String llTransferLindenDollars(LSL_String destination, LSL_Integer amt);
void llTriggerSound(string sound, double volume);
void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west);
LSL_String llUnescapeURL(string url);
void llUnSit(string id);
LSL_Float llVecDist(LSL_Vector a, LSL_Vector b);
LSL_Float llVecMag(LSL_Vector v);
LSL_Vector llVecNorm(LSL_Vector v);
void llVolumeDetect(int detect);
LSL_Float llWater(LSL_Vector offset);
void llWhisper(int channelID, string text);
LSL_Vector llWind(LSL_Vector offset);
LSL_String llXorBase64Strings(string str1, string str2);
LSL_String llXorBase64StringsCorrect(string str1, string str2);
void SetPrimitiveParamsEx(LSL_Key prim, LSL_List rules);
LSL_List GetLinkPrimitiveParamsEx(LSL_Key prim, LSL_List rules);
LSL_Integer llSetPrimMediaParams(LSL_Integer face, LSL_List commandList);
LSL_Integer llClearPrimMedia(LSL_Integer face);
LSL_List llGetPrimMediaParams(LSL_Integer face, LSL_List aList);
LSL_Integer llGetLinkNumberOfSides(int LinkNum);
DateTime llRezPrim(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param,
bool isRezAtRoot, bool doRecoil, bool SetDieAtEdge, bool CheckPos);
void print(string str);
LSL_String llGetDisplayName(string id);
LSL_String llGetUsername(string id);
LSL_String llGetEnv(LSL_String name);
LSL_Key llRequestDisplayName(LSL_Key uuid);
LSL_Key llRequestUsername(LSL_Key uuid);
LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options);
void llCreateCharacter(LSL_List options);
void llUpdateCharacter(LSL_List options);
void llDeleteCharacter();
void llPursue(LSL_Key target, LSL_List options);
void llEvade(LSL_Key target, LSL_List options);
void llFleeFrom(LSL_Vector source, LSL_Float distance, LSL_List options);
void llPatrolPoints(LSL_List patrolPoints, LSL_List options);
void llWanderWithin(LSL_Vector origin, LSL_Float distance, LSL_List options);
LSL_List llGetClosestNavPoint(LSL_Vector point, LSL_List options);
void llNavigateTo(LSL_Vector point, LSL_List options);
void llExecCharacterCmd(LSL_Integer command, LSL_List options);
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
namespace CameraProfile
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Media.Capture;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
/// <summary>
/// SetRecordProfile page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario1_SetRecordProfile : Page
{
/// <summary>
/// Private MainPage object for status updates
/// </summary>
private MainPage rootPage;
/// <summary>
/// Initializes a new instance of the <see cref="Scenario1_SetRecordProfile"/> class.
/// </summary>
public Scenario1_SetRecordProfile()
{
this.InitializeComponent();
}
/// <summary>
/// Override default OnNavigateTo to initialize
/// the rootPage object for Status message updates
/// </summary>
/// <param name="e">Contains state information and event data associated with the event</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
/// <summary>
/// Locates a video profile for the back camera and then queries if
/// the discovered profile supports 640x480 30 FPS recording.
/// If a supported profile is located, then we configure media
/// settings to the matching profile. Else we use default profile.
/// </summary>
/// <param name="sender">Contains information regarding button that fired event</param>
/// <param name="e">Contains state information and event data associated with the event</param>
private async void InitRecordProfileBtn_Click(object sender, RoutedEventArgs e)
{
MediaCapture mediaCapture = new MediaCapture();
MediaCaptureInitializationSettings mediaInitSettings = new MediaCaptureInitializationSettings();
string videoDeviceId = string.Empty;
// Look for a video capture device Id with a video profile matching panel location
videoDeviceId = await GetVideoProfileSupportedDeviceIdAsync(Windows.Devices.Enumeration.Panel.Back);
if (string.IsNullOrEmpty(videoDeviceId))
{
await LogStatus("ERROR: No Video Device Id found, verify your device supports profiles", NotifyType.ErrorMessage);
return;
}
await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture, "Found video capture device that supports Video Profile, Device Id:\r\n {0}", videoDeviceId));
await LogStatusToOutputBox("Retrieving all Video Profiles");
IReadOnlyList<MediaCaptureVideoProfile> profiles = MediaCapture.FindAllVideoProfiles(videoDeviceId);
await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture, "Number of Video Profiles found: {0}", profiles.Count));
// Output all Video Profiles found, frame rate is rounded up for display purposes
foreach (var profile in profiles)
{
var description = profile.SupportedRecordMediaDescription;
foreach (var desc in description)
{
await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture,
"Video Profile Found: Profile Id: {0}\r\n Width: {1} Height: {2} FrameRate: {3}", profile.Id, desc.Width, desc.Height, Math.Round(desc.FrameRate).ToString()));
}
}
// Look for WVGA 30FPS profile
await LogStatusToOutputBox("Querying for matching WVGA 30FPS Profile");
var match = (from profile in profiles
from desc in profile.SupportedRecordMediaDescription
where desc.Width == 640 && desc.Height == 480 && Math.Round(desc.FrameRate) == 30
select new { profile, desc }).FirstOrDefault();
if (match != null)
{
mediaInitSettings.VideoProfile = match.profile;
mediaInitSettings.RecordMediaDescription = match.desc;
await LogStatus(string.Format(CultureInfo.InvariantCulture,
"Matching WVGA 30FPS Video Profile found: \r\n Profile Id: {0}\r\n Width: {1} Height: {2} FrameRate: {3}",
mediaInitSettings.VideoProfile.Id, mediaInitSettings.RecordMediaDescription.Width,
mediaInitSettings.RecordMediaDescription.Height, Math.Round(mediaInitSettings.RecordMediaDescription.FrameRate).ToString()), NotifyType.StatusMessage);
}
else
{
// Could not locate a WVGA 30FPS profile, use default video recording profile
mediaInitSettings.VideoProfile = profiles[0];
await LogStatus("Could not locate a matching profile, setting to default recording profile", NotifyType.ErrorMessage);
}
await mediaCapture.InitializeAsync(mediaInitSettings);
await LogStatusToOutputBox("Media Capture settings initialized to selected profile");
}
/// <summary>
/// Locates a video profile for the back camera and then queries if
/// the discovered profile is a matching custom profile.
/// If a custom profile is located, we configure media
/// settings to the custom profile. Else we use default profile.
/// </summary>
/// <param name="sender">Contains information regarding button that fired event</param>
/// <param name="e">Contains state information and event data associated with the event</param>
private async void InitCustomProfileBtn_Click(object sender, RoutedEventArgs e)
{
MediaCapture mediaCapture = new MediaCapture();
MediaCaptureInitializationSettings mediaInitSettings = new MediaCaptureInitializationSettings();
string videoDeviceId = string.Empty;
// For demonstration purposes, we use the Profile Id from WVGA 640x480 30 FPS profile available
// on desktop simulator and phone emulators
string customProfileId = "{A0E517E8-8F8C-4F6F-9A57-46FC2F647EC0},0";
videoDeviceId = await GetVideoProfileSupportedDeviceIdAsync(Windows.Devices.Enumeration.Panel.Back);
if (string.IsNullOrEmpty(videoDeviceId))
{
await LogStatus("ERROR: No Video Device Id found, verify your device supports profiles", NotifyType.ErrorMessage);
return;
}
await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture, "Found video capture device that supports Video Profile, Device Id:\r\n {0}", videoDeviceId));
await LogStatusToOutputBox("Querying device for custom profile support");
mediaInitSettings.VideoProfile = (from profile in MediaCapture.FindAllVideoProfiles(videoDeviceId)
where profile.Id == customProfileId
select profile).FirstOrDefault();
// In the event the profile isn't located, we set Video Profile to the default
if (mediaInitSettings.VideoProfile == null)
{
await LogStatus("Could not locate a matching profile, setting to default recording profile", NotifyType.ErrorMessage);
mediaInitSettings.VideoProfile = MediaCapture.FindAllVideoProfiles(videoDeviceId).FirstOrDefault();
}
await LogStatus(string.Format(CultureInfo.InvariantCulture, "Custom recording profile located: {0}", customProfileId), NotifyType.StatusMessage);
await mediaCapture.InitializeAsync(mediaInitSettings);
}
/// <summary>
/// Helper method to obtain a device Id that supports a Video Profile.
/// If no Video Profile is found we return empty string indicating that there isn't a device on
/// the desired panel with a supported Video Profile.
/// </summary>
/// <param name="panel">Contains Device Enumeration information regarding camera panel we are looking for</param>
/// <returns>Device Information Id string</returns>
public async Task<string> GetVideoProfileSupportedDeviceIdAsync(Windows.Devices.Enumeration.Panel panel)
{
string deviceId = string.Empty;
// Find all video capture devices
await LogStatusToOutputBox("Looking for all video capture devices");
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
await LogStatusToOutputBox(string.Format(CultureInfo.InvariantCulture, "Number of video capture devices found: {0}", devices.Count.ToString()));
// Loop through devices looking for device that supports Video Profile
foreach (var device in devices)
{
// Check if the device on the requested panel supports Video Profile
if (MediaCapture.IsVideoProfileSupported(device.Id) && device.EnclosureLocation.Panel == panel)
{
// We've located a device that supports Video Profiles on expected panel
deviceId = device.Id;
break;
}
}
return deviceId;
}
/// <summary>
/// Marshall log message to the UI thread
/// and update outputBox, this method is for more general messages
/// </summary>
/// <param name="message">Message to log to the outputBox</param>
private async Task LogStatusToOutputBox(string message)
{
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
outputBox.Text += message + "\r\n";
outputScrollViewer.ChangeView(0, outputBox.ActualHeight, 1);
});
}
/// <summary>
/// Method to log Status to Main Status block,
/// this method is for important status messages to be
/// displayed at bottom of scenario page
/// </summary>
/// <param name="message">Message to log to the output box</param>
/// <param name="type">Notification Type for status message</param>
private async Task LogStatus(string message, NotifyType type)
{
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser(message, type);
});
await LogStatusToOutputBox(message);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="RectKeyFrameCollection.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This collection is used in conjunction with a KeyFrameRectAnimation
/// to animate a Rect property value along a set of key frames.
/// </summary>
public class RectKeyFrameCollection : Freezable, IList
{
#region Data
private List<RectKeyFrame> _keyFrames;
private static RectKeyFrameCollection s_emptyCollection;
#endregion
#region Constructors
/// <Summary>
/// Creates a new RectKeyFrameCollection.
/// </Summary>
public RectKeyFrameCollection()
: base()
{
_keyFrames = new List< RectKeyFrame>(2);
}
#endregion
#region Static Methods
/// <summary>
/// An empty RectKeyFrameCollection.
/// </summary>
public static RectKeyFrameCollection Empty
{
get
{
if (s_emptyCollection == null)
{
RectKeyFrameCollection emptyCollection = new RectKeyFrameCollection();
emptyCollection._keyFrames = new List< RectKeyFrame>(0);
emptyCollection.Freeze();
s_emptyCollection = emptyCollection;
}
return s_emptyCollection;
}
}
#endregion
#region Freezable
/// <summary>
/// Creates a freezable copy of this RectKeyFrameCollection.
/// </summary>
/// <returns>The copy</returns>
public new RectKeyFrameCollection Clone()
{
return (RectKeyFrameCollection)base.Clone();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new RectKeyFrameCollection();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
RectKeyFrameCollection sourceCollection = (RectKeyFrameCollection) sourceFreezable;
base.CloneCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< RectKeyFrame>(count);
for (int i = 0; i < count; i++)
{
RectKeyFrame keyFrame = (RectKeyFrame)sourceCollection._keyFrames[i].Clone();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(System.Windows.Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
RectKeyFrameCollection sourceCollection = (RectKeyFrameCollection) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< RectKeyFrame>(count);
for (int i = 0; i < count; i++)
{
RectKeyFrame keyFrame = (RectKeyFrame)sourceCollection._keyFrames[i].CloneCurrentValue();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(System.Windows.Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable sourceFreezable)
{
RectKeyFrameCollection sourceCollection = (RectKeyFrameCollection) sourceFreezable;
base.GetAsFrozenCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< RectKeyFrame>(count);
for (int i = 0; i < count; i++)
{
RectKeyFrame keyFrame = (RectKeyFrame)sourceCollection._keyFrames[i].GetAsFrozen();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(System.Windows.Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable)
{
RectKeyFrameCollection sourceCollection = (RectKeyFrameCollection) sourceFreezable;
base.GetCurrentValueAsFrozenCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< RectKeyFrame>(count);
for (int i = 0; i < count; i++)
{
RectKeyFrame keyFrame = (RectKeyFrame)sourceCollection._keyFrames[i].GetCurrentValueAsFrozen();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
///
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
for (int i = 0; i < _keyFrames.Count && canFreeze; i++)
{
canFreeze &= Freezable.Freeze(_keyFrames[i], isChecking);
}
return canFreeze;
}
#endregion
#region IEnumerable
/// <summary>
/// Returns an enumerator of the RectKeyFrames in the collection.
/// </summary>
public IEnumerator GetEnumerator()
{
ReadPreamble();
return _keyFrames.GetEnumerator();
}
#endregion
#region ICollection
/// <summary>
/// Returns the number of RectKeyFrames in the collection.
/// </summary>
public int Count
{
get
{
ReadPreamble();
return _keyFrames.Count;
}
}
/// <summary>
/// See <see cref="System.Collections.ICollection.IsSynchronized">ICollection.IsSynchronized</see>.
/// </summary>
public bool IsSynchronized
{
get
{
ReadPreamble();
return (IsFrozen || Dispatcher != null);
}
}
/// <summary>
/// See <see cref="System.Collections.ICollection.SyncRoot">ICollection.SyncRoot</see>.
/// </summary>
public object SyncRoot
{
get
{
ReadPreamble();
return ((ICollection)_keyFrames).SyncRoot;
}
}
/// <summary>
/// Copies all of the RectKeyFrames in the collection to an
/// array.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
ReadPreamble();
((ICollection)_keyFrames).CopyTo(array, index);
}
/// <summary>
/// Copies all of the RectKeyFrames in the collection to an
/// array of RectKeyFrames.
/// </summary>
public void CopyTo(RectKeyFrame[] array, int index)
{
ReadPreamble();
_keyFrames.CopyTo(array, index);
}
#endregion
#region IList
/// <summary>
/// Adds a RectKeyFrame to the collection.
/// </summary>
int IList.Add(object keyFrame)
{
return Add((RectKeyFrame)keyFrame);
}
/// <summary>
/// Adds a RectKeyFrame to the collection.
/// </summary>
public int Add(RectKeyFrame keyFrame)
{
if (keyFrame == null)
{
throw new ArgumentNullException("keyFrame");
}
WritePreamble();
OnFreezablePropertyChanged(null, keyFrame);
_keyFrames.Add(keyFrame);
WritePostscript();
return _keyFrames.Count - 1;
}
/// <summary>
/// Removes all RectKeyFrames from the collection.
/// </summary>
public void Clear()
{
WritePreamble();
if (_keyFrames.Count > 0)
{
for (int i = 0; i < _keyFrames.Count; i++)
{
OnFreezablePropertyChanged(_keyFrames[i], null);
}
_keyFrames.Clear();
WritePostscript();
}
}
/// <summary>
/// Returns true of the collection contains the given RectKeyFrame.
/// </summary>
bool IList.Contains(object keyFrame)
{
return Contains((RectKeyFrame)keyFrame);
}
/// <summary>
/// Returns true of the collection contains the given RectKeyFrame.
/// </summary>
public bool Contains(RectKeyFrame keyFrame)
{
ReadPreamble();
return _keyFrames.Contains(keyFrame);
}
/// <summary>
/// Returns the index of a given RectKeyFrame in the collection.
/// </summary>
int IList.IndexOf(object keyFrame)
{
return IndexOf((RectKeyFrame)keyFrame);
}
/// <summary>
/// Returns the index of a given RectKeyFrame in the collection.
/// </summary>
public int IndexOf(RectKeyFrame keyFrame)
{
ReadPreamble();
return _keyFrames.IndexOf(keyFrame);
}
/// <summary>
/// Inserts a RectKeyFrame into a specific location in the collection.
/// </summary>
void IList.Insert(int index, object keyFrame)
{
Insert(index, (RectKeyFrame)keyFrame);
}
/// <summary>
/// Inserts a RectKeyFrame into a specific location in the collection.
/// </summary>
public void Insert(int index, RectKeyFrame keyFrame)
{
if (keyFrame == null)
{
throw new ArgumentNullException("keyFrame");
}
WritePreamble();
OnFreezablePropertyChanged(null, keyFrame);
_keyFrames.Insert(index, keyFrame);
WritePostscript();
}
/// <summary>
/// Returns true if the collection is frozen.
/// </summary>
public bool IsFixedSize
{
get
{
ReadPreamble();
return IsFrozen;
}
}
/// <summary>
/// Returns true if the collection is frozen.
/// </summary>
public bool IsReadOnly
{
get
{
ReadPreamble();
return IsFrozen;
}
}
/// <summary>
/// Removes a RectKeyFrame from the collection.
/// </summary>
void IList.Remove(object keyFrame)
{
Remove((RectKeyFrame)keyFrame);
}
/// <summary>
/// Removes a RectKeyFrame from the collection.
/// </summary>
public void Remove(RectKeyFrame keyFrame)
{
WritePreamble();
if (_keyFrames.Contains(keyFrame))
{
OnFreezablePropertyChanged(keyFrame, null);
_keyFrames.Remove(keyFrame);
WritePostscript();
}
}
/// <summary>
/// Removes the RectKeyFrame at the specified index from the collection.
/// </summary>
public void RemoveAt(int index)
{
WritePreamble();
OnFreezablePropertyChanged(_keyFrames[index], null);
_keyFrames.RemoveAt(index);
WritePostscript();
}
/// <summary>
/// Gets or sets the RectKeyFrame at a given index.
/// </summary>
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (RectKeyFrame)value;
}
}
/// <summary>
/// Gets or sets the RectKeyFrame at a given index.
/// </summary>
public RectKeyFrame this[int index]
{
get
{
ReadPreamble();
return _keyFrames[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "RectKeyFrameCollection[{0}]", index));
}
WritePreamble();
if (value != _keyFrames[index])
{
OnFreezablePropertyChanged(_keyFrames[index], value);
_keyFrames[index] = value;
Debug.Assert(_keyFrames[index] != null);
WritePostscript();
}
}
}
#endregion
}
}
| |
// 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.IO;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XmlDiff;
using CoreXml.Test.XLinq;
using Xunit;
namespace XDocumentTests.Streaming
{
public class XStreamingElementAPI
{
private XDocument _xDoc = null;
private XDocument _xmlDoc = null;
private XmlDiff _diff;
private bool _invokeStatus = false;
private bool _invokeError = false;
private Stream _sourceStream = null;
private Stream _targetStream = null;
public void GetFreshStream()
{
_sourceStream = new MemoryStream();
_targetStream = new MemoryStream();
}
public void ResetStreamPos()
{
if (_sourceStream.CanSeek)
{
_sourceStream.Position = 0;
}
if (_targetStream.CanSeek)
{
_targetStream.Position = 0;
}
}
private XmlDiff Diff
{
get
{
return _diff ?? (_diff = new XmlDiff());
}
}
[Fact]
public void XNameAsNullConstructor()
{
Assert.Throws<ArgumentNullException>(() => new XStreamingElement(null));
}
[Fact]
public void XNameAsEmptyStringConstructor()
{
Assert.Throws<ArgumentException>(() => new XStreamingElement(string.Empty));
Assert.Throws<XmlException>(() => new XStreamingElement(" "));
}
[Fact]
public void XNameConstructor()
{
XStreamingElement streamElement = new XStreamingElement("contact");
Assert.Equal("<contact />", streamElement.ToString());
}
[Fact]
public void XNameWithNamespaceConstructor()
{
XNamespace ns = @"http:\\www.contacts.com\";
XElement contact = new XElement(ns + "contact");
XStreamingElement streamElement = new XStreamingElement(ns + "contact");
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void XNameAndNullObjectConstructor()
{
XStreamingElement streamElement = new XStreamingElement("contact", null);
Assert.Equal("<contact />", streamElement.ToString());
}
[Fact]
public void XNameAndXElementObjectConstructor()
{
XElement contact = new XElement("contact", new XElement("phone", "925-555-0134"));
XStreamingElement streamElement = new XStreamingElement("contact", contact.Element("phone"));
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void XNameAndEmptyStringConstructor()
{
XElement contact = new XElement("contact", "");
XStreamingElement streamElement = new XStreamingElement("contact", "");
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void XDocTypeInXStreamingElement()
{
XDocumentType node = new XDocumentType(
"DOCTYPE",
"note",
"SYSTEM",
"<!ELEMENT note (to,from,heading,body)><!ELEMENT to (#PCDATA)><!ELEMENT from (#PCDATA)><!ELEMENT heading (#PCDATA)><!ELEMENT body (#PCDATA)>");
XStreamingElement streamElement = new XStreamingElement("Root", node);
Assert.Throws<InvalidOperationException>(() => streamElement.Save(new MemoryStream()));
}
[Fact]
public void XmlDeclInXStreamingElement()
{
XDeclaration node = new XDeclaration("1.0", "utf-8", "yes");
XElement element = new XElement("Root", node);
XStreamingElement streamElement = new XStreamingElement("Root", node);
GetFreshStream();
streamElement.Save(_sourceStream);
element.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void XCDataInXStreamingElement()
{
XCData node = new XCData("CDATA Text '%^$#@!&*()'");
XElement element = new XElement("Root", node);
XStreamingElement streamElement = new XStreamingElement("Root", node);
GetFreshStream();
streamElement.Save(_sourceStream);
element.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void XCommentInXStreamingElement()
{
XComment node = new XComment("This is a comment");
XElement element = new XElement("Root", node);
XStreamingElement streamElement = new XStreamingElement("Root", node);
GetFreshStream();
streamElement.Save(_sourceStream);
element.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void XDocInXStreamingElement()
{
InputSpace.Contacts(ref _xDoc, ref _xmlDoc);
XStreamingElement streamElement = new XStreamingElement("Root", _xDoc);
Assert.Throws<InvalidOperationException>(() => streamElement.Save(new MemoryStream()));
}
[Fact]
public void XNameAndCollectionObjectConstructor()
{
XElement contact = new XElement(
"contacts",
new XElement("contact1", "jane"),
new XElement("contact2", "john"));
List<Object> list = new List<Object>();
list.Add(contact.Element("contact1"));
list.Add(contact.Element("contact2"));
XStreamingElement streamElement = new XStreamingElement("contacts", list);
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void XNameAndObjectArrayConstructor()
{
XElement contact = new XElement(
"contact",
new XElement("name", "jane"),
new XElement("phone", new XAttribute("type", "home"), "925-555-0134"));
XStreamingElement streamElement = new XStreamingElement(
"contact",
new object[] { contact.Element("name"), contact.Element("phone") });
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void NamePropertyGet()
{
XStreamingElement streamElement = new XStreamingElement("contact");
Assert.Equal("contact", streamElement.Name);
}
[Fact]
public void NamePropertySet()
{
XStreamingElement streamElement = new XStreamingElement("ThisWillChangeToContact");
streamElement.Name = "contact";
Assert.Equal("contact", streamElement.Name.ToString());
}
[Fact]
public void NamePropertySetInvalid()
{
XStreamingElement streamElement = new XStreamingElement("ThisWillChangeToInValidName");
Assert.Throws<ArgumentNullException>(() => streamElement.Name = null);
}
[Fact]
public void XMLPropertyGet()
{
XElement contact = new XElement("contact", new XElement("phone", "925-555-0134"));
XStreamingElement streamElement = new XStreamingElement("contact", contact.Element("phone"));
Assert.Equal(contact.ToString(SaveOptions.None), streamElement.ToString(SaveOptions.None));
}
[Fact]
public void AddWithNull()
{
XStreamingElement streamElement = new XStreamingElement("contact");
streamElement.Add(null);
Assert.Equal("<contact />", streamElement.ToString());
}
[Theory]
[InlineData(9255550134)]
[InlineData("9255550134")]
[InlineData(9255550134.0)]
public void AddObject(object content)
{
XElement contact = new XElement("phone", content);
XStreamingElement streamElement = new XStreamingElement("phone");
streamElement.Add(content);
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void AddTimeSpanObject()
{
XElement contact = new XElement("Time", TimeSpan.FromMinutes(12));
XStreamingElement streamElement = new XStreamingElement("Time");
streamElement.Add(TimeSpan.FromMinutes(12));
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void AddAttribute()
{
XElement contact = new XElement("phone", new XAttribute("type", "home"), "925-555-0134");
XStreamingElement streamElement = new XStreamingElement("phone");
streamElement.Add(contact.Attribute("type"));
streamElement.Add("925-555-0134");
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
//An attribute cannot be written after content.
[Fact]
public void AddAttributeAfterContent()
{
XElement contact = new XElement("phone", new XAttribute("type", "home"), "925-555-0134");
XStreamingElement streamElement = new XStreamingElement("phone", "925-555-0134");
streamElement.Add(contact.Attribute("type"));
using (XmlWriter w = XmlWriter.Create(new MemoryStream(), null))
{
Assert.Throws<InvalidOperationException>(() => streamElement.WriteTo(w));
}
}
[Fact]
public void AddIEnumerableOfNulls()
{
XElement element = new XElement("root", GetNulls());
XStreamingElement streamElement = new XStreamingElement("root");
streamElement.Add(GetNulls());
GetFreshStream();
streamElement.Save(_sourceStream);
element.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
///<summary>
/// This function returns an IEnumeralb of nulls
///</summary>
public IEnumerable<XNode> GetNulls()
{
return Enumerable.Repeat((XNode)null, 1000);
}
[Fact]
public void AddIEnumerableOfXNodes()
{
XElement x = InputSpace.GetElement(100, 3);
XElement element = new XElement("root", x.Nodes());
XStreamingElement streamElement = new XStreamingElement("root");
streamElement.Add(x.Nodes());
GetFreshStream();
streamElement.Save(_sourceStream);
element.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void AddIEnumerableOfMixedNodes()
{
XElement element = new XElement("root", GetMixedNodes());
XStreamingElement streamElement = new XStreamingElement("root");
streamElement.Add(GetMixedNodes());
GetFreshStream();
streamElement.Save(_sourceStream);
element.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
///<summary>
/// This function returns mixed IEnumerable of XObjects with XAttributes first
///</summary>
public IEnumerable<XObject> GetMixedNodes()
{
InputSpace.Load("Word.xml", ref _xDoc, ref _xmlDoc);
foreach (XAttribute x in _xDoc.Root.Attributes())
yield return x;
foreach (XNode n in _xDoc.Root.DescendantNodes())
yield return n;
}
[Fact]
public void AddIEnumerableOfXNodesPlusString()
{
InputSpace.Contacts(ref _xDoc, ref _xmlDoc);
XElement element = new XElement("contacts", _xDoc.Root.DescendantNodes(), "This String");
XStreamingElement streamElement = new XStreamingElement("contacts");
streamElement.Add(_xDoc.Root.DescendantNodes(), "This String");
GetFreshStream();
streamElement.Save(_sourceStream);
element.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void AddIEnumerableOfXNodesPlusAttribute()
{
InputSpace.Contacts(ref _xDoc, ref _xmlDoc);
XAttribute xAttrib = new XAttribute("Attribute", "Value");
XElement element = new XElement("contacts", xAttrib, _xDoc.Root.DescendantNodes());
XStreamingElement streamElement = new XStreamingElement("contacts");
streamElement.Add(xAttrib, _xDoc.Root.DescendantNodes());
GetFreshStream();
streamElement.Save(_sourceStream);
element.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void SaveWithNull()
{
XStreamingElement streamElement = new XStreamingElement("phone", "925-555-0134");
Assert.Throws<ArgumentNullException>(() => streamElement.Save((XmlWriter)null));
}
[Fact]
public void SaveWithXmlTextWriter()
{
XElement contact = new XElement(
"contacts",
new XElement("contact", "jane"),
new XElement("contact", "john"));
XStreamingElement streamElement = new XStreamingElement("contacts", contact.Elements());
GetFreshStream();
TextWriter w = new StreamWriter(_sourceStream);
streamElement.Save(w);
w.Flush();
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void SaveTwice()
{
XElement contact = new XElement(
"contacts",
new XElement("contact", "jane"),
new XElement("contact", "john"));
XStreamingElement streamElement = new XStreamingElement("contacts", contact.Elements());
GetFreshStream();
streamElement.Save(_sourceStream);
_sourceStream.Position = 0;
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void WriteToWithNull()
{
XStreamingElement streamElement = new XStreamingElement("phone", "925-555-0134");
Assert.Throws<ArgumentNullException>(() => streamElement.WriteTo((XmlWriter)null));
}
[Fact]
public void ModifyOriginalElement()
{
XElement contact = new XElement(
"contact",
new XElement("name", "jane"),
new XElement("phone", new XAttribute("type", "home"), "925-555-0134"));
XStreamingElement streamElement = new XStreamingElement("contact", new object[] { contact.Elements() });
foreach (XElement x in contact.Elements())
{
x.Remove();
}
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void NestedXStreamingElement()
{
XElement name = new XElement("name", "jane");
XElement phone = new XElement("phone", new XAttribute("type", "home"), "925-555-0134");
XElement contact = new XElement("contact", name, new XElement("phones", phone));
XStreamingElement streamElement = new XStreamingElement(
"contact",
name,
new XStreamingElement("phones", phone));
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void NestedXStreamingElementPlusIEnumerable()
{
InputSpace.Contacts(ref _xDoc, ref _xmlDoc);
XElement element = new XElement("contacts", new XElement("Element", "Value"), _xDoc.Root.DescendantNodes());
XStreamingElement streamElement = new XStreamingElement("contacts");
streamElement.Add(new XStreamingElement("Element", "Value"), _xDoc.Root.DescendantNodes());
GetFreshStream();
streamElement.Save(_sourceStream);
element.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void IEnumerableLazinessTest1()
{
XElement name = new XElement("name", "jane");
XElement phone = new XElement("phone", new XAttribute("type", "home"), "925-555-0134");
XElement contact = new XElement("contact", name, phone);
IEnumerable<XElement> elements = contact.Elements();
name.Remove();
phone.Remove();
XStreamingElement streamElement = new XStreamingElement("contact", new object[] { elements });
GetFreshStream();
streamElement.Save(_sourceStream);
contact.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void IEnumerableLazinessTest2()
{
XElement name = new XElement("name", "jane");
XElement phone = new XElement("phone", new XAttribute("type", "home"), "925-555-0134");
XElement contact = new XElement("contact", name, phone);
// During debug this test will not work correctly since ToString() of
// streamElement gets called for displaying the value in debugger local window.
XStreamingElement streamElement = new XStreamingElement("contact", GetElements(contact));
GetFreshStream();
contact.Save(_targetStream);
_invokeStatus = true;
streamElement.Save(_sourceStream);
Assert.False(_invokeError, "IEnumerable walked before expected");
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
///<summary>
/// This function is used in above variation to make sure that the
/// IEnumerable is indeed walked lazily
///</summary>
public IEnumerable<XElement> GetElements(XElement element)
{
if (_invokeStatus == false)
{
_invokeError = true;
}
foreach (XElement x in element.Elements())
{
yield return x;
}
}
[Fact]
public void XStreamingElementInXElement()
{
XElement element = new XElement("contacts");
XStreamingElement streamElement = new XStreamingElement("contact", "SomeValue");
element.Add(streamElement);
XElement x = element.Element("contact");
GetFreshStream();
streamElement.Save(_sourceStream);
x.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
[Fact]
public void XStreamingElementInXDocument()
{
_xDoc = new XDocument();
XStreamingElement streamElement = new XStreamingElement("contacts", "SomeValue");
_xDoc.Add(streamElement);
GetFreshStream();
streamElement.Save(_sourceStream);
_xDoc.Save(_targetStream);
ResetStreamPos();
Assert.True(Diff.Compare(_sourceStream, _targetStream));
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Redis/
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot ([email protected])
//
// Copyright 2017 ServiceStack, Inc. All Rights Reserved.
//
// Licensed under the same terms of ServiceStack.
//
using System;
using System.Collections.Generic;
namespace ServiceStack.Redis
{
public interface IRedisNativeClient
: IDisposable
{
//Redis utility operations
Dictionary<string, string> Info { get; }
long Db { get; set; }
long DbSize { get; }
DateTime LastSave { get; }
void Save();
void BgSave();
void Shutdown();
void BgRewriteAof();
void Quit();
void FlushDb();
void FlushAll();
bool Ping();
string Echo(string text);
void SlaveOf(string hostname, int port);
void SlaveOfNoOne();
byte[][] ConfigGet(string pattern);
void ConfigSet(string item, byte[] value);
void ConfigResetStat();
void ConfigRewrite();
byte[][] Time();
void DebugSegfault();
byte[] Dump(string key);
byte[] Restore(string key, long expireMs, byte[] dumpValue);
void Migrate(string host, int port, string key, int destinationDb, long timeoutMs);
bool Move(string key, int db);
long ObjectIdleTime(string key);
RedisText Role();
RedisData RawCommand(params object[] cmdWithArgs);
RedisData RawCommand(params byte[][] cmdWithBinaryArgs);
string ClientGetName();
void ClientSetName(string client);
void ClientKill(string host);
long ClientKill(string addr = null, string id = null, string type = null, string skipMe = null);
byte[] ClientList();
void ClientPause(int timeOutMs);
//Common key-value Redis operations
byte[][] Keys(string pattern);
string Type(string key);
long Exists(string key);
long StrLen(string key);
void Set(string key, byte[] value);
void SetEx(string key, int expireInSeconds, byte[] value);
bool Persist(string key);
void PSetEx(string key, long expireInMs, byte[] value);
long SetNX(string key, byte[] value);
void MSet(byte[][] keys, byte[][] values);
void MSet(string[] keys, byte[][] values);
bool MSetNx(byte[][] keys, byte[][] values);
bool MSetNx(string[] keys, byte[][] values);
byte[] Get(string key);
byte[] GetSet(string key, byte[] value);
byte[][] MGet(params byte[][] keysAndArgs);
byte[][] MGet(params string[] keys);
long Del(string key);
long Del(params string[] keys);
long Incr(string key);
long IncrBy(string key, int incrBy);
double IncrByFloat(string key, double incrBy);
long Decr(string key);
long DecrBy(string key, int decrBy);
long Append(string key, byte[] value);
byte[] GetRange(string key, int fromIndex, int toIndex);
long SetRange(string key, int offset, byte[] value);
long GetBit(string key, int offset);
long SetBit(string key, int offset, int value);
string RandomKey();
void Rename(string oldKeyname, string newKeyname);
bool RenameNx(string oldKeyname, string newKeyname);
bool Expire(string key, int seconds);
bool PExpire(string key, long ttlMs);
bool ExpireAt(string key, long unixTime);
bool PExpireAt(string key, long unixTimeMs);
long Ttl(string key);
long PTtl(string key);
//Scan APIs
ScanResult Scan(ulong cursor, int count = 10, string match = null);
ScanResult SScan(string setId, ulong cursor, int count = 10, string match = null);
ScanResult ZScan(string setId, ulong cursor, int count = 10, string match = null);
ScanResult HScan(string hashId, ulong cursor, int count = 10, string match = null);
//Hyperlog
bool PfAdd(string key, params byte[][] elements);
long PfCount(string key);
void PfMerge(string toKeyId, params string[] fromKeys);
//Redis Sort operation (works on lists, sets or hashes)
byte[][] Sort(string listOrSetId, SortOptions sortOptions);
//Redis List operations
byte[][] LRange(string listId, int startingFrom, int endingAt);
long RPush(string listId, byte[] value);
long RPushX(string listId, byte[] value);
long LPush(string listId, byte[] value);
long LPushX(string listId, byte[] value);
void LTrim(string listId, int keepStartingFrom, int keepEndingAt);
long LRem(string listId, int removeNoOfMatches, byte[] value);
long LLen(string listId);
byte[] LIndex(string listId, int listIndex);
void LInsert(string listId, bool insertBefore, byte[] pivot, byte[] value);
void LSet(string listId, int listIndex, byte[] value);
byte[] LPop(string listId);
byte[] RPop(string listId);
byte[][] BLPop(string listId, int timeOutSecs);
byte[][] BLPop(string[] listIds, int timeOutSecs);
byte[] BLPopValue(string listId, int timeOutSecs);
byte[][] BLPopValue(string[] listIds, int timeOutSecs);
byte[][] BRPop(string listId, int timeOutSecs);
byte[][] BRPop(string[] listIds, int timeOutSecs);
byte[] RPopLPush(string fromListId, string toListId);
byte[] BRPopValue(string listId, int timeOutSecs);
byte[][] BRPopValue(string[] listIds, int timeOutSecs);
byte[] BRPopLPush(string fromListId, string toListId, int timeOutSecs);
//Redis Set operations
byte[][] SMembers(string setId);
long SAdd(string setId, byte[] value);
long SAdd(string setId, byte[][] value);
long SRem(string setId, byte[] value);
byte[] SPop(string setId);
byte[][] SPop(string setId, int count);
void SMove(string fromSetId, string toSetId, byte[] value);
long SCard(string setId);
long SIsMember(string setId, byte[] value);
byte[][] SInter(params string[] setIds);
void SInterStore(string intoSetId, params string[] setIds);
byte[][] SUnion(params string[] setIds);
void SUnionStore(string intoSetId, params string[] setIds);
byte[][] SDiff(string fromSetId, params string[] withSetIds);
void SDiffStore(string intoSetId, string fromSetId, params string[] withSetIds);
byte[] SRandMember(string setId);
//Redis Sorted Set operations
long ZAdd(string setId, double score, byte[] value);
long ZAdd(string setId, long score, byte[] value);
long ZRem(string setId, byte[] value);
long ZRem(string setId, byte[][] values);
double ZIncrBy(string setId, double incrBy, byte[] value);
double ZIncrBy(string setId, long incrBy, byte[] value);
long ZRank(string setId, byte[] value);
long ZRevRank(string setId, byte[] value);
byte[][] ZRange(string setId, int min, int max);
byte[][] ZRangeWithScores(string setId, int min, int max);
byte[][] ZRevRange(string setId, int min, int max);
byte[][] ZRevRangeWithScores(string setId, int min, int max);
byte[][] ZRangeByScore(string setId, double min, double max, int? skip, int? take);
byte[][] ZRangeByScore(string setId, long min, long max, int? skip, int? take);
byte[][] ZRangeByScoreWithScores(string setId, double min, double max, int? skip, int? take);
byte[][] ZRangeByScoreWithScores(string setId, long min, long max, int? skip, int? take);
byte[][] ZRevRangeByScore(string setId, double min, double max, int? skip, int? take);
byte[][] ZRevRangeByScore(string setId, long min, long max, int? skip, int? take);
byte[][] ZRevRangeByScoreWithScores(string setId, double min, double max, int? skip, int? take);
byte[][] ZRevRangeByScoreWithScores(string setId, long min, long max, int? skip, int? take);
long ZRemRangeByRank(string setId, int min, int max);
long ZRemRangeByScore(string setId, double fromScore, double toScore);
long ZRemRangeByScore(string setId, long fromScore, long toScore);
long ZCard(string setId);
double ZScore(string setId, byte[] value);
long ZUnionStore(string intoSetId, params string[] setIds);
long ZInterStore(string intoSetId, params string[] setIds);
byte[][] ZRangeByLex(string setId, string min, string max, int? skip = null, int? take = null);
long ZLexCount(string setId, string min, string max);
long ZRemRangeByLex(string setId, string min, string max);
//Redis Hash operations
long HSet(string hashId, byte[] key, byte[] value);
void HMSet(string hashId, byte[][] keys, byte[][] values);
long HSetNX(string hashId, byte[] key, byte[] value);
long HIncrby(string hashId, byte[] key, int incrementBy);
double HIncrbyFloat(string hashId, byte[] key, double incrementBy);
byte[] HGet(string hashId, byte[] key);
byte[][] HMGet(string hashId, params byte[][] keysAndArgs);
long HDel(string hashId, byte[] key);
long HExists(string hashId, byte[] key);
long HLen(string hashId);
byte[][] HKeys(string hashId);
byte[][] HVals(string hashId);
byte[][] HGetAll(string hashId);
//Redis GEO operations
long GeoAdd(string key, double longitude, double latitude, string member);
long GeoAdd(string key, params RedisGeo[] geoPoints);
double GeoDist(string key, string fromMember, string toMember, string unit = null);
string[] GeoHash(string key, params string[] members);
List<RedisGeo> GeoPos(string key, params string[] members);
List<RedisGeoResult> GeoRadius(string key, double longitude, double latitude, double radius, string unit,
bool withCoords = false, bool withDist = false, bool withHash = false, int? count = null, bool? asc = null);
List<RedisGeoResult> GeoRadiusByMember(string key, string member, double radius, string unit,
bool withCoords = false, bool withDist = false, bool withHash = false, int? count = null, bool? asc = null);
//Redis Pub/Sub operations
void Watch(params string[] keys);
void UnWatch();
long Publish(string toChannel, byte[] message);
byte[][] Subscribe(params string[] toChannels);
byte[][] UnSubscribe(params string[] toChannels);
byte[][] PSubscribe(params string[] toChannelsMatchingPatterns);
byte[][] PUnSubscribe(params string[] toChannelsMatchingPatterns);
byte[][] ReceiveMessages();
IRedisSubscription CreateSubscription();
//Redis LUA support
RedisData EvalCommand(string luaBody, int numberKeysInArgs, params byte[][] keys);
RedisData EvalShaCommand(string sha1, int numberKeysInArgs, params byte[][] keys);
byte[][] Eval(string luaBody, int numberOfKeys, params byte[][] keysAndArgs);
byte[][] EvalSha(string sha1, int numberOfKeys, params byte[][] keysAndArgs);
long EvalInt(string luaBody, int numberOfKeys, params byte[][] keysAndArgs);
long EvalShaInt(string sha1, int numberOfKeys, params byte[][] keysAndArgs);
string EvalStr(string luaBody, int numberOfKeys, params byte[][] keysAndArgs);
string EvalShaStr(string sha1, int numberOfKeys, params byte[][] keysAndArgs);
string CalculateSha1(string luaBody);
byte[][] ScriptExists(params byte[][] sha1Refs);
void ScriptFlush();
void ScriptKill();
byte[] ScriptLoad(string body);
}
}
| |
//////////////////////////////////////////////////////////////////////
// Part of the LLBLGen Pro Driver for Sybase ASA, used in the generated code.
// LLBLGen Pro is (c) 2002-2016 Solutions Design. All rights reserved.
// http://www.llblgen.com
//////////////////////////////////////////////////////////////////////
// This Driver's sourcecode is released under the following license:
// --------------------------------------------------------------------------------------------
//
// The MIT License(MIT)
//
// Copyright (c)2002-2016 Solutions Design. All rights reserved.
// http://www.llblgen.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.
//////////////////////////////////////////////////////////////////////
// Contributers to the code:
// - Frans Bouma [FB]
//////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Linq;
using SD.Tools.BCLExtensions.DataRelated;
using SD.Tools.BCLExtensions.CollectionsRelated;
using SD.LLBLGen.Pro.DBDriverCore;
using System.Collections.Generic;
using System.Data.Common;
namespace SD.LLBLGen.Pro.DBDrivers.SybaseAsa
{
/// <summary>
/// SybaseAsa specific implementation of DBSchemaRetriever
/// </summary>
public class SybaseAsaSchemaRetriever : DBSchemaRetriever
{
/// <summary>
/// CTor
/// </summary>
/// <param name="catalogRetriever">The catalog retriever.</param>
public SybaseAsaSchemaRetriever(SybaseAsaCatalogRetriever catalogRetriever) : base(catalogRetriever)
{
}
/// <summary>
/// Retrieves the table- and field meta data for the tables which names are in the passed in elementNames and which are in the schema specified.
/// </summary>
/// <param name="schemaToFill">The schema to fill.</param>
/// <param name="elementNames">The element names.</param>
/// <remarks>Implementers should add DBTable instances with the DBTableField instances to the DBSchema instance specified.
/// Default implementation is a no-op</remarks>
protected override void RetrieveTableAndFieldMetaData(DBSchema schemaToFill, IEnumerable<DBElementName> elementNames)
{
#region Description of queries used
//field query:
//select tc.*, d.domain_name, d.[precision], r.remarks from systabcol tc
//inner join sysdomain d on tc.domain_id = d.domain_id left join sysremark r on tc.object_id = r.object_id
//where table_id =
//(
// select table_id from systab where table_name =?
// and creator =
// (
// select user_id from sysuser where user_name='<schemaname>'
// )
//)
//
// uc query
//select i.index_name, tc.column_name
//from sysidx i inner join sysidxcol ic
//on i.table_id=ic.table_id
//and i.index_id=ic.index_id
//inner join systabcol tc
//on ic.table_id = tc.table_id
//and ic.column_id = tc.column_id
//where i.table_id in
//(
// select table_id from systab
// where creator =
// (
// select user_id from sysuser where user_name='<schemaname>'
// )
// and table_name=?
//)
// AND i.[unique] in (1, 2)
// AND i.index_category=3
#endregion
DbConnection connection = this.DriverToUse.CreateConnection();
DbCommand fieldCommand = this.DriverToUse.CreateCommand(connection, string.Format("select tc.*, d.domain_name, d.[precision], r.remarks from systabcol tc inner join sysdomain d on tc.domain_id = d.domain_id left join sysremark r on tc.object_id = r.object_id where table_id = (select table_id from systab where table_name = ? and creator = (select user_id from sysuser where user_name='{0}')) order by tc.column_id asc", schemaToFill.SchemaOwner));
DbParameter tableNameParameter = this.DriverToUse.CreateParameter(fieldCommand, "@table_name", string.Empty);
DbDataAdapter fieldAdapter = this.DriverToUse.CreateDataAdapter(fieldCommand);
DbCommand pkCommand = this.DriverToUse.CreateStoredProcCallCommand(connection, "sp_pkeys");
DbParameter pkRetrievalTableNameParameter = this.DriverToUse.CreateParameter(pkCommand, "@table_name", string.Empty);
this.DriverToUse.CreateParameter(pkCommand, "@table_owner", schemaToFill.SchemaOwner);
DbDataAdapter pkRetrievalAdapter = this.DriverToUse.CreateDataAdapter(pkCommand);
DbCommand ucCommand = this.DriverToUse.CreateCommand(connection, string.Format("select i.index_name, tc.column_name from sysidx i inner join sysidxcol ic on i.table_id=ic.table_id and i.index_id=ic.index_id inner join systabcol tc on ic.table_id = tc.table_id and ic.column_id = tc.column_id where i.table_id in ( select table_id from systab where creator = (select user_id from sysuser where user_name='{0}' ) and table_name=? ) AND i.[unique] in (1, 2) AND i.index_category=3", schemaToFill.SchemaOwner));
DbParameter ucRetrievalTableNameParameter = this.DriverToUse.CreateParameter(ucCommand, "@table_name", string.Empty);
DbDataAdapter ucRetrievalAdapter = this.DriverToUse.CreateDataAdapter(ucCommand);
DataTable ucFieldsInTable = new DataTable();
DataTable fieldsInTable = new DataTable();
DataTable pkFieldsInTable = new DataTable();
List<DBTable> tablesToRemove = new List<DBTable>();
try
{
connection.Open();
fieldCommand.Prepare();
pkCommand.Prepare();
ucCommand.Prepare();
foreach(DBElementName tableName in elementNames)
{
DBTable currentTable = new DBTable(schemaToFill, tableName);
schemaToFill.Tables.Add(currentTable);
tableNameParameter.Value = currentTable.Name;
// get the fields.
fieldsInTable.Clear();
fieldAdapter.Fill(fieldsInTable);
try
{
int ordinalPosition = 1;
var fields = from row in fieldsInTable.AsEnumerable()
let typeDefinition = CreateTypeDefinition(row, "domain_name", "width")
let defaultValue = row.Value<string>("default") ?? string.Empty
let isIdentity = ((defaultValue=="autoincrement") || (row.Value<int>("max_identity") > 0))
select new DBTableField(row.Value<string>("column_name"), typeDefinition, row.Value<string>("remarks") ?? string.Empty)
{
OrdinalPosition = ordinalPosition++,
DefaultValue = defaultValue,
IsIdentity = isIdentity,
IsComputed = (row.Value<string>("column_type") == "C"),
IsNullable = (row.Value<string>("nulls") == "Y"),
IsTimeStamp = (typeDefinition.DBType==(int)AsaDbTypes.TimeStamp),
ParentTable = currentTable
};
currentTable.Fields.AddRange(fields);
// get Primary Key fields for this table
pkRetrievalTableNameParameter.Value = currentTable.Name;
pkFieldsInTable.Clear();
pkRetrievalAdapter.Fill(pkFieldsInTable);
foreach(DataRow row in pkFieldsInTable.AsEnumerable())
{
string columnName = row.Value<string>("column_name");
DBTableField primaryKeyField = currentTable.FindFieldByName(columnName);
if(primaryKeyField != null)
{
primaryKeyField.IsPrimaryKey = true;
// PrimaryKeyConstraintName is not set, as ASA allows dropping and creating PKs without names. It's therefore not obtained (and not available either)
}
}
// get UC fields for this table
ucRetrievalTableNameParameter.Value = currentTable.Name;
ucFieldsInTable.Clear();
ucRetrievalAdapter.Fill(ucFieldsInTable);
var ucFieldsPerUc = from row in ucFieldsInTable.AsEnumerable()
group row by row.Value<string>("index_name") into g
select g;
foreach(IGrouping<string, DataRow> ucFields in ucFieldsPerUc)
{
DBUniqueConstraint currentUC = new DBUniqueConstraint(ucFields.Key) { AppliesToTable = currentTable };
bool addUc = true;
foreach(DataRow row in ucFields)
{
DBTableField currentField = currentTable.FindFieldByName(row.Value<string>("column_name"));
if(currentField == null)
{
continue;
}
currentUC.Fields.Add(currentField);
}
addUc &= (currentUC.Fields.Count > 0);
if(addUc)
{
currentTable.UniqueConstraints.Add(currentUC);
currentUC.AppliesToTable = currentTable;
}
}
}
catch( ApplicationException ex )
{
// non fatal error, remove the table, proceed
schemaToFill.LogError( ex, "Table '" + currentTable.Name + "' removed from list due to an internal exception in Field population: " + ex.Message, "SybaseAsaSchemaRetriever::RetrieveTableAndFieldMetaData" );
tablesToRemove.Add(currentTable);
}
catch( InvalidCastException ex )
{
// non fatal error, remove the table, proceed
schemaToFill.LogError(ex, "Table '" + currentTable.Name + "' removed from list due to cast exception in Field population.", "SybaseAsaSchemaRetriever::RetrieveTableAndFieldMetaData");
tablesToRemove.Add(currentTable);
}
}
}
finally
{
connection.SafeClose(true);
}
foreach(DBTable toRemove in tablesToRemove)
{
schemaToFill.Tables.Remove(toRemove);
}
}
/// <summary>
/// Retrieves the view- and field meta data for the views which names are in the passed in elementNames and which are in the schema specified.
/// </summary>
/// <param name="schemaToFill">The schema to fill.</param>
/// <param name="elementNames">The element names.</param>
/// <remarks>Implementers should add DBView instances with the DBViewField instances to the DBSchema instance specified.
/// Default implementation is a no-op</remarks>
protected override void RetrieveViewAndFieldMetaData(DBSchema schemaToFill, IEnumerable<DBElementName> elementNames)
{
#region Description of queries used
//field query:
//select tc.*, d.domain_name, d.[precision], r.remarks from systabcol tc
//inner join sysdomain d on tc.domain_id = d.domain_id left join sysremark r on tc.object_id = r.object_id
//where table_id =
//(
// select table_id from systab where table_name =?
// and creator =
// (
// select user_id from sysuser where user_name='<schemaname>'
// )
//)
#endregion
DbConnection connection = this.DriverToUse.CreateConnection();
DbCommand fieldCommand = this.DriverToUse.CreateCommand(connection, string.Format("select tc.*, d.domain_name, d.[precision], r.remarks from systabcol tc inner join sysdomain d on tc.domain_id = d.domain_id left join sysremark r on tc.object_id = r.object_id where table_id = (select table_id from systab where table_name = ? and creator = (select user_id from sysuser where user_name='{0}')) order by tc.column_id asc", schemaToFill.SchemaOwner));
DbParameter tableNameParameter = this.DriverToUse.CreateParameter(fieldCommand, "@table_name", string.Empty);
this.DriverToUse.CreateParameter(fieldCommand, "@table_owner", schemaToFill.SchemaOwner);
DbDataAdapter fieldAdapter = this.DriverToUse.CreateDataAdapter(fieldCommand);
DataTable fieldsInView = new DataTable();
List<DBView> viewsToRemove = new List<DBView>();
try
{
connection.Open();
fieldCommand.Prepare();
foreach(DBElementName viewName in elementNames)
{
DBView currentView = new DBView(schemaToFill, viewName);
schemaToFill.Views.Add(currentView);
tableNameParameter.Value = currentView.Name;
// get the fields.
fieldsInView.Clear();
fieldAdapter.Fill(fieldsInView);
try
{
int ordinalPosition = 1;
var fields = from row in fieldsInView.AsEnumerable()
let typeDefinition = CreateTypeDefinition(row, "domain_name", "width")
select new DBViewField(row.Value<string>("column_name"), typeDefinition, row.Value<string>("remarks") ?? string.Empty)
{
OrdinalPosition = ordinalPosition++,
IsNullable = (row.Value<string>("nulls") == "Y"),
ParentView = currentView
};
currentView.Fields.AddRange(fields);
}
catch(ApplicationException ex)
{
// non fatal error, remove the view, proceed
schemaToFill.LogError(ex, "View '" + currentView.Name + "' removed from list due to an internal exception in Field population: " + ex.Message, "SybaseAsaSchemaRetriever::RetrieveViewAndFieldMetaData");
viewsToRemove.Add(currentView);
}
catch(InvalidCastException ex)
{
// non fatal error, remove the view, proceed
schemaToFill.LogError(ex, "View '" + currentView.Name + "' removed from list due to cast exception in Field population.", "SybaseAsaSchemaRetriever::RetrieveViewAndFieldMetaData");
viewsToRemove.Add(currentView);
}
}
}
finally
{
connection.SafeClose(true);
}
foreach(DBView toRemove in viewsToRemove)
{
schemaToFill.Views.Remove(toRemove);
}
}
/// <summary>
/// Retrieves the stored procedure- and parameter meta data for the stored procedures which names are in the passed in elementNames and which are
/// in the schema specified.
/// </summary>
/// <param name="schemaToFill">The schema to fill.</param>
/// <param name="elementNames">The element names.</param>
/// <remarks>Implementers should add DBStoredProcedure instances with the DBStoredProcedureParameter instances to the DBSchema instance specified.
/// Default implementation is a no-op</remarks>
protected override void RetrieveStoredProcedureAndParameterMetaData(DBSchema schemaToFill, IEnumerable<DBElementName> elementNames)
{
#region Description of query used
//select pp.*, d.domain_name, d.[precision]
//from sysprocparm pp inner join sysprocedure p
//on pp.proc_id = p.proc_id
//inner join sysdomain d on pp.domain_id = d.domain_id
//where pp.parm_type in (0, 1)
//and p.proc_name = ?
//and p.creator = (select user_id from sysuser where user_name='<schemaname>')
//order by pp.parm_id ASC
#endregion
DbConnection connection = this.DriverToUse.CreateConnection();
DbCommand command = this.DriverToUse.CreateCommand(connection, string.Format("select pp.*, d.domain_name, d.[precision] from sysprocparm pp inner join sysprocedure p on pp.proc_id = p.proc_id inner join sysdomain d on pp.domain_id = d.domain_id where pp.parm_type in (0, 1) and p.proc_name = ? and p.creator = (select user_id from sysuser where user_name='{0}') order by pp.parm_id ASC", schemaToFill.SchemaOwner));
DbParameter procNameParameter = this.DriverToUse.CreateParameter(command, "@procedure_name", string.Empty);
DbDataAdapter adapter = this.DriverToUse.CreateDataAdapter(command);
DataTable parameterRows = new DataTable();
List<DBStoredProcedure> storedProceduresToRemove = new List<DBStoredProcedure>();
try
{
connection.Open();
command.Prepare();
List<string> storedProceduresAdded = new List<string>();
foreach(DBElementName procName in elementNames)
{
DBStoredProcedure storedProcedure = new DBStoredProcedure(schemaToFill, procName);
schemaToFill.StoredProcedures.Add(storedProcedure);
storedProceduresAdded.Add(storedProcedure.Name);
procNameParameter.Value = storedProcedure.Name;
parameterRows.Clear();
adapter.Fill(parameterRows);
try
{
var parameters = from row in parameterRows.AsEnumerable()
where new[] { 0, 4}.Contains(row.Value<int>("parm_type"))
let typeDefinition = CreateTypeDefinition(row, "domain_name", "width")
select new DBStoredProcedureParameter(row.Value<string>("parm_name"), typeDefinition, row.Value<string>("remarks") ?? string.Empty)
{
OrdinalPosition = row.Value<int>("parm_id"),
Direction = DetermineParameterDirection(row),
ParentStoredProcedure = storedProcedure
};
storedProcedure.Parameters.AddRange(p => p.OrdinalPosition, parameters);
}
catch(InvalidCastException ex)
{
// non fatal error, remove the stored procedure, proceed
schemaToFill.LogError(ex, "Stored procedure '" + storedProcedure.Name + "' removed from list due to cast exception in Parameter population.", "SybaseAsaSchemaRetriever::RetrieveStoredProcedureAndParameterMetaData");
storedProceduresToRemove.Add(storedProcedure);
}
catch(ApplicationException ex)
{
// non fatal error, remove the table, proceed
schemaToFill.LogError(ex, "Stored procedure '" + storedProcedure.Name + "' removed from list due to an internal exception in Field population: " + ex.Message, "SybaseAsaSchemaRetriever::RetrieveStoredProcedureAndParameterMetaData");
storedProceduresToRemove.Add(storedProcedure);
}
}
// now add the procs which names are in the list of elementNames which aren't added yet, as these procs don't have parameters.
var procsWithoutParameters = elementNames.Except(storedProceduresAdded.Select(s => new DBElementName(s)));
foreach(DBElementName procName in procsWithoutParameters)
{
schemaToFill.StoredProcedures.Add(new DBStoredProcedure(schemaToFill, procName));
}
}
finally
{
connection.SafeClose(true);
}
foreach(DBStoredProcedure toRemove in storedProceduresToRemove)
{
schemaToFill.StoredProcedures.Remove(toRemove);
}
}
/// <summary>
/// Determines the parameter direction.
/// </summary>
/// <param name="row">The row.</param>
/// <returns></returns>
private static ParameterDirection DetermineParameterDirection(DataRow row)
{
ParameterDirection toReturn;
bool input = (row.Value<string>("parm_mode_in") == "Y");
bool output = (row.Value<string>("parm_mode_out") == "Y");
bool returnValue = (row.Value<int>("parm_type") == 4);
if(returnValue)
{
toReturn = ParameterDirection.ReturnValue;
}
else
{
if(input)
{
toReturn = output ? ParameterDirection.InputOutput : ParameterDirection.Input;
}
else
{
toReturn = ParameterDirection.Output;
}
}
return toReturn;
}
/// <summary>
/// creates a new type definition from the data in the row specified.
/// </summary>
/// <param name="row">The row.</param>
/// <param name="columnNameTypeName">Name of the column name type.</param>
/// <param name="columnNameLength">Length of the column name.</param>
/// <returns>a filled DBTypeDefinition instance</returns>
private DBTypeDefinition CreateTypeDefinition(DataRow row, string columnNameTypeName, string columnNameLength)
{
DBTypeDefinition toReturn = new DBTypeDefinition();
string datatypeAsString = row.Value<string>(columnNameTypeName);
int length = row.Value<int>(columnNameLength);
int precision = row.Value<int?>("precision") ?? length;
int dbType = SybaseAsaDBDriver.ConvertStringToDBType(datatypeAsString, length);
switch((AsaDbTypes)dbType)
{
case AsaDbTypes.Image:
case AsaDbTypes.LongBinary:
case AsaDbTypes.LongNVarChar:
case AsaDbTypes.LongVarChar:
length = 0; // unlimited.
break;
}
int scale = row.Value<int?>("scale") ?? 0;
switch((AsaDbTypes)dbType)
{
case AsaDbTypes.Image:
case AsaDbTypes.LongBinary:
case AsaDbTypes.LongNVarChar:
case AsaDbTypes.LongVarChar:
length = 0; // unlimited.
break;
}
toReturn.SetDBType(dbType, this.DriverToUse, length, precision, scale);
return toReturn;
}
}
}
| |
// 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.Collections.Generic;
using System.Globalization;
using System.Runtime.Tests.Common;
using Xunit;
public static class UInt16Tests
{
[Fact]
public static void TestCtorEmpty()
{
ushort i = new ushort();
Assert.Equal(0, i);
}
[Fact]
public static void TestCtorValue()
{
ushort i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void TestMaxValue()
{
Assert.Equal(0xFFFF, ushort.MaxValue);
}
[Fact]
public static void TestMinValue()
{
Assert.Equal(0, ushort.MinValue);
}
[Theory]
[InlineData((ushort)234, 0)]
[InlineData(ushort.MinValue, 1)]
[InlineData((ushort)0, 1)]
[InlineData((ushort)45, 1)]
[InlineData((ushort)123, 1)]
[InlineData((ushort)456, -1)]
[InlineData(ushort.MaxValue, -1)]
public static void TestCompareTo(ushort value, int expected)
{
ushort i = 234;
int result = CompareHelper.NormalizeCompare(i.CompareTo(value));
Assert.Equal(expected, result);
}
[Theory]
[InlineData(null, 1)]
[InlineData((ushort)234, 0)]
[InlineData(ushort.MinValue, 1)]
[InlineData((ushort)0, 1)]
[InlineData((ushort)45, 1)]
[InlineData((ushort)123, 1)]
[InlineData((ushort)456, -1)]
[InlineData(ushort.MaxValue, -1)]
public static void TestCompareToObject(object obj, int expected)
{
IComparable comparable = (ushort)234;
int i = CompareHelper.NormalizeCompare(comparable.CompareTo(obj));
Assert.Equal(expected, i);
}
[Fact]
public static void TestCompareToObjectInvalid()
{
IComparable comparable = (ushort)234;
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); //Obj is not a ushort
}
[Theory]
[InlineData((ushort)789, true)]
[InlineData((ushort)0, false)]
public static void TestEqualsObject(object obj, bool expected)
{
ushort i = 789;
Assert.Equal(expected, i.Equals(obj));
}
[Theory]
[InlineData((ushort)789, true)]
[InlineData((ushort)0, false)]
public static void TestEquals(ushort i2, bool expected)
{
ushort i = 789;
Assert.Equal(expected, i.Equals(i2));
}
[Fact]
public static void TestGetHashCode()
{
ushort i1 = 123;
ushort i2 = 654;
Assert.NotEqual(0, i1.GetHashCode());
Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode());
}
[Fact]
public static void TestToString()
{
ushort i1 = 6310;
Assert.Equal("6310", i1.ToString());
}
[Fact]
public static void TestToStringFormatProvider()
{
var numberFormat = new NumberFormatInfo();
ushort i1 = 6310;
Assert.Equal("6310", i1.ToString(numberFormat));
}
[Fact]
public static void TestToStringFormat()
{
ushort i1 = 6310;
Assert.Equal("6310", i1.ToString("G"));
ushort i2 = 8249;
Assert.Equal("8249", i2.ToString("g"));
ushort i3 = 2468;
Assert.Equal(string.Format("{0:N}", 2468.00), i3.ToString("N"));
ushort i4 = 0x248;
Assert.Equal("248", i4.ToString("x"));
}
[Fact]
public static void TestToStringFormatFormatProvider()
{
var numberFormat = new NumberFormatInfo();
ushort i1 = 6310;
Assert.Equal("6310", i1.ToString("G", numberFormat));
ushort i2 = 8249;
Assert.Equal("8249", i2.ToString("g", numberFormat));
numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up
numberFormat.NumberGroupSeparator = "*";
numberFormat.NumberNegativePattern = 0;
ushort i3 = 2468;
Assert.Equal("2*468.00", i3.ToString("N", numberFormat));
}
public static IEnumerable<object[]> ParseValidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
yield return new object[] { "0", defaultStyle, defaultFormat, (ushort)0 };
yield return new object[] { "123", defaultStyle, defaultFormat, (ushort)123 };
yield return new object[] { " 123 ", defaultStyle, defaultFormat, (ushort)123 };
yield return new object[] { "65535", defaultStyle, defaultFormat, (ushort)65535 };
yield return new object[] { "12", NumberStyles.HexNumber, defaultFormat, (ushort)0x12 };
yield return new object[] { "1000", NumberStyles.AllowThousands, defaultFormat, (ushort)1000 };
yield return new object[] { "123", defaultStyle, emptyNfi, (ushort)123 };
yield return new object[] { "123", NumberStyles.Any, emptyNfi, (ushort)123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyNfi, (ushort)0x12 };
yield return new object[] { "abc", NumberStyles.HexNumber, emptyNfi, (ushort)0xabc };
yield return new object[] { "$1,000", NumberStyles.Currency, testNfi, (ushort)1000 };
}
public static IEnumerable<object[]> ParseInvalidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
testNfi.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, defaultFormat, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { " ", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { "abc", defaultStyle, defaultFormat, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, defaultFormat, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, defaultFormat, typeof(FormatException) }; // Parentheses
yield return new object[] { 100.ToString("C0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Thousands
yield return new object[] { 678.90.ToString("F2"), defaultStyle, defaultFormat, typeof(FormatException) }; //Decimal
yield return new object[] { "abc", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Negative hex value
yield return new object[] { " 123 ", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "678.90", defaultStyle, testNfi, typeof(FormatException) }; // Decimal
yield return new object[] { "-1", defaultStyle, defaultFormat, typeof(OverflowException) }; // < min value
yield return new object[] { "65536", defaultStyle, defaultFormat, typeof(OverflowException) }; // > max value
yield return new object[] { "(123)", NumberStyles.AllowParentheses, defaultFormat, typeof(OverflowException) }; // Parentheses = negative
}
[Theory, MemberData("ParseValidData")]
public static void TestParse(string value, NumberStyles style, NumberFormatInfo nfi, ushort expected)
{
ushort i;
//If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.Equal(true, ushort.TryParse(value, out i));
Assert.Equal(expected, i);
Assert.Equal(expected, ushort.Parse(value));
//If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (nfi != null)
{
Assert.Equal(expected, ushort.Parse(value, nfi));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.Equal(true, ushort.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
Assert.Equal(expected, i);
//If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (nfi == null)
{
Assert.Equal(expected, ushort.Parse(value, style));
}
Assert.Equal(expected, ushort.Parse(value, style, nfi ?? new NumberFormatInfo()));
}
[Theory, MemberData("ParseInvalidData")]
public static void TestParseInvalid(string value, NumberStyles style, NumberFormatInfo nfi, Type exceptionType)
{
ushort i;
//If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.Equal(false, ushort.TryParse(value, out i));
Assert.Equal(default(ushort), i);
Assert.Throws(exceptionType, () => ushort.Parse(value));
//If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (nfi != null)
{
Assert.Throws(exceptionType, () => ushort.Parse(value, nfi));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.Equal(false, ushort.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
Assert.Equal(default(ushort), i);
//If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (nfi == null)
{
Assert.Throws(exceptionType, () => ushort.Parse(value, style));
}
Assert.Throws(exceptionType, () => ushort.Parse(value, style, nfi ?? new NumberFormatInfo()));
}
}
| |
// Copyright (c) 2014 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Palaso.Extensions;
using Palaso.PlatformUtilities;
using Palaso.Reporting;
namespace Palaso.IO
{
public static class PathUtilities
{
// On Unix there are more characters valid in file names, but we
// want the result to be identical on both platforms, so we want
// to use the larger invalid Windows list for both platforms
public static char[] GetInvalidOSIndependentFileNameChars()
{
return new char[]
{
'\0',
'\u0001',
'\u0002',
'\u0003',
'\u0004',
'\u0005',
'\u0006',
'\a',
'\b',
'\t',
'\n',
'\v',
'\f',
'\r',
'\u000e',
'\u000f',
'\u0010',
'\u0011',
'\u0012',
'\u0013',
'\u0014',
'\u0015',
'\u0016',
'\u0017',
'\u0018',
'\u0019',
'\u001a',
'\u001b',
'\u001c',
'\u001d',
'\u001e',
'\u001f',
'"',
'<',
'>',
'|',
':',
'*',
'?',
'\\',
'/'
};
}
// map directory name to its disk device number (not used on Windows)
private static Dictionary<string,int> _deviceNumber = new Dictionary<string, int>();
public static int GetDeviceNumber(string filePath)
{
if (Palaso.PlatformUtilities.Platform.IsWindows)
{
var driveInfo = new DriveInfo(Path.GetPathRoot(filePath));
return driveInfo.Name.ToUpper()[0] - 'A' + 1;
}
// path can mean a file or a directory. Get the directory
// so that our device number cache can work better. (fewer
// unique directory names than filenames)
var pathToCheck = filePath;
if (File.Exists(pathToCheck))
pathToCheck = Path.GetDirectoryName(pathToCheck);
else if (!Directory.Exists(pathToCheck))
{
// Work up the path until a directory exists.
do
{
pathToCheck = Path.GetDirectoryName(pathToCheck);
}
while (!String.IsNullOrEmpty(pathToCheck) && !Directory.Exists(pathToCheck));
// If the whole path is invalid, give up.
if (String.IsNullOrEmpty(pathToCheck))
return -1;
}
int retval;
// Use cached value if we can to avoid process invocation.
if (_deviceNumber.TryGetValue(pathToCheck, out retval))
return retval;
using (var process = new Process())
{
var statFlags = Palaso.PlatformUtilities.Platform.IsMac ? "-f" : "-c";
process.StartInfo = new ProcessStartInfo
{
FileName = "stat",
Arguments = string.Format("{0} %d \"{1}\"", statFlags, pathToCheck),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
process.Start();
var output = process.StandardOutput.ReadToEnd();
// This process is frequently not exiting even after filling the output string
// with the desired information. So we'll wait a couple of seconds instead of
// waiting forever and just go on. If there's data to process, we'll use it.
// (2 seconds should be more than enough for that simple command to execute.
// "time statc -c %d "/tmp" reports 2ms of real time and 2ms of user time.)
// See https://jira.sil.org/browse/BL-771 for a bug report involving this code
// with a simple process.WaitForExit().
// This feels like a Mono bug of some sort, so feel free to regard this as a
// workaround hack.
process.WaitForExit(2000);
if (!String.IsNullOrWhiteSpace(output))
{
if (Int32.TryParse(output.Trim(), out retval))
{
_deviceNumber.Add(pathToCheck, retval);
return retval;
}
}
return -1;
}
}
public static bool PathsAreOnSameVolume(string firstPath, string secondPath)
{
if (string.IsNullOrEmpty(firstPath) || string.IsNullOrEmpty(secondPath))
return false;
return PathUtilities.GetDeviceNumber(firstPath) == PathUtilities.GetDeviceNumber(secondPath);
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
private struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
[MarshalAs(UnmanagedType.U4)]
public int wFunc;
public string pFrom;
public string pTo;
public short fFlags;
[MarshalAs(UnmanagedType.Bool)]
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
}
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
private const int FO_DELETE = 3;
private const int FOF_ALLOWUNDO = 0x40;
private const int FOF_NOCONFIRMATION = 0x10; // Don't prompt the user
private const int FOF_SIMPLEPROGRESS = 0x0100;
private static void WriteTrashInfoFile(string trashPath, string filePath, string trashedFile)
{
var trashInfo = Path.Combine(trashPath, "info", trashedFile + ".trashinfo");
var lines = new List<string>();
lines.Add("[Trash Info]");
lines.Add(string.Format("Path={0}", filePath));
lines.Add(string.Format("DeletionDate={0}",
DateTime.Now.ToString("yyyyMMddTHH:mm:ss", CultureInfo.InvariantCulture)));
File.WriteAllLines(trashInfo, lines);
}
/// <summary>
/// Delete a file or directory by moving it to the trash bin
/// </summary>
/// <param name="filePath">Full path of the file.</param>
/// <returns><c>true</c> if successfully deleted.</returns>
public static bool DeleteToRecycleBin(string filePath)
{
if (PlatformUtilities.Platform.IsWindows)
{
if (!File.Exists(filePath) && !Directory.Exists(filePath))
return false;
// alternative using visual basic dll:
// FileSystem.DeleteDirectory(item.FolderPath,UIOption.OnlyErrorDialogs), RecycleOption.SendToRecycleBin);
//moves it to the recyle bin
var shf = new SHFILEOPSTRUCT();
shf.wFunc = FO_DELETE;
shf.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
string pathWith2Nulls = filePath + "\0\0";
shf.pFrom = pathWith2Nulls;
SHFileOperation(ref shf);
return !shf.fAnyOperationsAborted;
}
// On Linux we'll have to move the file to $XDG_DATA_HOME/Trash/files and create
// a filename.trashinfo file in $XDG_DATA_HOME/Trash/info that contains the original
// filepath and the deletion date. See http://stackoverflow.com/a/20255190
// and http://freedesktop.org/wiki/Specifications/trash-spec/.
// Environment.SpecialFolder.LocalApplicationData corresponds to $XDG_DATA_HOME.
// move file or directory
if (Directory.Exists(filePath) || File.Exists(filePath))
{
var trashPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData), "Trash");
var trashedFileName = Path.GetRandomFileName();
if (!Directory.Exists(trashPath))
{
// in case the trash bin doesn't exist we create it. This can happen e.g.
// on the build machine
Directory.CreateDirectory(Path.Combine(trashPath, "files"));
Directory.CreateDirectory(Path.Combine(trashPath, "info"));
}
var recyclePath = Path.Combine(Path.Combine(trashPath, "files"), trashedFileName);
WriteTrashInfoFile(trashPath, filePath, trashedFileName);
// Directory.Move works for directories and files
DirectoryUtilities.MoveDirectorySafely(filePath, recyclePath);
return true;
}
return false;
}
[DllImport("shell32.dll", ExactSpelling = true)]
public static extern void ILFree(IntPtr pidlList);
[DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
public static extern IntPtr ILCreateFromPathW(string pszPath);
[DllImport("shell32.dll", ExactSpelling = true)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags);
public static void SelectItemInExplorerEx(string path)
{
var pidlList = ILCreateFromPathW(path);
if(pidlList == IntPtr.Zero)
throw new Exception(string.Format("ILCreateFromPathW({0}) failed", path));
try
{
Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
}
finally
{
ILFree(pidlList);
}
}
/// <summary>
/// On Windows this selects the file or directory in Windows Explorer; on Linux it selects the file
/// in the default file manager if that supports selecting a file and we know it,
/// otherwise we fall back to xdg-open and open the directory that contains that file.
/// </summary>
/// <param name="path">File or directory path.</param>
public static void SelectFileInExplorer(string path)
{
if (Platform.IsWindows)
{
//we need to use this becuase of a bug in windows that strips composed characters before trying to find the target path (http://stackoverflow.com/a/30405340/723299)
var pidlList = ILCreateFromPathW(path);
if(pidlList == IntPtr.Zero)
throw new Exception(string.Format("ILCreateFromPathW({0}) failed", path));
try
{
Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
}
finally
{
ILFree(pidlList);
}
}
else
{
var fileManager = DefaultFileManager;
string arguments;
switch (fileManager)
{
case "nautilus":
case "nemo":
arguments = string.Format("\"{0}\"", path);
break;
default:
fileManager = "xdg-open";
arguments = string.Format("\"{0}\"", Path.GetDirectoryName(path));
break;
}
Process.Start(fileManager, arguments);
}
}
/// <summary>
/// Opens the specified directory in the default file manager
/// </summary>
/// <param name="directory">Full path of the directory</param>
public static void OpenDirectoryInExplorer(string directory)
{
//Enhance: on Windows, use ShellExecuteExW instead, as it will probably be able to
//handle languages with combining characters (diactrics), whereas this explorer
//approach will fail (at least as of windows 8.1)
var fileManager = DefaultFileManager;
var arguments = "\"{0}\"";
// the value returned by GetDefaultFileManager() may include arguments
var firstSpace = fileManager.IndexOf(' ');
if (firstSpace > -1)
{
arguments = fileManager.Substring(firstSpace + 1) + " " + arguments;
fileManager = fileManager.Substring(0, firstSpace);
}
arguments = string.Format(arguments, directory);
Process.Start(new ProcessStartInfo()
{
FileName = fileManager,
Arguments = arguments,
UseShellExecute = false
});
}
/// <summary>
/// Opens the file in the application associated with the file type.
/// </summary>
/// <param name="filePath">Full path to the file</param>
public static void OpenFileInApplication(string filePath)
{
Process.Start(filePath);
}
private static string GetDefaultFileManager()
{
if (PlatformUtilities.Platform.IsWindows)
return "explorer.exe";
const string fallbackFileManager = "xdg-open";
using (var xdgmime = new Process())
{
bool processError = false;
xdgmime.RunProcess("xdg-mime", "query default inode/directory", exception => {
processError = true;
});
if (processError)
{
Logger.WriteMinorEvent("Error executing 'xdg-mime query default inode/directory'");
return fallbackFileManager;
}
string desktopFile = xdgmime.StandardOutput.ReadToEnd().TrimEnd(' ', '\n', '\r');
xdgmime.WaitForExit();
if (string.IsNullOrEmpty(desktopFile))
{
Logger.WriteMinorEvent("Didn't find default value for mime type inode/directory");
return fallbackFileManager;
}
// Look in /usr/share/applications for .desktop file
var desktopFilename = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"applications", desktopFile);
if (!File.Exists(desktopFilename))
{
// We didn't find the .desktop file yet, so check in ~/.local/share/applications
desktopFilename = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"applications", desktopFile);
}
if (!File.Exists(desktopFilename))
{
Logger.WriteMinorEvent("Can't find desktop file for {0}", desktopFile);
return fallbackFileManager;
}
using (var reader = File.OpenText(desktopFilename))
{
string line;
for (line = reader.ReadLine();
!line.StartsWith("Exec=", StringComparison.InvariantCultureIgnoreCase) && !reader.EndOfStream;
line = reader.ReadLine())
{
}
if (!line.StartsWith("Exec=", StringComparison.InvariantCultureIgnoreCase))
{
Logger.WriteMinorEvent("Can't find Exec line in {0}", desktopFile);
_defaultFileManager = string.Empty;
return _defaultFileManager;
}
var start = "Exec=".Length;
var argStart = line.IndexOf('%');
var cmdLine = argStart > 0 ? line.Substring(start, argStart - start) : line.Substring(start);
cmdLine = cmdLine.TrimEnd();
Logger.WriteMinorEvent("Detected default file manager as {0}", cmdLine);
return cmdLine;
}
}
}
private static string _defaultFileManager;
private static string DefaultFileManager
{
get
{
if (_defaultFileManager == null)
_defaultFileManager = GetDefaultFileManager();
return _defaultFileManager;
}
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Internal.Fakeables;
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public sealed class LogManager
{
private static readonly LogFactory factory = new LogFactory();
private static IAppDomain currentAppDomain;
private static ICollection<Assembly> _hiddenAssemblies;
private static readonly object lockObject = new object();
/// <summary>
/// Delegate used to set/get the culture in use.
/// </summary>
[Obsolete]
public delegate CultureInfo GetCultureInfo();
#if !SILVERLIGHT && !MONO
/// <summary>
/// Initializes static members of the LogManager class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static LogManager()
{
SetupTerminationEvents();
}
#endif
/// <summary>
/// Prevents a default instance of the LogManager class from being created.
/// </summary>
private LogManager()
{
}
/// <summary>
/// Gets the default <see cref="NLog.LogFactory" /> instance.
/// </summary>
internal static LogFactory LogFactory
{
get { return factory; }
}
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged
{
add { factory.ConfigurationChanged += value; }
remove { factory.ConfigurationChanged -= value; }
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded
{
add { factory.ConfigurationReloaded += value; }
remove { factory.ConfigurationReloaded -= value; }
}
#endif
/// <summary>
/// Gets or sets a value indicating whether NLog should throw exceptions.
/// By default exceptions are not thrown under any circumstances.
/// </summary>
public static bool ThrowExceptions
{
get { return factory.ThrowExceptions; }
set { factory.ThrowExceptions = value; }
}
/// <summary>
/// Gets or sets a value indicating whether <see cref="NLogConfigurationException"/> should be thrown.
/// </summary>
/// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>
/// This option is for backwards-compatiblity.
/// By default exceptions are not thrown under any circumstances.
///
/// </remarks>
public static bool? ThrowConfigExceptions
{
get { return factory.ThrowConfigExceptions; }
set { factory.ThrowConfigExceptions = value; }
}
/// <summary>
/// Gets or sets a value indicating whether Variables should be kept on configuration reload.
/// Default value - false.
/// </summary>
public static bool KeepVariablesOnReload
{
get { return factory.KeepVariablesOnReload; }
set { factory.KeepVariablesOnReload = value; }
}
internal static IAppDomain CurrentAppDomain
{
get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); }
set
{
#if !SILVERLIGHT && !MONO
if (currentAppDomain != null)
{
currentAppDomain.DomainUnload -= TurnOffLogging;
currentAppDomain.ProcessExit -= TurnOffLogging;
}
#endif
currentAppDomain = value;
}
}
/// <summary>
/// Gets or sets the current logging configuration.
/// <see cref="NLog.LogFactory.Configuration" />
/// </summary>
public static LoggingConfiguration Configuration
{
get { return factory.Configuration; }
set { factory.Configuration = value; }
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public static LogLevel GlobalThreshold
{
get { return factory.GlobalThreshold; }
set { factory.GlobalThreshold = value; }
}
/// <summary>
/// Gets or sets the default culture to use.
/// </summary>
[Obsolete("Use Configuration.DefaultCultureInfo property instead")]
public static GetCultureInfo DefaultCultureInfo
{
get { return () => factory.DefaultCultureInfo ?? CultureInfo.CurrentCulture; }
set { throw new NotSupportedException("Setting the DefaultCultureInfo delegate is no longer supported. Use the Configuration.DefaultCultureInfo property to change the default CultureInfo."); }
}
/// <summary>
/// Gets the logger with the name of the current class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
return factory.GetLogger(GetClassFullName());
}
internal static bool IsHiddenAssembly(Assembly assembly)
{
return _hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly);
}
/// <summary>
/// Adds the given assembly which will be skipped
/// when NLog is trying to find the calling method on stack trace.
/// </summary>
/// <param name="assembly">The assembly to skip.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AddHiddenAssembly(Assembly assembly)
{
lock (lockObject)
{
if (_hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly))
return;
_hiddenAssemblies = new HashSet<Assembly>(_hiddenAssemblies ?? Enumerable.Empty<Assembly>())
{
assembly
};
}
}
/// <summary>
/// Gets a custom logger with the name of the current class. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger(Type loggerType)
{
return factory.GetLogger(GetClassFullName(), loggerType);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger which discards all log messages.</returns>
[CLSCompliant(false)]
public static Logger CreateNullLogger()
{
return factory.CreateNullLogger();
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
[CLSCompliant(false)]
public static Logger GetLogger(string name)
{
return factory.GetLogger(name);
}
/// <summary>
/// Gets the specified named custom logger. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
/// <remarks>The generic way for this method is <see cref="NLog.LogFactory{loggerType}.GetLogger(string)"/></remarks>
[CLSCompliant(false)]
public static Logger GetLogger(string name, Type loggerType)
{
return factory.GetLogger(name, loggerType);
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger.
/// and recalculates their target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public static void ReconfigExistingLoggers()
{
factory.ReconfigExistingLoggers();
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public static void Flush()
{
factory.Flush();
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(TimeSpan timeout)
{
factory.Flush(timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(int timeoutMilliseconds)
{
factory.Flush(timeoutMilliseconds);
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public static void Flush(AsyncContinuation asyncContinuation)
{
factory.Flush(asyncContinuation);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
factory.Flush(asyncContinuation, timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
factory.Flush(asyncContinuation, timeoutMilliseconds);
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
/// <returns>An object that implements IDisposable whose Dispose() method reenables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
public static IDisposable DisableLogging()
{
return factory.SuspendLogging();
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static void EnableLogging()
{
factory.ResumeLogging();
}
/// <summary>
/// Checks if logging is currently enabled.
/// </summary>
/// <returns><see langword="true" /> if logging is currently enabled, <see langword="false"/>
/// otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static bool IsLoggingEnabled()
{
return factory.IsLoggingEnabled();
}
/// <summary>
/// Dispose all targets, and shutdown logging.
/// </summary>
public static void Shutdown()
{
if (Configuration != null && Configuration.AllTargets != null)
{
foreach (var target in Configuration.AllTargets)
{
if (target != null) target.Dispose();
}
}
}
#if !SILVERLIGHT && !MONO
private static void SetupTerminationEvents()
{
try
{
CurrentAppDomain.ProcessExit += TurnOffLogging;
CurrentAppDomain.DomainUnload += TurnOffLogging;
}
catch (Exception exception)
{
InternalLogger.Warn(exception, "Error setting up termination events.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
#endif
/// <summary>
/// Gets the fully qualified name of the class invoking the LogManager, including the
/// namespace but not the assembly.
/// </summary>
private static string GetClassFullName()
{
string className;
Type declaringType;
int framesToSkip = 2;
do
{
#if SILVERLIGHT
StackFrame frame = new StackTrace().GetFrame(framesToSkip);
#else
StackFrame frame = new StackFrame(framesToSkip, false);
#endif
MethodBase method = frame.GetMethod();
declaringType = method.DeclaringType;
if (declaringType == null)
{
className = method.Name;
break;
}
framesToSkip++;
className = declaringType.FullName;
} while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));
return className;
}
private static void TurnOffLogging(object sender, EventArgs args)
{
// Reset logging configuration to null; this causes old configuration (if any) to be
// closed.
InternalLogger.Info("Shutting down logging...");
if (Configuration != null)
{
Configuration = null;
factory.Dispose(); // Release event listeners
}
CurrentAppDomain = null; // No longer part of AppDomains
InternalLogger.Info("Logger has been shut down.");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.