context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Wraps a stream and provides convenient read functionality
** for strings and primitive types.
**
**
============================================================*/
using System;
using System.Runtime;
using System.Text;
using System.Globalization;
using System.Diagnostics;
using System.Security;
namespace System.IO
{
public class BinaryReader : IDisposable
{
private const int MaxCharBytesSize = 128;
private Stream _stream;
private byte[] _buffer;
private Decoder _decoder;
private byte[] _charBytes;
private char[] _singleChar;
private char[] _charBuffer;
private int _maxCharsSize; // From MaxCharBytesSize & Encoding
// Performance optimization for Read() w/ Unicode. Speeds us up by ~40%
private bool _2BytesPerChar;
private bool _isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf
private bool _leaveOpen;
public BinaryReader(Stream input) : this(input, Encoding.UTF8, false)
{
}
public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false)
{
}
public BinaryReader(Stream input, Encoding encoding, bool leaveOpen)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (!input.CanRead)
throw new ArgumentException(SR.Argument_StreamNotReadable);
_stream = input;
_decoder = encoding.GetDecoder();
_maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize);
int minBufferSize = encoding.GetMaxByteCount(1); // max bytes per one char
if (minBufferSize < 16)
minBufferSize = 16;
_buffer = new byte[minBufferSize];
// _charBuffer and _charBytes will be left null.
// For Encodings that always use 2 bytes per char (or more),
// special case them here to make Read() & Peek() faster.
_2BytesPerChar = encoding is UnicodeEncoding;
// check if BinaryReader is based on MemoryStream, and keep this for it's life
// we cannot use "as" operator, since derived classes are not allowed
_isMemoryStream = (_stream.GetType() == typeof(MemoryStream));
_leaveOpen = leaveOpen;
Debug.Assert(_decoder != null, "[BinaryReader.ctor]_decoder!=null");
}
public virtual Stream BaseStream
{
get
{
return _stream;
}
}
public virtual void Close()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Stream copyOfStream = _stream;
_stream = null;
if (copyOfStream != null && !_leaveOpen)
copyOfStream.Close();
}
_stream = null;
_buffer = null;
_decoder = null;
_charBytes = null;
_singleChar = null;
_charBuffer = null;
}
public void Dispose()
{
Dispose(true);
}
public virtual int PeekChar()
{
if (_stream == null) __Error.FileNotOpen();
if (!_stream.CanSeek)
return -1;
long origPos = _stream.Position;
int ch = Read();
_stream.Position = origPos;
return ch;
}
public virtual int Read()
{
if (_stream == null)
{
__Error.FileNotOpen();
}
return InternalReadOneChar();
}
public virtual bool ReadBoolean()
{
FillBuffer(1);
return (_buffer[0] != 0);
}
public virtual byte ReadByte()
{
// Inlined to avoid some method call overhead with FillBuffer.
if (_stream == null) __Error.FileNotOpen();
int b = _stream.ReadByte();
if (b == -1)
__Error.EndOfFile();
return (byte)b;
}
[CLSCompliant(false)]
public virtual sbyte ReadSByte()
{
FillBuffer(1);
return (sbyte)(_buffer[0]);
}
public virtual char ReadChar()
{
int value = Read();
if (value == -1)
{
__Error.EndOfFile();
}
return (char)value;
}
public virtual short ReadInt16()
{
FillBuffer(2);
return (short)(_buffer[0] | _buffer[1] << 8);
}
[CLSCompliant(false)]
public virtual ushort ReadUInt16()
{
FillBuffer(2);
return (ushort)(_buffer[0] | _buffer[1] << 8);
}
public virtual int ReadInt32()
{
if (_isMemoryStream)
{
if (_stream == null) __Error.FileNotOpen();
// read directly from MemoryStream buffer
MemoryStream mStream = _stream as MemoryStream;
Debug.Assert(mStream != null, "_stream as MemoryStream != null");
return mStream.InternalReadInt32();
}
else
{
FillBuffer(4);
return (int)(_buffer[0] | _buffer[1] << 8 | _buffer[2] << 16 | _buffer[3] << 24);
}
}
[CLSCompliant(false)]
public virtual uint ReadUInt32()
{
FillBuffer(4);
return (uint)(_buffer[0] | _buffer[1] << 8 | _buffer[2] << 16 | _buffer[3] << 24);
}
public virtual long ReadInt64()
{
FillBuffer(8);
uint lo = (uint)(_buffer[0] | _buffer[1] << 8 |
_buffer[2] << 16 | _buffer[3] << 24);
uint hi = (uint)(_buffer[4] | _buffer[5] << 8 |
_buffer[6] << 16 | _buffer[7] << 24);
return (long)((ulong)hi) << 32 | lo;
}
[CLSCompliant(false)]
public virtual ulong ReadUInt64()
{
FillBuffer(8);
uint lo = (uint)(_buffer[0] | _buffer[1] << 8 |
_buffer[2] << 16 | _buffer[3] << 24);
uint hi = (uint)(_buffer[4] | _buffer[5] << 8 |
_buffer[6] << 16 | _buffer[7] << 24);
return ((ulong)hi) << 32 | lo;
}
public virtual unsafe float ReadSingle()
{
FillBuffer(4);
uint tmpBuffer = (uint)(_buffer[0] | _buffer[1] << 8 | _buffer[2] << 16 | _buffer[3] << 24);
return *((float*)&tmpBuffer);
}
public virtual unsafe double ReadDouble()
{
FillBuffer(8);
uint lo = (uint)(_buffer[0] | _buffer[1] << 8 |
_buffer[2] << 16 | _buffer[3] << 24);
uint hi = (uint)(_buffer[4] | _buffer[5] << 8 |
_buffer[6] << 16 | _buffer[7] << 24);
ulong tmpBuffer = ((ulong)hi) << 32 | lo;
return *((double*)&tmpBuffer);
}
public virtual decimal ReadDecimal()
{
FillBuffer(16);
try
{
return Decimal.ToDecimal(_buffer);
}
catch (ArgumentException e)
{
// ReadDecimal cannot leak out ArgumentException
throw new IOException(SR.Arg_DecBitCtor, e);
}
}
public virtual String ReadString()
{
if (_stream == null)
__Error.FileNotOpen();
int currPos = 0;
int n;
int stringLength;
int readLength;
int charsRead;
// Length of the string in bytes, not chars
stringLength = Read7BitEncodedInt();
if (stringLength < 0)
{
throw new IOException(SR.Format(SR.IO_InvalidStringLen_Len, stringLength));
}
if (stringLength == 0)
{
return String.Empty;
}
if (_charBytes == null)
{
_charBytes = new byte[MaxCharBytesSize];
}
if (_charBuffer == null)
{
_charBuffer = new char[_maxCharsSize];
}
StringBuilder sb = null;
do
{
readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos);
n = _stream.Read(_charBytes, 0, readLength);
if (n == 0)
{
__Error.EndOfFile();
}
charsRead = _decoder.GetChars(_charBytes, 0, n, _charBuffer, 0);
if (currPos == 0 && n == stringLength)
return new String(_charBuffer, 0, charsRead);
if (sb == null)
sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller.
sb.Append(_charBuffer, 0, charsRead);
currPos += n;
} while (currPos < stringLength);
return StringBuilderCache.GetStringAndRelease(sb);
}
public virtual int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (_stream == null)
__Error.FileNotOpen();
// SafeCritical: index and count have already been verified to be a valid range for the buffer
return InternalReadChars(new Span<char>(buffer, index, count));
}
public virtual int Read(Span<char> buffer)
{
if (_stream == null)
__Error.FileNotOpen();
return InternalReadChars(buffer);
}
private int InternalReadChars(Span<char> buffer)
{
Debug.Assert(_stream != null);
int numBytes = 0;
int index = 0;
int charsRemaining = buffer.Length;
if (_charBytes == null)
{
_charBytes = new byte[MaxCharBytesSize];
}
while (charsRemaining > 0)
{
int charsRead = 0;
// We really want to know what the minimum number of bytes per char
// is for our encoding. Otherwise for UnicodeEncoding we'd have to
// do ~1+log(n) reads to read n characters.
numBytes = charsRemaining;
// special case for DecoderNLS subclasses when there is a hanging byte from the previous loop
DecoderNLS decoder = _decoder as DecoderNLS;
if (decoder != null && decoder.HasState && numBytes > 1)
{
numBytes -= 1;
}
if (_2BytesPerChar)
numBytes <<= 1;
if (numBytes > MaxCharBytesSize)
numBytes = MaxCharBytesSize;
int position = 0;
byte[] byteBuffer = null;
if (_isMemoryStream)
{
MemoryStream mStream = _stream as MemoryStream;
Debug.Assert(mStream != null, "_stream as MemoryStream != null");
position = mStream.InternalGetPosition();
numBytes = mStream.InternalEmulateRead(numBytes);
byteBuffer = mStream.InternalGetBuffer();
}
else
{
numBytes = _stream.Read(_charBytes, 0, numBytes);
byteBuffer = _charBytes;
}
if (numBytes == 0)
{
return (buffer.Length - charsRemaining);
}
Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
checked
{
if (position < 0 || numBytes < 0 || position > byteBuffer.Length - numBytes)
{
throw new ArgumentOutOfRangeException(nameof(numBytes));
}
if (index < 0 || charsRemaining < 0 || index > buffer.Length - charsRemaining)
{
throw new ArgumentOutOfRangeException(nameof(charsRemaining));
}
unsafe
{
fixed (byte* pBytes = byteBuffer)
fixed (char* pChars = &buffer.DangerousGetPinnableReference())
{
charsRead = _decoder.GetChars(pBytes + position, numBytes, pChars + index, charsRemaining, flush: false);
}
}
}
charsRemaining -= charsRead;
index += charsRead;
}
// this should never fail
Debug.Assert(charsRemaining >= 0, "We read too many characters.");
// we may have read fewer than the number of characters requested if end of stream reached
// or if the encoding makes the char count too big for the buffer (e.g. fallback sequence)
return (buffer.Length - charsRemaining);
}
private int InternalReadOneChar()
{
// I know having a separate InternalReadOneChar method seems a little
// redundant, but this makes a scenario like the security parser code
// 20% faster, in addition to the optimizations for UnicodeEncoding I
// put in InternalReadChars.
int charsRead = 0;
int numBytes = 0;
long posSav = posSav = 0;
if (_stream.CanSeek)
posSav = _stream.Position;
if (_charBytes == null)
{
_charBytes = new byte[MaxCharBytesSize];
}
if (_singleChar == null)
{
_singleChar = new char[1];
}
while (charsRead == 0)
{
// We really want to know what the minimum number of bytes per char
// is for our encoding. Otherwise for UnicodeEncoding we'd have to
// do ~1+log(n) reads to read n characters.
// Assume 1 byte can be 1 char unless _2BytesPerChar is true.
numBytes = _2BytesPerChar ? 2 : 1;
int r = _stream.ReadByte();
_charBytes[0] = (byte)r;
if (r == -1)
numBytes = 0;
if (numBytes == 2)
{
r = _stream.ReadByte();
_charBytes[1] = (byte)r;
if (r == -1)
numBytes = 1;
}
if (numBytes == 0)
{
// Console.WriteLine("Found no bytes. We're outta here.");
return -1;
}
Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
try
{
charsRead = _decoder.GetChars(_charBytes, 0, numBytes, _singleChar, 0);
}
catch
{
// Handle surrogate char
if (_stream.CanSeek)
_stream.Seek((posSav - _stream.Position), SeekOrigin.Current);
// else - we can't do much here
throw;
}
Debug.Assert(charsRead < 2, "InternalReadOneChar - assuming we only got 0 or 1 char, not 2!");
// Console.WriteLine("That became: " + charsRead + " characters.");
}
if (charsRead == 0)
return -1;
return _singleChar[0];
}
public virtual char[] ReadChars(int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_stream == null)
{
__Error.FileNotOpen();
}
if (count == 0)
{
return Array.Empty<Char>();
}
// SafeCritical: we own the chars buffer, and therefore can guarantee that the index and count are valid
char[] chars = new char[count];
int n = InternalReadChars(new Span<char>(chars));
if (n != count)
{
char[] copy = new char[n];
Buffer.InternalBlockCopy(chars, 0, copy, 0, 2 * n); // sizeof(char)
chars = copy;
}
return chars;
}
public virtual int Read(byte[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (_stream == null) __Error.FileNotOpen();
return _stream.Read(buffer, index, count);
}
public virtual int Read(Span<byte> buffer)
{
if (_stream == null)
__Error.FileNotOpen();
return _stream.Read(buffer);
}
public virtual byte[] ReadBytes(int count)
{
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (_stream == null) __Error.FileNotOpen();
if (count == 0)
{
return Array.Empty<Byte>();
}
byte[] result = new byte[count];
int numRead = 0;
do
{
int n = _stream.Read(result, numRead, count);
if (n == 0)
break;
numRead += n;
count -= n;
} while (count > 0);
if (numRead != result.Length)
{
// Trim array. This should happen on EOF & possibly net streams.
byte[] copy = new byte[numRead];
Buffer.InternalBlockCopy(result, 0, copy, 0, numRead);
result = copy;
}
return result;
}
protected virtual void FillBuffer(int numBytes)
{
if (_buffer != null && (numBytes < 0 || numBytes > _buffer.Length))
{
throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_BinaryReaderFillBuffer);
}
int bytesRead = 0;
int n = 0;
if (_stream == null) __Error.FileNotOpen();
// Need to find a good threshold for calling ReadByte() repeatedly
// vs. calling Read(byte[], int, int) for both buffered & unbuffered
// streams.
if (numBytes == 1)
{
n = _stream.ReadByte();
if (n == -1)
__Error.EndOfFile();
_buffer[0] = (byte)n;
return;
}
do
{
n = _stream.Read(_buffer, bytesRead, numBytes - bytesRead);
if (n == 0)
{
__Error.EndOfFile();
}
bytesRead += n;
} while (bytesRead < numBytes);
}
internal protected int Read7BitEncodedInt()
{
// Read out an Int32 7 bits at a time. The high bit
// of the byte when on means to continue reading more bytes.
int count = 0;
int shift = 0;
byte b;
do
{
// Check for a corrupted stream. Read a max of 5 bytes.
// In a future version, add a DataFormatException.
if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7
throw new FormatException(SR.Format_Bad7BitInt32);
// ReadByte handles end of stream cases for us.
b = ReadByte();
count |= (b & 0x7F) << shift;
shift += 7;
} while ((b & 0x80) != 0);
return count;
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Threading;
using System.Globalization;
namespace Protobuild
{
using System.Collections.Generic;
using System.IO.Compression;
public static class MainClass
{
public static void Main(string[] args)
{
// Ensure we always use the invariant culture in Protobuild.
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var kernel = new LightweightKernel();
kernel.BindCore();
kernel.BindBuildResources();
kernel.BindGeneration();
kernel.BindJSIL();
kernel.BindTargets();
kernel.BindFileFilter();
kernel.BindPackages();
var commandMappings = new Dictionary<string, ICommand>
{
{ "sync", kernel.Get<SyncCommand>() },
{ "resync", kernel.Get<ResyncCommand>() },
{ "generate", kernel.Get<GenerateCommand>() },
{ "clean", kernel.Get<CleanCommand>() },
{ "extract-xslt", kernel.Get<ExtractXSLTCommand>() },
{ "enable", kernel.Get<EnableServiceCommand>() },
{ "disable", kernel.Get<DisableServiceCommand>() },
{ "debug-service-resolution", kernel.Get<DebugServiceResolutionCommand>() },
{ "spec", kernel.Get<ServiceSpecificationCommand>() },
{ "query-features", kernel.Get<QueryFeaturesCommand>() },
{ "add", kernel.Get<AddPackageCommand>() },
{ "list", kernel.Get<ListPackagesCommand>() },
{ "install", kernel.Get<InstallPackageCommand>() },
{ "upgrade", kernel.Get<UpgradePackageCommand>() },
{ "upgrade-all", kernel.Get<UpgradeAllPackagesCommand>() },
{ "pack", kernel.Get<PackPackageCommand>() },
{ "format", kernel.Get<FormatPackageCommand>() },
{ "push", kernel.Get<PushPackageCommand>() },
{ "repush", kernel.Get<RepushPackageCommand>() },
{ "resolve", kernel.Get<ResolveCommand>() },
{ "no-resolve", kernel.Get<NoResolveCommand>() },
{ "redirect", kernel.Get<RedirectPackageCommand>() },
{ "swap-to-source", kernel.Get<SwapToSourceCommand>() },
{ "swap-to-binary", kernel.Get<SwapToBinaryCommand>() },
{ "start", kernel.Get<StartCommand>() },
{ "execute", kernel.Get<ExecuteCommand>() },
};
var execution = new Execution();
execution.CommandToExecute = kernel.Get<DefaultCommand>();
var options = new Options();
foreach (var kv in commandMappings)
{
var key = kv.Key;
var value = kv.Value;
if (value.GetArgCount() == 0)
{
options[key] = x => { value.Encounter(execution, x); };
}
else
{
options[key + "@" + value.GetArgCount()] = x => { value.Encounter(execution, x); };
}
}
Action<string[]> helpAction = x =>
{
PrintHelp(commandMappings);
ExecEnvironment.Exit(0);
};
options["help"] = helpAction;
options["?"] = helpAction;
if (ExecEnvironment.DoNotWrapExecutionInTry)
{
options.Parse(args);
}
else
{
try
{
options.Parse(args);
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
PrintHelp(commandMappings);
ExecEnvironment.Exit(1);
}
}
if (ExecEnvironment.DoNotWrapExecutionInTry)
{
var exitCode = execution.CommandToExecute.Execute(execution);
ExecEnvironment.Exit(exitCode);
}
else
{
try
{
var exitCode = execution.CommandToExecute.Execute(execution);
ExecEnvironment.Exit(exitCode);
}
catch (ExecEnvironment.SelfInvokeExitException)
{
throw;
}
catch (Exception ex)
{
Console.WriteLine(ex);
ExecEnvironment.Exit(1);
}
}
}
private static void PrintHelp(Dictionary<string, ICommand> commandMappings)
{
Console.WriteLine("Protobuild.exe [options]");
Console.WriteLine();
Console.WriteLine("By default Protobuild resynchronises or generates projects for");
Console.WriteLine("the current platform, depending on the module configuration.");
Console.WriteLine();
foreach (var kv in commandMappings)
{
var description = kv.Value.GetDescription();
description = description.Replace("\n", " ");
description = description.Replace("\r", "");
var lines = new List<string>();
var wordBuffer = string.Empty;
var lineBuffer = string.Empty;
var count = 0;
for (var i = 0; i < description.Length || wordBuffer.Length > 0; i++)
{
if (i < description.Length)
{
if (description[i] == ' ')
{
if (wordBuffer.Length > 0)
{
lineBuffer += wordBuffer + " ";
}
wordBuffer = string.Empty;
}
else
{
wordBuffer += description[i];
count++;
}
}
else
{
lineBuffer += wordBuffer + " ";
count++;
}
if (count >= 74)
{
lines.Add(lineBuffer);
lineBuffer = string.Empty;
count = 0;
}
}
if (count > 0)
{
lines.Add(lineBuffer);
lineBuffer = string.Empty;
}
var argDesc = string.Empty;
foreach (var arg in kv.Value.GetArgNames())
{
if (arg.EndsWith("?"))
{
argDesc += " [" + arg.TrimEnd('?') + "]";
}
else
{
argDesc += " " + arg;
}
}
Console.WriteLine(" -" + kv.Key + argDesc);
Console.WriteLine();
foreach (var line in lines)
{
Console.WriteLine(" " + line);
}
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using ZErrorCode = System.IO.Compression.ZLibNative.ErrorCode;
using ZFlushCode = System.IO.Compression.ZLibNative.FlushCode;
namespace System.IO.Compression
{
internal class DeflaterZLib : IDeflater
{
private ZLibNative.ZLibStreamHandle _zlibStream;
private GCHandle _inputBufferHandle;
private bool _isDisposed;
// Note, DeflateStream or the deflater do not try to be thread safe.
// The lock is just used to make writing to unmanaged structures atomic to make sure
// that they do not get inconsistent fields that may lead to an unmanaged memory violation.
// To prevent *managed* buffer corruption or other weird behaviour users need to synchronise
// on the stream explicitly.
private readonly object _syncLock = new object();
#region exposed members
internal DeflaterZLib()
: this(CompressionLevel.Optimal)
{
}
internal DeflaterZLib(CompressionLevel compressionLevel)
{
ZLibNative.CompressionLevel zlibCompressionLevel;
int memLevel;
switch (compressionLevel)
{
// See the note in ZLibNative.CompressionLevel for the recommended combinations.
case CompressionLevel.Optimal:
zlibCompressionLevel = ZLibNative.CompressionLevel.BestCompression;
memLevel = ZLibNative.Deflate_DefaultMemLevel;
break;
case CompressionLevel.Fastest:
zlibCompressionLevel = ZLibNative.CompressionLevel.BestSpeed;
memLevel = ZLibNative.Deflate_DefaultMemLevel;
break;
case CompressionLevel.NoCompression:
zlibCompressionLevel = ZLibNative.CompressionLevel.NoCompression;
memLevel = ZLibNative.Deflate_NoCompressionMemLevel;
break;
default:
throw new ArgumentOutOfRangeException("compressionLevel");
}
int windowBits = ZLibNative.Deflate_DefaultWindowBits;
ZLibNative.CompressionStrategy strategy = ZLibNative.CompressionStrategy.DefaultStrategy;
DeflateInit(zlibCompressionLevel, windowBits, memLevel, strategy);
}
~DeflaterZLib()
{
Dispose(false);
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
_zlibStream.Dispose();
if (_inputBufferHandle.IsAllocated)
DeallocateInputBufferHandle();
_isDisposed = true;
}
}
public bool NeedsInput()
{
return 0 == _zlibStream.AvailIn;
}
void IDeflater.SetInput(byte[] inputBuffer, int startIndex, int count)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(null != inputBuffer);
Debug.Assert(startIndex >= 0 && count >= 0 && count + startIndex <= inputBuffer.Length);
Debug.Assert(!_inputBufferHandle.IsAllocated);
if (0 == count)
return;
lock (_syncLock)
{
_inputBufferHandle = GCHandle.Alloc(inputBuffer, GCHandleType.Pinned);
_zlibStream.NextIn = _inputBufferHandle.AddrOfPinnedObject() + startIndex;
_zlibStream.AvailIn = (uint)count;
}
}
int IDeflater.GetDeflateOutput(byte[] outputBuffer)
{
Contract.Ensures(Contract.Result<int>() >= 0 && Contract.Result<int>() <= outputBuffer.Length);
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input");
Debug.Assert(_inputBufferHandle.IsAllocated);
try
{
int bytesRead;
ReadDeflateOutput(outputBuffer, ZFlushCode.NoFlush, out bytesRead);
return bytesRead;
}
finally
{
// Before returning, make sure to release input buffer if necesary:
if (0 == _zlibStream.AvailIn && _inputBufferHandle.IsAllocated)
DeallocateInputBufferHandle();
}
}
private unsafe ZErrorCode ReadDeflateOutput(byte[] outputBuffer, ZFlushCode flushCode, out int bytesRead)
{
lock (_syncLock)
{
fixed (byte* bufPtr = outputBuffer)
{
_zlibStream.NextOut = (IntPtr)bufPtr;
_zlibStream.AvailOut = (uint)outputBuffer.Length;
ZErrorCode errC = Deflate(flushCode);
bytesRead = outputBuffer.Length - (int)_zlibStream.AvailOut;
return errC;
}
}
}
bool IDeflater.Finish(byte[] outputBuffer, out int bytesRead)
{
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(!_inputBufferHandle.IsAllocated);
// Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
// If there is still input left we should never be getting here; instead we
// should be calling GetDeflateOutput.
ZErrorCode errC = ReadDeflateOutput(outputBuffer, ZFlushCode.Finish, out bytesRead);
return errC == ZErrorCode.StreamEnd;
}
#endregion // exposed functions
#region helpers & native call wrappers
private void DeallocateInputBufferHandle()
{
Debug.Assert(_inputBufferHandle.IsAllocated);
lock (_syncLock)
{
_zlibStream.AvailIn = 0;
_zlibStream.NextIn = ZLibNative.ZNullPtr;
_inputBufferHandle.Free();
}
}
[SecuritySafeCritical]
private void DeflateInit(ZLibNative.CompressionLevel compressionLevel, int windowBits, int memLevel,
ZLibNative.CompressionStrategy strategy)
{
ZErrorCode errC;
try
{
errC = ZLibNative.CreateZLibStreamForDeflate(out _zlibStream, compressionLevel,
windowBits, memLevel, strategy);
}
catch (Exception cause)
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZErrorCode.Ok:
return;
case ZErrorCode.MemError:
throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
case ZErrorCode.VersionError:
throw new ZLibException(SR.ZLibErrorVersionMismatch, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
case ZErrorCode.StreamError:
throw new ZLibException(SR.ZLibErrorIncorrectInitParameters, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
}
}
[SecuritySafeCritical]
private ZErrorCode Deflate(ZFlushCode flushCode)
{
ZErrorCode errC;
try
{
errC = _zlibStream.Deflate(flushCode);
}
catch (Exception cause)
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZErrorCode.Ok:
case ZErrorCode.StreamEnd:
return errC;
case ZErrorCode.BufError:
return errC; // This is a recoverable error
case ZErrorCode.StreamError:
throw new ZLibException(SR.ZLibErrorInconsistentStream, "deflate", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "deflate", (int)errC, _zlibStream.GetErrorMessage());
}
}
#endregion // helpers & native call wrappers
} // internal class DeflaterZLib
} // namespace System.IO.Compression
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.events._Listener
{
public sealed class Listener_Impl_
{
static Listener_Impl_()
{
#line 50 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::pony.events._Listener.Listener_Impl_.flist = new global::haxe.ds.IntMap<object>();
}
public static global::haxe.ds.IntMap<object> flist;
public static object _new(object f, global::haxe.lang.Null<bool> @event, global::haxe.lang.Null<bool> ignoreReturn, global::haxe.lang.Null<int> count)
{
unchecked
{
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int __temp_count106 = ( (global::haxe.lang.Runtime.eq((count).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (-1) )) : (count.@value) );
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
bool __temp_ignoreReturn105 = ( (global::haxe.lang.Runtime.eq((ignoreReturn).toDynamic(), (default(global::haxe.lang.Null<bool>)).toDynamic())) ? (((bool) (true) )) : (ignoreReturn.@value) );
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
bool __temp_event104 = ( (global::haxe.lang.Runtime.eq((@event).toDynamic(), (default(global::haxe.lang.Null<bool>)).toDynamic())) ? (((bool) (false) )) : (@event.@value) );
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object this1 = default(object);
{
#line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object __temp_getvar185 = f;
#line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
double __temp_ret186 = ((double) (global::haxe.lang.Runtime.getField_f(__temp_getvar185, "used", 1303220797, true)) );
#line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::haxe.lang.Runtime.setField(__temp_getvar185, "used", 1303220797, ( __temp_ret186 + 1.0 ));
#line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
double __temp_expr443 = __temp_ret186;
}
this1 = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{102, 98429794, 373703110, 1247723251, 1975830554}), new global::Array<object>(new object[]{f, __temp_ignoreReturn105, true, default(global::pony.events.Event), __temp_event104}), new global::Array<int>(new int[]{1248019663, 1303220797}), new global::Array<double>(new double[]{((double) (__temp_count106) ), ((double) (0) )}));
#line 53 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return this1;
}
#line default
}
public static object fromEFunction(global::haxe.lang.Function f)
{
unchecked
{
#line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return global::pony.events._Listener.Listener_Impl_._fromFunction(global::pony._Function.Function_Impl_.@from(f, 1), true);
}
#line default
}
public static object fromFunction(object f)
{
unchecked
{
#line 62 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
#line default
}
public static object fromSignal(global::pony.events.Signal s)
{
unchecked
{
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::Array<object> @event = new global::Array<object>(new object[]{new global::pony.events.Event(((global::Array) (default(global::Array)) ), ((object) (s.target) ), ((global::pony.events.Event) (default(global::pony.events.Event)) ))});
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::Array<object> _g = new global::Array<object>(new object[]{s});
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object f = global::pony._Function.Function_Impl_.@from(new global::pony.events._Listener.Listener_Impl__fromSignal_65__Fun(((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (_g) ))) ), ((global::Array<object>) (global::Array<object>.__hx_cast<object>(((global::Array) (@event) ))) )), 0);
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return global::pony.events._Listener.Listener_Impl_._fromFunction(f, false);
}
}
}
#line default
}
public static object _fromFunction(object f, bool ev)
{
unchecked
{
#line 68 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
if (global::pony.events._Listener.Listener_Impl_.flist.exists(((int) (global::haxe.lang.Runtime.getField_f(f, "id", 23515, true)) )))
{
return (global::pony.events._Listener.Listener_Impl_.flist.@get(((int) (global::haxe.lang.Runtime.getField_f(f, "id", 23515, true)) ))).toDynamic();
}
else
{
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object o = default(object);
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int count = -1;
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
bool ignoreReturn = true;
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object this1 = default(object);
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object __temp_getvar187 = f;
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
double __temp_ret188 = ((double) (global::haxe.lang.Runtime.getField_f(__temp_getvar187, "used", 1303220797, true)) );
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::haxe.lang.Runtime.setField(__temp_getvar187, "used", 1303220797, ( __temp_ret188 + 1.0 ));
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
double __temp_expr444 = __temp_ret188;
}
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
this1 = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{102, 98429794, 373703110, 1247723251, 1975830554}), new global::Array<object>(new object[]{f, ignoreReturn, true, default(global::pony.events.Event), ev}), new global::Array<int>(new int[]{1248019663, 1303220797}), new global::Array<double>(new double[]{((double) (count) ), ((double) (0) )}));
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
o = this1;
}
global::pony.events._Listener.Listener_Impl_.flist.@set(((int) (global::haxe.lang.Runtime.getField_f(f, "id", 23515, true)) ), o);
return o;
}
}
#line default
}
public static int _get_count(object this1)
{
unchecked
{
#line 77 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return ((int) (global::haxe.lang.Runtime.getField_f(this1, "count", 1248019663, true)) );
}
#line default
}
public static bool call(object this1, global::pony.events.Event @event)
{
unchecked
{
#line 80 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
if (( ! (((bool) (global::haxe.lang.Runtime.getField(this1, "active", 373703110, true)) )) ))
{
#line 80 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return true;
}
{
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object __temp_getvar189 = this1;
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int __temp_ret190 = ((int) (global::haxe.lang.Runtime.getField_f(__temp_getvar189, "count", 1248019663, true)) );
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::haxe.lang.Runtime.setField_f(__temp_getvar189, "count", 1248019663, ((double) (( __temp_ret190 - 1 )) ));
#line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int __temp_expr445 = __temp_ret190;
}
@event.currentListener = this1;
bool r = true;
if (((bool) (global::haxe.lang.Runtime.getField(this1, "event", 1975830554, true)) ))
{
object __temp_stmt449 = default(object);
#line 85 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 85 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::Array args = new global::Array<object>(new object[]{@event});
#line 85 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object this2 = global::haxe.lang.Runtime.getField(this1, "f", 102, true);
#line 85 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
if (( args == default(global::Array) ))
{
#line 85 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
args = new global::Array<object>(new object[]{});
}
#line 85 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
__temp_stmt449 = global::Reflect.callMethod(default(object), global::haxe.lang.Runtime.getField(this2, "f", 102, true), ((global::Array) (global::haxe.lang.Runtime.callField(((global::Array) (global::haxe.lang.Runtime.getField(this2, "args", 1081380189, true)) ), "concat", 1204816148, new global::Array<object>(new object[]{args}))) ));
}
#line 85 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
bool __temp_stmt448 = global::haxe.lang.Runtime.eq(__temp_stmt449, false);
#line 85 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
if (__temp_stmt448)
{
#line 85 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
r = false;
}
}
else
{
#line 87 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::Array args1 = ((global::Array) (global::haxe.lang.Runtime.callField(@event.args, "copy", 1103412149, default(global::Array))) );
global::haxe.lang.Runtime.callField(args1, "push", 1247875546, new global::Array<object>(new object[]{@event.target}));
global::haxe.lang.Runtime.callField(args1, "push", 1247875546, new global::Array<object>(new object[]{@event}));
object __temp_stmt447 = default(object);
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::Array args2 = ((global::Array) (global::haxe.lang.Runtime.callField(args1, "slice", 2127021138, new global::Array<object>(new object[]{0, ((int) (global::haxe.lang.Runtime.getField_f(global::haxe.lang.Runtime.getField(this1, "f", 102, true), "count", 1248019663, true)) )}))) );
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object this3 = global::haxe.lang.Runtime.getField(this1, "f", 102, true);
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
if (( args2 == default(global::Array) ))
{
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
args2 = new global::Array<object>(new object[]{});
}
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
__temp_stmt447 = global::Reflect.callMethod(default(object), global::haxe.lang.Runtime.getField(this3, "f", 102, true), ((global::Array) (global::haxe.lang.Runtime.callField(((global::Array) (global::haxe.lang.Runtime.getField(this3, "args", 1081380189, true)) ), "concat", 1204816148, new global::Array<object>(new object[]{args2}))) ));
}
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
bool __temp_stmt446 = global::haxe.lang.Runtime.eq(__temp_stmt447, false);
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
if (__temp_stmt446)
{
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
r = false;
}
}
#line 92 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::haxe.lang.Runtime.setField(this1, "prev", 1247723251, @event);
if (((bool) (global::haxe.lang.Runtime.getField(this1, "ignoreReturn", 98429794, true)) ))
{
#line 93 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return true;
}
else
{
#line 93 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return r;
}
}
#line default
}
public static object setCount(object this1, int count)
{
unchecked
{
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object f = global::haxe.lang.Runtime.getField(this1, "f", 102, true);
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object this2 = default(object);
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object __temp_getvar191 = f;
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
double __temp_ret192 = ((double) (global::haxe.lang.Runtime.getField_f(__temp_getvar191, "used", 1303220797, true)) );
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::haxe.lang.Runtime.setField(__temp_getvar191, "used", 1303220797, ( __temp_ret192 + 1.0 ));
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
double __temp_expr452 = __temp_ret192;
}
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
bool __temp_odecl450 = ((bool) (global::haxe.lang.Runtime.getField(this1, "event", 1975830554, true)) );
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
bool __temp_odecl451 = ((bool) (global::haxe.lang.Runtime.getField(this1, "ignoreReturn", 98429794, true)) );
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
this2 = new global::haxe.lang.DynamicObject(new global::Array<int>(new int[]{102, 98429794, 373703110, 1247723251, 1975830554}), new global::Array<object>(new object[]{f, __temp_odecl451, true, default(global::pony.events.Event), __temp_odecl450}), new global::Array<int>(new int[]{1248019663, 1303220797}), new global::Array<double>(new double[]{((double) (count) ), ((double) (0) )}));
}
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return this2;
}
}
#line default
}
public static void _use(object this1)
{
unchecked
{
#line 100 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 100 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object __temp_getvar193 = this1;
#line 100 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int __temp_ret194 = ((int) (global::haxe.lang.Runtime.getField_f(__temp_getvar193, "used", 1303220797, true)) );
#line 100 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::haxe.lang.Runtime.setField_f(__temp_getvar193, "used", 1303220797, ((double) (( __temp_ret194 + 1 )) ));
#line 100 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int __temp_expr453 = __temp_ret194;
}
}
#line default
}
public static void unuse(object this1)
{
unchecked
{
#line 103 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 103 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object __temp_getvar195 = this1;
#line 103 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int __temp_ret196 = ((int) (global::haxe.lang.Runtime.getField_f(__temp_getvar195, "used", 1303220797, true)) );
#line 103 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::haxe.lang.Runtime.setField_f(__temp_getvar195, "used", 1303220797, ((double) (( __temp_ret196 - 1 )) ));
#line 103 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int __temp_expr454 = __temp_ret196;
}
if (( ((int) (global::haxe.lang.Runtime.getField_f(this1, "used", 1303220797, true)) ) == 0 ))
{
global::pony.events._Listener.Listener_Impl_.flist.@remove(((int) (global::haxe.lang.Runtime.getField_f(global::haxe.lang.Runtime.getField(this1, "f", 102, true), "id", 23515, true)) ));
{
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
{
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object __temp_getvar197 = global::haxe.lang.Runtime.getField(this1, "f", 102, true);
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int __temp_ret198 = ((int) (global::haxe.lang.Runtime.getField_f(__temp_getvar197, "used", 1303220797, true)) );
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::haxe.lang.Runtime.setField_f(__temp_getvar197, "used", 1303220797, ((double) (( __temp_ret198 - 1 )) ));
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int __temp_expr455 = __temp_ret198;
}
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
if (( global::haxe.lang.Runtime.compare(((int) (global::haxe.lang.Runtime.getField_f(global::haxe.lang.Runtime.getField(this1, "f", 102, true), "used", 1303220797, true)) ), 0) <= 0 ))
{
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
if (( global::haxe.lang.Runtime.getField(global::haxe.lang.Runtime.getField(this1, "f", 102, true), "f", 102, true) is global::haxe.lang.Closure ))
{
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::pony._Function.Function_Impl_.cslist.@remove(global::pony._Function.Function_Impl_.buildCSHash(global::haxe.lang.Runtime.getField(global::haxe.lang.Runtime.getField(this1, "f", 102, true), "f", 102, true)));
}
else
{
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::pony._Function.Function_Impl_.list.@remove(global::pony._Function.Function_Impl_.buildCSHash(global::haxe.lang.Runtime.getField(global::haxe.lang.Runtime.getField(this1, "f", 102, true), "f", 102, true)));
}
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::haxe.lang.Runtime.setField(this1, "f", 102, default(object));
#line 106 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
global::pony._Function.Function_Impl_.unusedCount--;
}
}
}
}
#line default
}
public static int _get_used(object this1)
{
unchecked
{
#line 110 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return ((int) (global::haxe.lang.Runtime.getField_f(this1, "used", 1303220797, true)) );
}
#line default
}
public static int unusedCount()
{
unchecked
{
#line 113 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
int c = 0;
{
#line 114 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object __temp_iterator199 = global::pony.events._Listener.Listener_Impl_.flist.iterator();
#line 114 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator199, "hasNext", 407283053, default(global::Array))) ))
{
#line 114 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
object l = ((object) (global::haxe.lang.Runtime.callField(__temp_iterator199, "next", 1224901875, default(global::Array))) );
#line 114 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
if (( global::haxe.lang.Runtime.compare(((int) (global::haxe.lang.Runtime.getField_f(l, "used", 1303220797, true)) ), 0) <= 0 ))
{
#line 114 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
c++;
}
}
}
return c;
}
#line default
}
public static bool _get_active(object this1)
{
unchecked
{
#line 118 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return ((bool) (global::haxe.lang.Runtime.getField(this1, "active", 373703110, true)) );
}
#line default
}
public static bool _set_active(object this1, bool b)
{
unchecked
{
#line 120 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return ((bool) (global::haxe.lang.Runtime.setField(this1, "active", 373703110, b)) );
}
#line default
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony.events._Listener
{
public class Listener_Impl__fromSignal_65__Fun : global::haxe.lang.Function
{
public Listener_Impl__fromSignal_65__Fun(global::Array<object> _g, global::Array<object> @event) : base(0, 0)
{
unchecked
{
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
this._g = _g;
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
this.@event = @event;
}
#line default
}
public override object __hx_invoke0_o()
{
unchecked
{
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
((global::pony.events.Signal) (this._g[0]) ).dispatchEvent(((global::pony.events.Event) (this.@event[0]) ));
#line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/events/Listener.hx"
return default(object);
}
#line default
}
public global::Array<object> _g;
public global::Array<object> @event;
}
}
| |
using NUnit.Framework;
using System;
using System.Linq;
using OpenQA.Selenium.Environment;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Interactions;
using System.Collections.Generic;
namespace OpenQA.Selenium.IE
{
[TestFixture]
public class IeSpecificTests : DriverTestFixture
{
[Test]
public void InputOnChangeAlert()
{
driver.Url = alertsPage;
driver.FindElement(By.Id("input")).Clear();
IAlert alert = WaitFor<IAlert>(() => { return driver.SwitchTo().Alert(); });
alert.Accept();
}
[Test]
public void ScrollingFrameTest()
{
try
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("frameScrollPage.html");
WaitFor(FrameToExistAndBeSwitchedTo("scrolling_frame"));
IWebElement element = driver.FindElement(By.Name("scroll_checkbox"));
element.Click();
Assert.IsTrue(element.Selected);
driver.SwitchTo().DefaultContent();
WaitFor(FrameToExistAndBeSwitchedTo("scrolling_child_frame"));
WaitFor(FrameToExistAndBeSwitchedTo("scrolling_frame"));
element = driver.FindElement(By.Name("scroll_checkbox"));
element.Click();
Assert.IsTrue(element.Selected);
}
finally
{
driver.SwitchTo().DefaultContent();
}
}
[Test]
public void AlertSelectTest()
{
driver.Url = alertsPage;
driver.FindElement(By.Id("value1")).Click();
IAlert alert = WaitFor<IAlert>(() => { return driver.SwitchTo().Alert(); });
alert.Accept();
}
[Test]
public void ShouldBeAbleToBrowseTransformedXml()
{
driver.Url = xhtmlTestPage;
driver.FindElement(By.Id("linkId")).Click();
// Using transformed XML (Issue 1203)
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("transformable.xml");
driver.FindElement(By.Id("x")).Click();
// Sleep is required; driver may not be fast enough after this Click().
System.Threading.Thread.Sleep(2000);
Assert.AreEqual("XHTML Test Page", driver.Title);
// Act on the result page to make sure the window handling is still valid.
driver.FindElement(By.Id("linkId")).Click();
Assert.AreEqual("We Arrive Here", driver.Title);
}
[Test]
public void ShouldBeAbleToStartMoreThanOneInstanceOfTheIEDriverSimultaneously()
{
IWebDriver secondDriver = new InternetExplorerDriver();
driver.Url = xhtmlTestPage;
secondDriver.Url = formsPage;
Assert.AreEqual("XHTML Test Page", driver.Title);
Assert.AreEqual("We Leave From Here", secondDriver.Title);
// We only need to quit the second driver if the test passes
secondDriver.Quit();
}
[Test]
public void ShouldPropagateSessionCookies()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("sessionCookie.html");
IWebElement setColorButton = driver.FindElement(By.Id("setcolorbutton"));
setColorButton.Click();
IWebElement openWindowButton = driver.FindElement(By.Id("openwindowbutton"));
openWindowButton.Click();
System.Threading.Thread.Sleep(2000);
string startWindow = driver.CurrentWindowHandle;
driver.SwitchTo().Window("cookiedestwindow");
string bodyStyle = driver.FindElement(By.TagName("body")).GetAttribute("style");
driver.Close();
driver.SwitchTo().Window(startWindow);
Assert.IsTrue(bodyStyle.Contains("BACKGROUND-COLOR: #80ffff") || bodyStyle.Contains("background-color: rgb(128, 255, 255)"));
}
[Test]
public void ShouldHandleShowModalDialogWindows()
{
driver.Url = alertsPage;
string originalWindowHandle = driver.CurrentWindowHandle;
IWebElement element = driver.FindElement(By.Id("dialog"));
element.Click();
WaitFor(() => { return driver.WindowHandles.Count > 1; });
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
Assert.AreEqual(2, windowHandles.Count);
string dialogHandle = string.Empty;
foreach (string handle in windowHandles)
{
if (handle != originalWindowHandle)
{
dialogHandle = handle;
break;
}
}
Assert.AreNotEqual(string.Empty, dialogHandle);
driver.SwitchTo().Window(dialogHandle);
IWebElement closeElement = driver.FindElement(By.Id("close"));
closeElement.Click();
WaitFor(() => { return driver.WindowHandles.Count == 1; });
windowHandles = driver.WindowHandles;
Assert.AreEqual(1, windowHandles.Count);
driver.SwitchTo().Window(originalWindowHandle);
}
[Test]
public void ScrollTest()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("scroll.html");
driver.FindElement(By.Id("line8")).Click();
Assert.AreEqual("line8", driver.FindElement(By.Id("clicked")).Text);
driver.FindElement(By.Id("line1")).Click();
Assert.AreEqual("line1", driver.FindElement(By.Id("clicked")).Text);
}
[Test]
public void ShouldNotScrollOverflowElementsWhichAreVisible()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("scroll2.html");
var list = driver.FindElement(By.TagName("ul"));
var item = list.FindElement(By.Id("desired"));
item.Click();
Assert.AreEqual(0, ((IJavaScriptExecutor)driver).ExecuteScript("return arguments[0].scrollTop;", list), "Should not have scrolled");
}
[Test]
public void ShouldNotScrollIfAlreadyScrolledAndElementIsInView()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("scroll3.html");
driver.FindElement(By.Id("button1")).Click();
var scrollTop = GetScrollTop();
driver.FindElement(By.Id("button2")).Click();
Assert.AreEqual(scrollTop, GetScrollTop());
}
[Test]
public void ShouldBeAbleToHandleCascadingModalDialogs()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("modal_dialogs/modalindex.html");
string parentHandle = driver.CurrentWindowHandle;
// Launch first modal
driver.FindElement(By.CssSelector("input[type='button'][value='btn1']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 1; });
ReadOnlyCollection<string> windows = driver.WindowHandles;
string firstWindowHandle = windows.Except(new List<string>() { parentHandle }).First();
driver.SwitchTo().Window(firstWindowHandle);
Assert.AreEqual(2, windows.Count);
// Launch second modal
driver.FindElement(By.CssSelector("input[type='button'][value='btn2']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 2; });
ReadOnlyCollection<string> windows_1 = driver.WindowHandles;
string secondWindowHandle = windows_1.Except(windows).First();
driver.SwitchTo().Window(secondWindowHandle);
Assert.AreEqual(3, windows_1.Count);
// Launch third modal
driver.FindElement(By.CssSelector("input[type='button'][value='btn3']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 3; });
ReadOnlyCollection<string> windows_2 = driver.WindowHandles;
string finalWindowHandle = windows_2.Except(windows_1).First();
Assert.AreEqual(4, windows_2.Count);
driver.SwitchTo().Window(finalWindowHandle).Close();
driver.SwitchTo().Window(secondWindowHandle).Close();
driver.SwitchTo().Window(firstWindowHandle).Close();
driver.SwitchTo().Window(parentHandle);
}
[Test]
public void ShouldBeAbleToHandleCascadingModalDialogsLaunchedWithJavaScriptLinks()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("modal_dialogs/modalindex.html");
string parentHandle = driver.CurrentWindowHandle;
// Launch first modal
driver.FindElement(By.CssSelector("a[id='lnk1']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 1; });
ReadOnlyCollection<string> windows = driver.WindowHandles;
string firstWindowHandle = windows.Except(new List<string>() { parentHandle }).First();
driver.SwitchTo().Window(firstWindowHandle);
Assert.AreEqual(2, windows.Count);
// Launch second modal
driver.FindElement(By.CssSelector("a[id='lnk2']")).Click();
System.Threading.Thread.Sleep(5000);
WaitFor(() => { return driver.WindowHandles.Count > 2; });
ReadOnlyCollection<string> windows_1 = driver.WindowHandles;
string secondWindowHandle = windows_1.Except(windows).First();
driver.SwitchTo().Window(secondWindowHandle);
Assert.AreEqual(3, windows_1.Count);
// Launch third modal
driver.FindElement(By.CssSelector("a[id='lnk3']")).Click();
WaitFor(() => { return driver.WindowHandles.Count > 3; });
ReadOnlyCollection<string> windows_2 = driver.WindowHandles;
string finalWindowHandle = windows_2.Except(windows_1).First();
Assert.AreEqual(4, windows_2.Count);
driver.SwitchTo().Window(finalWindowHandle).Close();
driver.SwitchTo().Window(secondWindowHandle).Close();
driver.SwitchTo().Window(firstWindowHandle).Close();
driver.SwitchTo().Window(parentHandle);
}
private long GetScrollTop()
{
return (long)((IJavaScriptExecutor)driver).ExecuteScript("return document.body.scrollTop;");
}
private Func<bool> FrameToExistAndBeSwitchedTo(string frameName)
{
return () =>
{
try
{
driver.SwitchTo().Frame(frameName);
}
catch (NoSuchFrameException)
{
return false;
}
return true;
};
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using XenAPI;
using XenAdmin.Core;
namespace XenAdmin.Dialogs
{
public partial class ConfirmVMDeleteDialog : XenDialogBase
{
private const int MINIMUM_COL_WIDTH = 50;
public ConfirmVMDeleteDialog(IEnumerable<VM> vms)
{
Util.ThrowIfParameterNull(vms, "vms");
InitializeComponent();
HelpButton = true;
// We have to set the header text again here because they're in base64
// encoding in the resx, so can't be easily localised: see CA-43371.
listView.Groups["listViewGroupAttachedDisks"].Header = Messages.ATTACHED_VIRTUAL_DISKS;
listView.Groups["listViewGroupSnapshots"].Header = Messages.SNAPSHOTS;
List<VM> vmList = new List<VM>(vms);
if (vmList.Count == 1)
{
String type = vmList[0].is_a_template ? Messages.TEMPLATE : Messages.VM;
Text = String.Format(Messages.CONFIRM_DELETE_TITLE, type);
}
else
{
Text = Messages.CONFIRM_DELETE_ITEMS_TITLE;
}
List<VDI> sharedVDIsCouldBeDelete=new List<VDI>();
foreach (VM vm in vmList)
{
foreach (VBD vbd in vm.Connection.ResolveAll(vm.VBDs))
{
if (!vbd.IsCDROM())
{
VDI vdi = vbd.Connection.Resolve(vbd.VDI);
if (vdi != null)
{
IList<VM> VMsUsingVDI = vdi.GetVMs();
bool allTheVMsAreDeleted = true;
if (VMsUsingVDI.Count > 1)
{
foreach (VM vmUsingVdi in VMsUsingVDI)
{
if (!vmList.Contains(vmUsingVdi))
{
allTheVMsAreDeleted = false;
break;
}
}
if (allTheVMsAreDeleted&&!sharedVDIsCouldBeDelete.Contains(vdi))
{
sharedVDIsCouldBeDelete.Add(vdi);
}
}
else
{
ListViewItem item = new ListViewItem();
item.Text = vdi.Name();
item.SubItems.Add(vm.Name());
item.Group = listView.Groups["listViewGroupAttachedDisks"];
item.Tag = vbd;
item.Checked = vbd.GetIsOwner();
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
subitem.Tag = subitem.Text;
listView.Items.Add(item);
}
}
}
}
foreach (VM snapshot in vm.Connection.ResolveAll(vm.snapshots))
{
ListViewItem item = new ListViewItem();
item.Text = snapshot.Name();
item.SubItems.Add(vm.Name());
item.Tag = snapshot;
item.Group = listView.Groups["listViewGroupSnapshots"];
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
subitem.Tag = subitem.Text;
listView.Items.Add(item);
}
}
foreach (VDI vdi in sharedVDIsCouldBeDelete)
{
ListViewItem item = new ListViewItem();
item.Text = vdi.Name();
item.SubItems.Add(vdi.VMsOfVDI());
item.Group = listView.Groups["listViewGroupAttachedDisks"];
item.Tag = vdi.Connection.ResolveAll(vdi.VBDs);
item.Checked = false;
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
subitem.Tag = subitem.Text;
listView.Items.Add(item);
}
EnableSelectAllClear();
EllipsizeStrings();
}
public ConfirmVMDeleteDialog(VM vm)
: this(new VM[] { vm })
{
}
public List<VBD> DeleteDisks
{
get
{
List<VBD> vbds = new List<VBD>();
foreach (ListViewItem item in listView.CheckedItems)
{
VBD vbd = item.Tag as VBD;
if (vbd != null)
vbds.Add(vbd);
List<VBD> vbdsList = item.Tag as List<VBD>;
if (vbdsList != null)
vbds.AddRange(vbdsList);
}
return vbds;
}
}
public List<VM> DeleteSnapshots
{
get
{
List<VM> snapshots = new List<VM>();
foreach (ListViewItem item in listView.CheckedItems)
{
VM snapshot = item.Tag as VM;
if (snapshot != null)
snapshots.Add(snapshot);
}
return snapshots;
}
}
private void EllipsizeStrings()
{
foreach (ColumnHeader col in listView.Columns)
EllipsizeStrings(col.Index);
}
private void EllipsizeStrings(int columnIndex)
{
foreach (ListViewItem item in listView.Items)
{
if (columnIndex < 0 || columnIndex >= item.SubItems.Count)
continue;
var subItem = item.SubItems[columnIndex];
string wholeText = subItem.Tag as string;
if (wholeText == null)
continue;
var rec = new Rectangle(subItem.Bounds.Left, subItem.Bounds.Top,
listView.Columns[columnIndex].Width, subItem.Bounds.Height);
subItem.Text = wholeText.Ellipsise(rec, subItem.Font);
listView.Invalidate(rec);
}
}
private void buttonSelectAll_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in listView.Items)
{
item.Checked = true;
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in listView.Items)
{
item.Checked = false;
}
}
private void EnableSelectAllClear()
{
bool allChecked = true;
bool allUnChecked = true;
foreach (ListViewItem item in listView.Items)
{
if (item.Checked)
allUnChecked = false;
else
allChecked = false;
}
buttonSelectAll.Enabled = !allChecked;
buttonClear.Enabled = !allUnChecked;
}
private void listView_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
if (e.ColumnIndex < 0 || e.ColumnIndex >= listView.Columns.Count)
return;
if (e.NewWidth < MINIMUM_COL_WIDTH)
{
e.NewWidth = MINIMUM_COL_WIDTH;
e.Cancel = true;
}
}
private void listView_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e)
{
EllipsizeStrings(e.ColumnIndex);
}
private void listView_ItemChecked(object sender, ItemCheckedEventArgs e)
{
EnableSelectAllClear();
}
private class ListViewDeleteDialog:ListView
{
private bool _b = false;
private string _msg = Messages.EMPTY_LIST_DISK_SNAPSHOTS;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
base.WndProc(ref m);
if (m.Msg == 20)
{
if (Items.Count == 0)
{
_b = true;
using (Graphics g = CreateGraphics())
{
int w = (Width - g.MeasureString(_msg, Font).ToSize().Width) / 2;
g.DrawString(_msg, Font, SystemBrushes.ControlText, w, 30);
}
}
else
{
if (_b)
{
Invalidate();
_b = false;
}
}
}
if (m.Msg == 4127)
Invalidate();
}
}
}
}
| |
/*
* FCKeditor - The text editor for internet
* Copyright (C) 2003-2004 Frederico Caldeira Knabben
*
* Licensed under the terms of the GNU Lesser General Public License:
* http://www.opensource.org/licenses/lgpl-license.php
*
* For further information visit:
* http://www.fckeditor.net/
*
* File Name: FCKeditor.cs
* This is the FCKeditor Asp.Net control.
*
* Version: 2.1
* Modified: 2005-02-27 19:44:36
*
* File Authors:
* Frederico Caldeira Knabben (fredck@fckeditor.net)
*/
using System ;
using System.Web.UI ;
using System.Web.UI.WebControls ;
using System.ComponentModel ;
using System.Text.RegularExpressions ;
using System.Globalization ;
using System.Security.Permissions ;
namespace FredCK.FCKeditorV2
{
public enum LanguageDirection
{
LeftToRight,
RightToLeft
}
[ DefaultProperty("Value") ]
[ ValidationProperty("Value") ]
[ ToolboxData("<{0}:FCKeditor runat=server></{0}:FCKeditor>") ]
[ Designer("FredCK.FCKeditorV2.FCKeditorDesigner") ]
[ ParseChildren(false) ]
public class FCKeditor : System.Web.UI.Control, IPostBackDataHandler
{
private FCKeditorConfigurations oConfig ;
public FCKeditor()
{
oConfig = new FCKeditorConfigurations() ;
}
#region Base Configurations Properties
[ Browsable( false ) ]
public FCKeditorConfigurations Config
{
get { return oConfig ; }
}
[ DefaultValue( "" ) ]
public string Value
{
get { return (string)IsNull( ViewState["Value"], "" ) ; }
set { ViewState["Value"] = value ; }
}
/// <summary>
/// <p>
/// Sets or gets the virtual path to the editor's directory. It is
/// relative to the current page.
/// </p>
/// <p>
/// The default value is "/FCKeditor/".
/// </p>
/// <p>
/// The base path can be also set in the Web.config file using the
/// appSettings section. Just set the "FCKeditor:BasePath" for that.
/// For example:
/// <code>
/// <configuration>
/// <appSettings>
/// <add key="FCKeditor:BasePath" value="/scripts/FCKeditor/" />
/// </appSettings>
/// </configuration>
/// </code>
/// </p>
/// </summary>
[ DefaultValue( "/FCKeditor/" ) ]
public string BasePath
{
get
{
if ( ViewState["BasePath"] == null )
{
return (string)IsNull(
System.Configuration.ConfigurationSettings.AppSettings["FCKeditor:BasePath"],
"/FCKeditor/" ) ;
}
else
return (string)ViewState["BasePath"] ;
}
set { ViewState["BasePath"] = value ; }
}
[ DefaultValue( "Default" ) ]
public string ToolbarSet
{
get { return (string)IsNull( ViewState["ToolbarSet"], "Default" ) ; }
set { ViewState["ToolbarSet"] = value ; }
}
#endregion
#region Appearence Properties
[ Category( "Appearence" ) ]
[ DefaultValue( "100%" ) ]
public Unit Width
{
get { return (Unit)IsNull( ViewState["Width"], Unit.Parse("100%", CultureInfo.InvariantCulture) ) ; }
set { ViewState["Width"] = value ; }
}
[ Category("Appearence") ]
[ DefaultValue( "200px" ) ]
public Unit Height
{
get { return (Unit)IsNull( ViewState["Height"], Unit.Parse("200px", CultureInfo.InvariantCulture) ) ; }
set { ViewState["Height"] = value ; }
}
#endregion
#region Configurations Properties
[ Category("Configurations") ]
public string CustomConfigurationsPath
{
set { this.Config["CustomConfigurationsPath"] = value ; }
}
[ Category("Configurations") ]
public string EditorAreaCSS
{
set { this.Config["EditorAreaCSS"] = value ; }
}
[ Category("Configurations") ]
public string BaseHref
{
set { this.Config["BaseHref"] = value ; }
}
[ Category("Configurations") ]
public string SkinPath
{
set { this.Config["SkinPath"] = value ; }
}
[ Category("Configurations") ]
public string PluginsPath
{
set { this.Config["PluginsPath"] = value ; }
}
[ Category("Configurations") ]
public bool FullPage
{
set { this.Config["FullPage"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool Debug
{
set { this.Config["Debug"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool AutoDetectLanguage
{
set { this.Config["AutoDetectLanguage"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public string DefaultLanguage
{
set { this.Config["DefaultLanguage"] = value ; }
}
[ Category("Configurations") ]
public LanguageDirection ContentLangDirection
{
set { this.Config["ContentLangDirection"] = ( value == LanguageDirection.LeftToRight ? "ltr" : "rtl" ) ; }
}
[ Category("Configurations") ]
public bool EnableXHTML
{
set { this.Config["EnableXHTML"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool EnableSourceXHTML
{
set { this.Config["EnableSourceXHTML"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool FillEmptyBlocks
{
set { this.Config["FillEmptyBlocks"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool FormatSource
{
set { this.Config["FormatSource"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool FormatOutput
{
set { this.Config["FormatOutput"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public string FormatIndentator
{
set { this.Config["FormatIndentator"] = value ; }
}
[ Category("Configurations") ]
public bool GeckoUseSPAN
{
set { this.Config["GeckoUseSPAN"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool StartupFocus
{
set { this.Config["StartupFocus"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool ForcePasteAsPlainText
{
set { this.Config["ForcePasteAsPlainText"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool ForceSimpleAmpersand
{
set { this.Config["ForceSimpleAmpersand"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public int TabSpaces
{
set { this.Config["TabSpaces"] = value.ToString() ; }
}
[ Category("Configurations") ]
public bool UseBROnCarriageReturn
{
set { this.Config["UseBROnCarriageReturn"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool ToolbarStartExpanded
{
set { this.Config["ToolbarStartExpanded"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public bool ToolbarCanCollapse
{
set { this.Config["ToolbarCanCollapse"] = ( value ? "true" : "false" ) ; }
}
[ Category("Configurations") ]
public string FontColors
{
set { this.Config["FontColors"] = value ; }
}
[ Category("Configurations") ]
public string FontNames
{
set { this.Config["FontNames"] = value ; }
}
[ Category("Configurations") ]
public string FontSizes
{
set { this.Config["FontSizes"] = value ; }
}
[ Category("Configurations") ]
public string FontFormats
{
set { this.Config["FontFormats"] = value ; }
}
[ Category("Configurations") ]
public string StylesXmlPath
{
set { this.Config["StylesXmlPath"] = value ; }
}
[ Category("Configurations") ]
public string LinkBrowserURL
{
set { this.Config["LinkBrowserURL"] = value ; }
}
[ Category("Configurations") ]
public string ImageBrowserURL
{
set { this.Config["ImageBrowserURL"] = value ; }
}
#endregion
#region Rendering
protected override void Render(HtmlTextWriter writer)
{
writer.Write( "<div>" ) ;
if ( this.CheckBrowserCompatibility() )
{
string sLink = this.BasePath ;
if ( sLink.StartsWith( "~" ) )
sLink = this.ResolveUrl( sLink ) ;
sLink += "editor/fckeditor.html?InstanceName=" + this.ClientID ;
if ( this.ToolbarSet.Length > 0 ) sLink += "&Toolbar=" + this.ToolbarSet ;
// Render the linked hidden field.
writer.Write(
"<input type=\"hidden\" id=\"{0}\" name=\"{1}\" value=\"{2}\">",
this.ClientID,
this.UniqueID,
System.Web.HttpUtility.HtmlEncode( this.Value ) ) ;
// Render the configurations hidden field.
writer.Write(
"<input type=\"hidden\" id=\"{0}___Config\" value=\"{1}\">",
this.ClientID,
this.Config.GetHiddenFieldString() ) ;
// Render the editor IFRAME.
writer.Write(
"<iframe id=\"{0}___Frame\" src=\"{1}\" width=\"{2}\" height=\"{3}\" frameborder=\"no\" scrolling=\"no\"></iframe>",
this.ClientID,
sLink,
this.Width,
this.Height ) ;
}
else
{
writer.Write(
"<textarea name=\"{0}\" rows=\"4\" cols=\"40\" style=\"width: {1}; height: {2}\" wrap=\"virtual\">{3}</textarea>",
this.UniqueID,
this.Width,
this.Height,
System.Web.HttpUtility.HtmlEncode( this.Value ) ) ;
}
writer.Write( "</div>" ) ;
}
public bool CheckBrowserCompatibility()
{
System.Web.HttpBrowserCapabilities oBrowser = Page.Request.Browser ;
// Internet Explorer 5.5+ for Windows
if (oBrowser.Browser == "IE" && ( oBrowser.MajorVersion >= 6 || ( oBrowser.MajorVersion == 5 && oBrowser.MinorVersion >= 0.5 ) ) && oBrowser.Win32)
return true ;
else
{
Match oMatch = Regex.Match( this.Page.Request.UserAgent, @"(?<=Gecko/)\d{8}" ) ;
return ( oMatch.Success && int.Parse( oMatch.Value, CultureInfo.InvariantCulture ) >= 20030210 ) ;
}
}
#endregion
#region Postback Handling
public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
{
if ( postCollection[postDataKey] != this.Value )
{
this.Value = postCollection[postDataKey] ;
return true ;
}
return false ;
}
public void RaisePostDataChangedEvent()
{
// Do nothing
}
#endregion
#region Tools
private object IsNull( object valueToCheck, object replacementValue )
{
return valueToCheck == null ? replacementValue : valueToCheck ;
}
#endregion
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Configuration;
using System.Reflection;
using log4net.Util;
using log4net.Repository;
namespace log4net.Core
{
/// <summary>
/// Static manager that controls the creation of repositories
/// </summary>
/// <remarks>
/// <para>
/// Static manager that controls the creation of repositories
/// </para>
/// <para>
/// This class is used by the wrapper managers (e.g. <see cref="log4net.LogManager"/>)
/// to provide access to the <see cref="ILogger"/> objects.
/// </para>
/// <para>
/// This manager also holds the <see cref="IRepositorySelector"/> that is used to
/// lookup and create repositories. The selector can be set either programmatically using
/// the <see cref="RepositorySelector"/> property, or by setting the <c>log4net.RepositorySelector</c>
/// AppSetting in the applications config file to the fully qualified type name of the
/// selector to use.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public sealed class LoggerManager
{
#region Private Instance Constructors
/// <summary>
/// Private constructor to prevent instances. Only static methods should be used.
/// </summary>
/// <remarks>
/// <para>
/// Private constructor to prevent instances. Only static methods should be used.
/// </para>
/// </remarks>
private LoggerManager()
{
}
#endregion Private Instance Constructors
#region Static Constructor
/// <summary>
/// Hook the shutdown event
/// </summary>
/// <remarks>
/// <para>
/// On the full .NET runtime, the static constructor hooks up the
/// <c>AppDomain.ProcessExit</c> and <c>AppDomain.DomainUnload</c>> events.
/// These are used to shutdown the log4net system as the application exits.
/// </para>
/// </remarks>
static LoggerManager()
{
try
{
// Register the AppDomain events, note we have to do this with a
// method call rather than directly here because the AppDomain
// makes a LinkDemand which throws the exception during the JIT phase.
RegisterAppDomainEvents();
}
catch(System.Security.SecurityException)
{
LogLog.Debug(declaringType, "Security Exception (ControlAppDomain LinkDemand) while trying "+
"to register Shutdown handler with the AppDomain. LoggerManager.Shutdown() "+
"will not be called automatically when the AppDomain exits. It must be called "+
"programmatically.");
}
// Dump out our assembly version into the log if debug is enabled
LogLog.Debug(declaringType, GetVersionInfo());
// Set the default repository selector
#if NETCF
s_repositorySelector = new CompactRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy));
#else
// Look for the RepositorySelector type specified in the AppSettings 'log4net.RepositorySelector'
string appRepositorySelectorTypeName = SystemInfo.GetAppSetting("log4net.RepositorySelector");
if (appRepositorySelectorTypeName != null && appRepositorySelectorTypeName.Length > 0)
{
// Resolve the config string into a Type
Type appRepositorySelectorType = null;
try
{
appRepositorySelectorType = SystemInfo.GetTypeFromString(appRepositorySelectorTypeName, false, true);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Exception while resolving RepositorySelector Type ["+appRepositorySelectorTypeName+"]", ex);
}
if (appRepositorySelectorType != null)
{
// Create an instance of the RepositorySelectorType
object appRepositorySelectorObj = null;
try
{
appRepositorySelectorObj = Activator.CreateInstance(appRepositorySelectorType);
}
catch(Exception ex)
{
LogLog.Error(declaringType, "Exception while creating RepositorySelector ["+appRepositorySelectorType.FullName+"]", ex);
}
if (appRepositorySelectorObj != null && appRepositorySelectorObj is IRepositorySelector)
{
s_repositorySelector = (IRepositorySelector)appRepositorySelectorObj;
}
else
{
LogLog.Error(declaringType, "RepositorySelector Type ["+appRepositorySelectorType.FullName+"] is not an IRepositorySelector");
}
}
}
// Create the DefaultRepositorySelector if not configured above
if (s_repositorySelector == null)
{
s_repositorySelector = new DefaultRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy));
}
#endif
}
/// <summary>
/// Register for ProcessExit and DomainUnload events on the AppDomain
/// </summary>
/// <remarks>
/// <para>
/// This needs to be in a separate method because the events make
/// a LinkDemand for the ControlAppDomain SecurityPermission. Because
/// this is a LinkDemand it is demanded at JIT time. Therefore we cannot
/// catch the exception in the method itself, we have to catch it in the
/// caller.
/// </para>
/// </remarks>
private static void RegisterAppDomainEvents()
{
#if !NETCF
// ProcessExit seems to be fired if we are part of the default domain
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
// Otherwise DomainUnload is fired
AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload);
#endif
}
#endregion Static Constructor
#region Public Static Methods
/// <summary>
/// Return the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="repository">the repository to lookup in</param>
/// <returns>Return the default <see cref="ILoggerRepository"/> instance</returns>
/// <remarks>
/// <para>
/// Gets the <see cref="ILoggerRepository"/> for the repository specified
/// by the <paramref name="repository"/> argument.
/// </para>
/// </remarks>
[Obsolete("Use GetRepository instead of GetLoggerRepository")]
public static ILoggerRepository GetLoggerRepository(string repository)
{
return GetRepository(repository);
}
/// <summary>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <returns>The default <see cref="ILoggerRepository"/> instance.</returns>
[Obsolete("Use GetRepository instead of GetLoggerRepository")]
public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly)
{
return GetRepository(repositoryAssembly);
}
/// <summary>
/// Return the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="repository">the repository to lookup in</param>
/// <returns>Return the default <see cref="ILoggerRepository"/> instance</returns>
/// <remarks>
/// <para>
/// Gets the <see cref="ILoggerRepository"/> for the repository specified
/// by the <paramref name="repository"/> argument.
/// </para>
/// </remarks>
public static ILoggerRepository GetRepository(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
return RepositorySelector.GetRepository(repository);
}
/// <summary>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <returns>The default <see cref="ILoggerRepository"/> instance.</returns>
/// <remarks>
/// <para>
/// Returns the default <see cref="ILoggerRepository"/> instance.
/// </para>
/// </remarks>
public static ILoggerRepository GetRepository(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
return RepositorySelector.GetRepository(repositoryAssembly);
}
/// <summary>
/// Returns the named logger if it exists.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <param name="name">The fully qualified logger name to look for.</param>
/// <returns>
/// The logger found, or <c>null</c> if the named logger does not exist in the
/// specified repository.
/// </returns>
/// <remarks>
/// <para>
/// If the named logger exists (in the specified repository) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.
/// </para>
/// </remarks>
public static ILogger Exists(string repository, string name)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repository).Exists(name);
}
/// <summary>
/// Returns the named logger if it exists.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <param name="name">The fully qualified logger name to look for.</param>
/// <returns>
/// The logger found, or <c>null</c> if the named logger does not exist in the
/// specified assembly's repository.
/// </returns>
/// <remarks>
/// <para>
/// If the named logger exists (in the specified assembly's repository) then it
/// returns a reference to the logger, otherwise it returns
/// <c>null</c>.
/// </para>
/// </remarks>
public static ILogger Exists(Assembly repositoryAssembly, string name)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repositoryAssembly).Exists(name);
}
/// <summary>
/// Returns all the currently defined loggers in the specified repository.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <returns>All the defined loggers.</returns>
/// <remarks>
/// <para>
/// The root logger is <b>not</b> included in the returned array.
/// </para>
/// </remarks>
public static ILogger[] GetCurrentLoggers(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
return RepositorySelector.GetRepository(repository).GetCurrentLoggers();
}
/// <summary>
/// Returns all the currently defined loggers in the specified assembly's repository.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <returns>All the defined loggers.</returns>
/// <remarks>
/// <para>
/// The root logger is <b>not</b> included in the returned array.
/// </para>
/// </remarks>
public static ILogger[] GetCurrentLoggers(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
return RepositorySelector.GetRepository(repositoryAssembly).GetCurrentLoggers();
}
/// <summary>
/// Retrieves or creates a named logger.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Retrieves a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.
/// </para>
/// <para>
/// By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.
/// </para>
/// </remarks>
public static ILogger GetLogger(string repository, string name)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repository).GetLogger(name);
}
/// <summary>
/// Retrieves or creates a named logger.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <param name="name">The name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Retrieves a logger named as the <paramref name="name"/>
/// parameter. If the named logger already exists, then the
/// existing instance will be returned. Otherwise, a new instance is
/// created.
/// </para>
/// <para>
/// By default, loggers do not have a set level but inherit
/// it from the hierarchy. This is one of the central features of
/// log4net.
/// </para>
/// </remarks>
public static ILogger GetLogger(Assembly repositoryAssembly, string name)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(name);
}
/// <summary>
/// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
/// </summary>
/// <param name="repository">The repository to lookup in.</param>
/// <param name="type">The <paramref name="type"/> of which the fullname will be used as the name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Gets the logger for the fully qualified name of the type specified.
/// </para>
/// </remarks>
public static ILogger GetLogger(string repository, Type type)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
return RepositorySelector.GetRepository(repository).GetLogger(type.FullName);
}
/// <summary>
/// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
/// </summary>
/// <param name="repositoryAssembly">the assembly to use to lookup the repository</param>
/// <param name="type">The <paramref name="type"/> of which the fullname will be used as the name of the logger to retrieve.</param>
/// <returns>The logger with the name specified.</returns>
/// <remarks>
/// <para>
/// Gets the logger for the fully qualified name of the type specified.
/// </para>
/// </remarks>
public static ILogger GetLogger(Assembly repositoryAssembly, Type type)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(type.FullName);
}
/// <summary>
/// Shuts down the log4net system.
/// </summary>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in all the
/// default repositories.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>
/// The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void Shutdown()
{
foreach(ILoggerRepository repository in GetAllRepositories())
{
repository.Shutdown();
}
}
/// <summary>
/// Shuts down the repository for the repository specified.
/// </summary>
/// <param name="repository">The repository to shutdown.</param>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in the
/// repository for the <paramref name="repository"/> specified.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>
/// The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void ShutdownRepository(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
RepositorySelector.GetRepository(repository).Shutdown();
}
/// <summary>
/// Shuts down the repository for the repository specified.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param>
/// <remarks>
/// <para>
/// Calling this method will <b>safely</b> close and remove all
/// appenders in all the loggers including root contained in the
/// repository for the repository. The repository is looked up using
/// the <paramref name="repositoryAssembly"/> specified.
/// </para>
/// <para>
/// Some appenders need to be closed before the application exists.
/// Otherwise, pending logging events might be lost.
/// </para>
/// <para>
/// The <c>shutdown</c> method is careful to close nested
/// appenders before closing regular appenders. This is allows
/// configurations where a regular appender is attached to a logger
/// and again to a nested appender.
/// </para>
/// </remarks>
public static void ShutdownRepository(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
RepositorySelector.GetRepository(repositoryAssembly).Shutdown();
}
/// <summary>
/// Resets all values contained in this repository instance to their defaults.
/// </summary>
/// <param name="repository">The repository to reset.</param>
/// <remarks>
/// <para>
/// Resets all values contained in the repository instance to their
/// defaults. This removes all appenders from all loggers, sets
/// the level of all non-root loggers to <c>null</c>,
/// sets their additivity flag to <c>true</c> and sets the level
/// of the root logger to <see cref="Level.Debug"/>. Moreover,
/// message disabling is set its default "off" value.
/// </para>
/// </remarks>
public static void ResetConfiguration(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
RepositorySelector.GetRepository(repository).ResetConfiguration();
}
/// <summary>
/// Resets all values contained in this repository instance to their defaults.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to lookup the repository to reset.</param>
/// <remarks>
/// <para>
/// Resets all values contained in the repository instance to their
/// defaults. This removes all appenders from all loggers, sets
/// the level of all non-root loggers to <c>null</c>,
/// sets their additivity flag to <c>true</c> and sets the level
/// of the root logger to <see cref="Level.Debug"/>. Moreover,
/// message disabling is set its default "off" value.
/// </para>
/// </remarks>
public static void ResetConfiguration(Assembly repositoryAssembly)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
RepositorySelector.GetRepository(repositoryAssembly).ResetConfiguration();
}
/// <summary>
/// Creates a repository with the specified name.
/// </summary>
/// <param name="repository">The name of the repository, this must be unique amongst repositories.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b>
/// </para>
/// <para>
/// Creates the default type of <see cref="ILoggerRepository"/> which is a
/// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object.
/// </para>
/// <para>
/// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined.
/// An <see cref="Exception"/> will be thrown if the repository already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified repository already exists.</exception>
[Obsolete("Use CreateRepository instead of CreateDomain")]
public static ILoggerRepository CreateDomain(string repository)
{
return CreateRepository(repository);
}
/// <summary>
/// Creates a repository with the specified name.
/// </summary>
/// <param name="repository">The name of the repository, this must be unique amongst repositories.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// Creates the default type of <see cref="ILoggerRepository"/> which is a
/// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object.
/// </para>
/// <para>
/// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined.
/// An <see cref="Exception"/> will be thrown if the repository already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified repository already exists.</exception>
public static ILoggerRepository CreateRepository(string repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
return RepositorySelector.CreateRepository(repository, null);
}
/// <summary>
/// Creates a repository with the specified name and repository type.
/// </summary>
/// <param name="repository">The name of the repository, this must be unique to the repository.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the repository specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b>
/// </para>
/// <para>
/// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined.
/// An Exception will be thrown if the repository already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified repository already exists.</exception>
[Obsolete("Use CreateRepository instead of CreateDomain")]
public static ILoggerRepository CreateDomain(string repository, Type repositoryType)
{
return CreateRepository(repository, repositoryType);
}
/// <summary>
/// Creates a repository with the specified name and repository type.
/// </summary>
/// <param name="repository">The name of the repository, this must be unique to the repository.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the repository specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined.
/// An Exception will be thrown if the repository already exists.
/// </para>
/// </remarks>
/// <exception cref="LogException">The specified repository already exists.</exception>
public static ILoggerRepository CreateRepository(string repository, Type repositoryType)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
if (repositoryType == null)
{
throw new ArgumentNullException("repositoryType");
}
return RepositorySelector.CreateRepository(repository, repositoryType);
}
/// <summary>
/// Creates a repository for the specified assembly and repository type.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the repository specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b>
/// </para>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be associated with the repository
/// specified such that a call to <see cref="GetRepository(Assembly)"/> with the
/// same assembly specified will return the same repository instance.
/// </para>
/// </remarks>
[Obsolete("Use CreateRepository instead of CreateDomain")]
public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType)
{
return CreateRepository(repositoryAssembly, repositoryType);
}
/// <summary>
/// Creates a repository for the specified assembly and repository type.
/// </summary>
/// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param>
/// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/>
/// and has a no arg constructor. An instance of this type will be created to act
/// as the <see cref="ILoggerRepository"/> for the repository specified.</param>
/// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns>
/// <remarks>
/// <para>
/// The <see cref="ILoggerRepository"/> created will be associated with the repository
/// specified such that a call to <see cref="GetRepository(Assembly)"/> with the
/// same assembly specified will return the same repository instance.
/// </para>
/// </remarks>
public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType)
{
if (repositoryAssembly == null)
{
throw new ArgumentNullException("repositoryAssembly");
}
if (repositoryType == null)
{
throw new ArgumentNullException("repositoryType");
}
return RepositorySelector.CreateRepository(repositoryAssembly, repositoryType);
}
/// <summary>
/// Gets an array of all currently defined repositories.
/// </summary>
/// <returns>An array of all the known <see cref="ILoggerRepository"/> objects.</returns>
/// <remarks>
/// <para>
/// Gets an array of all currently defined repositories.
/// </para>
/// </remarks>
public static ILoggerRepository[] GetAllRepositories()
{
return RepositorySelector.GetAllRepositories();
}
/// <summary>
/// Gets or sets the repository selector used by the <see cref="LogManager" />.
/// </summary>
/// <value>
/// The repository selector used by the <see cref="LogManager" />.
/// </value>
/// <remarks>
/// <para>
/// The repository selector (<see cref="IRepositorySelector"/>) is used by
/// the <see cref="LogManager"/> to create and select repositories
/// (<see cref="ILoggerRepository"/>).
/// </para>
/// <para>
/// The caller to <see cref="LogManager"/> supplies either a string name
/// or an assembly (if not supplied the assembly is inferred using
/// <see cref="Assembly.GetCallingAssembly()"/>).
/// </para>
/// <para>
/// This context is used by the selector to lookup a specific repository.
/// </para>
/// <para>
/// For the full .NET Framework, the default repository is <c>DefaultRepositorySelector</c>;
/// for the .NET Compact Framework <c>CompactRepositorySelector</c> is the default
/// repository.
/// </para>
/// </remarks>
public static IRepositorySelector RepositorySelector
{
get { return s_repositorySelector; }
set { s_repositorySelector = value; }
}
#endregion Public Static Methods
#region Private Static Methods
/// <summary>
/// Internal method to get pertinent version info.
/// </summary>
/// <returns>A string of version info.</returns>
private static string GetVersionInfo()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
// Grab the currently executing assembly
Assembly myAssembly = Assembly.GetExecutingAssembly();
// Build Up message
sb.Append("log4net assembly [").Append(myAssembly.FullName).Append("]. ");
sb.Append("Loaded from [").Append(SystemInfo.AssemblyLocationInfo(myAssembly)).Append("]. ");
sb.Append("(.NET Runtime [").Append(Environment.Version.ToString()).Append("]");
#if (!SSCLI)
sb.Append(" on ").Append(Environment.OSVersion.ToString());
#endif
sb.Append(")");
return sb.ToString();
}
#if (!NETCF)
/// <summary>
/// Called when the <see cref="AppDomain.DomainUnload"/> event fires
/// </summary>
/// <param name="sender">the <see cref="AppDomain"/> that is exiting</param>
/// <param name="e">null</param>
/// <remarks>
/// <para>
/// Called when the <see cref="AppDomain.DomainUnload"/> event fires.
/// </para>
/// <para>
/// When the event is triggered the log4net system is <see cref="Shutdown()"/>.
/// </para>
/// </remarks>
private static void OnDomainUnload(object sender, EventArgs e)
{
Shutdown();
}
/// <summary>
/// Called when the <see cref="AppDomain.ProcessExit"/> event fires
/// </summary>
/// <param name="sender">the <see cref="AppDomain"/> that is exiting</param>
/// <param name="e">null</param>
/// <remarks>
/// <para>
/// Called when the <see cref="AppDomain.ProcessExit"/> event fires.
/// </para>
/// <para>
/// When the event is triggered the log4net system is <see cref="Shutdown()"/>.
/// </para>
/// </remarks>
private static void OnProcessExit(object sender, EventArgs e)
{
Shutdown();
}
#endif
#endregion Private Static Methods
#region Private Static Fields
/// <summary>
/// The fully qualified type of the LoggerManager class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(LoggerManager);
/// <summary>
/// Initialize the default repository selector
/// </summary>
private static IRepositorySelector s_repositorySelector;
#endregion Private Static Fields
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using System.IO;
using System.Text.Unicode;
using Xunit;
namespace System.Text.Encodings.Web.Tests
{
public class HtmlEncoderTests
{
[Theory]
[InlineData("💩", "\U0001f4a9")]
[InlineData("😂2", "\U0001F6022")]
[InlineData("😂 21", "\U0001F602 21")]
[InlineData("x😂y", "x\U0001F602y")]
[InlineData("😂x😂y", "\U0001F602x\U0001F602y")]
public void TestSurrogate(string expected, string actual)
{
Assert.Equal(expected, System.Text.Encodings.Web.HtmlEncoder.Default.Encode(actual));
using (var writer = new StringWriter())
{
System.Text.Encodings.Web.HtmlEncoder.Default.Encode(writer, actual);
Assert.Equal(expected, writer.GetStringBuilder().ToString());
}
}
[Fact]
public void Ctor_WithTextEncoderSettings()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacters('a', 'b');
filter.AllowCharacters('\0', '&', '\uFFFF', 'd');
HtmlEncoder encoder = new HtmlEncoder(filter);
// Act & assert
Assert.Equal("a", encoder.HtmlEncode("a"));
Assert.Equal("b", encoder.HtmlEncode("b"));
Assert.Equal("c", encoder.HtmlEncode("c"));
Assert.Equal("d", encoder.HtmlEncode("d"));
Assert.Equal("�", encoder.HtmlEncode("\0")); // we still always encode control chars
Assert.Equal("&", encoder.HtmlEncode("&")); // we still always encode HTML-special chars
Assert.Equal("", encoder.HtmlEncode("\uFFFF")); // we still always encode non-chars and other forbidden chars
}
[Fact]
public void Ctor_WithUnicodeRanges()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.Latin1Supplement, UnicodeRanges.MiscellaneousSymbols);
// Act & assert
Assert.Equal("a", encoder.HtmlEncode("a"));
Assert.Equal("\u00E9", encoder.HtmlEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal("\u2601", encoder.HtmlEncode("\u2601" /* CLOUD */));
}
[Fact]
public void Ctor_WithNoParameters_DefaultsToBasicLatin()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
// Act & assert
Assert.Equal("a", encoder.HtmlEncode("a"));
Assert.Equal("é", encoder.HtmlEncode("\u00E9" /* LATIN SMALL LETTER E WITH ACUTE */));
Assert.Equal("☁", encoder.HtmlEncode("\u2601" /* CLOUD */));
}
[Fact]
public void Default_EquivalentToBasicLatin()
{
// Arrange
HtmlEncoder controlEncoder = new HtmlEncoder(UnicodeRanges.BasicLatin);
HtmlEncoder testEncoder = HtmlEncoder.Default;
// Act & assert
for (int i = 0; i <= char.MaxValue; i++)
{
if (!IsSurrogateCodePoint(i))
{
string input = new string((char)i, 1);
Assert.Equal(controlEncoder.HtmlEncode(input), testEncoder.HtmlEncode(input));
}
}
}
[Theory]
[InlineData("<", "<")]
[InlineData(">", ">")]
[InlineData("&", "&")]
[InlineData("'", "'")]
[InlineData("\"", """)]
[InlineData("+", "+")]
public void HtmlEncode_AllRangesAllowed_StillEncodesForbiddenChars_Simple(string input, string expected)
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All);
// Act
string retVal = encoder.HtmlEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void HtmlEncode_AllRangesAllowed_StillEncodesForbiddenChars_Extended()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All);
// Act & assert - BMP chars
for (int i = 0; i <= 0xFFFF; i++)
{
string input = new string((char)i, 1);
string expected;
if (IsSurrogateCodePoint(i))
{
expected = "\uFFFD"; // unpaired surrogate -> Unicode replacement char
}
else
{
if (input == "<") { expected = "<"; }
else if (input == ">") { expected = ">"; }
else if (input == "&") { expected = "&"; }
else if (input == "\"") { expected = """; }
else
{
bool mustEncode = false;
if (i == '\'' || i == '+')
{
mustEncode = true; // apostrophe, plus
}
else if (i <= 0x001F || (0x007F <= i && i <= 0x9F))
{
mustEncode = true; // control char
}
else if (!UnicodeHelpers.IsCharacterDefined((char)i))
{
mustEncode = true; // undefined (or otherwise disallowed) char
}
if (mustEncode)
{
expected = string.Format(CultureInfo.InvariantCulture, "&#x{0:X};", i);
}
else
{
expected = input; // no encoding
}
}
}
string retVal = encoder.HtmlEncode(input);
Assert.Equal(expected, retVal);
}
// Act & assert - astral chars
for (int i = 0x10000; i <= 0x10FFFF; i++)
{
string input = char.ConvertFromUtf32(i);
string expected = string.Format(CultureInfo.InvariantCulture, "&#x{0:X};", i);
string retVal = encoder.HtmlEncode(input);
Assert.Equal(expected, retVal);
}
}
[Fact]
public void HtmlEncode_BadSurrogates_ReturnsUnicodeReplacementChar()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder(UnicodeRanges.All); // allow all codepoints
// "a<unpaired leading>b<unpaired trailing>c<trailing before leading>d<unpaired trailing><valid>e<high at end of string>"
const string input = "a\uD800b\uDFFFc\uDFFF\uD800d\uDFFF\uD800\uDFFFe\uD800";
const string expected = "a\uFFFDb\uFFFDc\uFFFD\uFFFDd\uFFFD𐏿e\uFFFD";
// Act
string retVal = encoder.HtmlEncode(input);
// Assert
Assert.Equal(expected, retVal);
}
[Fact]
public void HtmlEncode_EmptyStringInput_ReturnsEmptyString()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
// Act & assert
Assert.Equal("", encoder.HtmlEncode(""));
}
[Fact]
public void HtmlEncode_InputDoesNotRequireEncoding_ReturnsOriginalStringInstance()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
string input = "Hello, there!";
// Act & assert
Assert.Same(input, encoder.HtmlEncode(input));
}
[Fact]
public void HtmlEncode_NullInput_Throws()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
Assert.Throws<ArgumentNullException>(() => { encoder.HtmlEncode(null); });
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingAtBeginning()
{
Assert.Equal("&Hello, there!", new HtmlEncoder().HtmlEncode("&Hello, there!"));
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingAtEnd()
{
Assert.Equal("Hello, there!&", new HtmlEncoder().HtmlEncode("Hello, there!&"));
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingInMiddle()
{
Assert.Equal("Hello, &there!", new HtmlEncoder().HtmlEncode("Hello, &there!"));
}
[Fact]
public void HtmlEncode_WithCharsRequiringEncodingInterspersed()
{
Assert.Equal("Hello, <there>!", new HtmlEncoder().HtmlEncode("Hello, <there>!"));
}
[Fact]
public void HtmlEncode_CharArray()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
var output = new StringWriter();
// Act
encoder.HtmlEncode("Hello+world!".ToCharArray(), 3, 5, output);
// Assert
Assert.Equal("lo+wo", output.ToString());
}
[Fact]
public void HtmlEncode_StringSubstring()
{
// Arrange
HtmlEncoder encoder = new HtmlEncoder();
var output = new StringWriter();
// Act
encoder.HtmlEncode("Hello+world!", 3, 5, output);
// Assert
Assert.Equal("lo+wo", output.ToString());
}
[Fact]
public void HtmlEncode_AstralWithTextWriter()
{
byte[] buffer = new byte[10];
MemoryStream ms = new MemoryStream(buffer);
using (StreamWriter sw = new StreamWriter(ms))
{
string input = "\U0010FFFF";
System.Text.Encodings.Web.HtmlEncoder.Default.Encode(sw, input);
}
Assert.Equal("", System.Text.Encoding.UTF8.GetString(buffer));
}
private static bool IsSurrogateCodePoint(int codePoint)
{
return (0xD800 <= codePoint && codePoint <= 0xDFFF);
}
}
}
| |
using UnityEngine.Rendering;
using UnityEngine.Profiling;
using System.Collections.Generic;
using System;
namespace UnityEngine.Experimental.Rendering
{
[Serializable]
public class ShadowSettings
{
public bool enabled;
public int shadowAtlasWidth;
public int shadowAtlasHeight;
public float maxShadowDistance;
public int directionalLightCascadeCount;
public Vector3 directionalLightCascades;
public float directionalLightNearPlaneOffset;
static ShadowSettings defaultShadowSettings = null;
public static ShadowSettings Default
{
get
{
if (defaultShadowSettings == null)
{
defaultShadowSettings = new ShadowSettings();
defaultShadowSettings.enabled = true;
defaultShadowSettings.shadowAtlasHeight = defaultShadowSettings.shadowAtlasWidth = 4096;
defaultShadowSettings.directionalLightCascadeCount = 1;
defaultShadowSettings.directionalLightCascades = new Vector3(0.05F, 0.2F, 0.3F);
defaultShadowSettings.directionalLightCascadeCount = 4;
defaultShadowSettings.directionalLightNearPlaneOffset = 5;
defaultShadowSettings.maxShadowDistance = 1000.0F;
}
return defaultShadowSettings;
}
}
}
public struct InputShadowLightData
{
public int lightIndex;
public int shadowResolution;
}
public struct ShadowLight
{
public int shadowSliceIndex;
public int shadowSliceCount;
}
public struct ShadowSliceData
{
public Matrix4x4 shadowTransform;
public int atlasX;
public int atlasY;
public int shadowResolution;
}
public struct ShadowOutput
{
public ShadowSliceData[] shadowSlices;
public ShadowLight[] shadowLights;
public Vector4[] directionalShadowSplitSphereSqr;
public int GetShadowSliceCountLightIndex(int lightIndex)
{
return shadowLights[lightIndex].shadowSliceCount;
}
public int GetShadowSliceIndex(int lightIndex, int sliceIndex)
{
if (sliceIndex >= shadowLights[lightIndex].shadowSliceCount)
throw new System.IndexOutOfRangeException();
return shadowLights[lightIndex].shadowSliceIndex + sliceIndex;
}
}
public struct ShadowRenderPass : IDisposable
{
ShadowSettings m_Settings;
[NonSerialized]
bool m_FailedToPackLastTime;
int m_ShadowTexName;
const int k_DepthBuffer = 24;
public int shadowTexName
{
get { return m_ShadowTexName; }
}
public ShadowRenderPass(ShadowSettings settings)
{
m_Settings = settings;
m_FailedToPackLastTime = false;
m_ShadowTexName = Shader.PropertyToID("g_tShadowBuffer");
}
public void Dispose()
{
}
struct AtlasEntry
{
public AtlasEntry(int splitIndex, int lightIndex)
{
this.splitIndex = splitIndex;
this.lightIndex = lightIndex;
}
public readonly int splitIndex;
public readonly int lightIndex;
}
int CalculateNumShadowSplits(int index, VisibleLight[] lights)
{
var lightType = lights[index].lightType;
switch (lightType)
{
case LightType.Spot:
return 1;
case LightType.Directional:
return m_Settings.directionalLightCascadeCount;
default:
return 6;
}
}
public static void ClearPackedShadows(VisibleLight[] lights, out ShadowOutput packedShadows)
{
packedShadows.directionalShadowSplitSphereSqr = null;
packedShadows.shadowSlices = null;
packedShadows.shadowLights = new ShadowLight[lights.Length];
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
bool AutoPackLightsIntoShadowTexture(List<InputShadowLightData> shadowLights, VisibleLight[] lights, out ShadowOutput packedShadows)
{
var activeShadowLights = new Dictionary<int, InputShadowLightData>();
var shadowIndices = new List<int>();
//@TODO: Disallow multiple directional lights
for (int i = 0; i < shadowLights.Count; i++)
{
shadowIndices.Add(shadowLights[i].lightIndex);
activeShadowLights[shadowLights[i].lightIndex] = shadowLights[i];
}
// World's stupidest sheet packer:
// 1. Sort all lights from largest to smallest
// 2. In a left->right, top->bottom pattern, fill quads until you reach the edge of the texture
// 3. Move position to x=0, y=bottomOfFirstTextureInThisRow
// 4. Goto 2.
// Yes, this will produce holes as the quads shrink, but it's good enough for now. I'll work on this more later to fill the gaps.
// Sort all lights from largest to smallest
shadowIndices.Sort(
delegate(int l1, int l2)
{
var nCompare = 0;
// Sort shadow-casting lights by shadow resolution
nCompare = activeShadowLights[l1].shadowResolution.CompareTo(activeShadowLights[l2].shadowResolution); // Sort by shadow size
if (nCompare == 0) // Same, so sort by range to stabilize sort results
nCompare = lights[l1].range.CompareTo(lights[l2].range); // Sort by shadow size
if (nCompare == 0) // Still same, so sort by instance ID to stabilize sort results
nCompare = lights[l1].light.GetInstanceID().CompareTo(lights[l2].light.GetInstanceID());
return nCompare;
}
);
// Start filling lights into texture
var requestedPages = new List<AtlasEntry>();
packedShadows.shadowLights = new ShadowLight[lights.Length];
for (int i = 0; i != shadowIndices.Count; i++)
{
var numShadowSplits = CalculateNumShadowSplits(shadowIndices[i], lights);
packedShadows.shadowLights[shadowIndices[i]].shadowSliceCount = numShadowSplits;
packedShadows.shadowLights[shadowIndices[i]].shadowSliceIndex = requestedPages.Count;
for (int s = 0; s < numShadowSplits; s++)
requestedPages.Add(new AtlasEntry(requestedPages.Count, shadowIndices[i]));
}
var nCurrentX = 0;
var nCurrentY = -1;
var nNextY = 0;
packedShadows.shadowSlices = new ShadowSliceData[requestedPages.Count];
packedShadows.directionalShadowSplitSphereSqr = new Vector4[4];
foreach (var entry in requestedPages)
{
var shadowResolution = activeShadowLights[entry.lightIndex].shadowResolution;
// Check if first texture is too wide
if (nCurrentY == -1)
{
if ((shadowResolution > m_Settings.shadowAtlasWidth) || (shadowResolution > m_Settings.shadowAtlasHeight))
{
Debug.LogError("ERROR! Shadow packer ran out of space in the " + m_Settings.shadowAtlasWidth + "x" + m_Settings.shadowAtlasHeight + " texture!\n\n");
m_FailedToPackLastTime = true;
ClearPackedShadows(lights, out packedShadows);
return false;
}
}
// Goto next scanline
if ((nCurrentY == -1) || ((nCurrentX + shadowResolution) > m_Settings.shadowAtlasWidth))
{
nCurrentX = 0;
nCurrentY = nNextY;
nNextY += shadowResolution;
}
// Check if we've run out of space
if ((nCurrentY + shadowResolution) > m_Settings.shadowAtlasHeight)
{
Debug.LogError("ERROR! Shadow packer ran out of space in the " + m_Settings.shadowAtlasWidth + "x" + m_Settings.shadowAtlasHeight + " texture!\n\n");
m_FailedToPackLastTime = true;
ClearPackedShadows(lights, out packedShadows);
return false;
}
// Save location to light
packedShadows.shadowSlices[entry.splitIndex].atlasX = nCurrentX;
packedShadows.shadowSlices[entry.splitIndex].atlasY = nCurrentY;
packedShadows.shadowSlices[entry.splitIndex].shadowResolution = shadowResolution;
// Move ahead
nCurrentX += shadowResolution;
//Debug.Log( "Sheet packer: " + vl.m_cachedLight.name + " ( " + vl.m_shadowX + ", " + vl.m_shadowY + " ) " + vl.m_shadowResolution + "\n\n" );
}
if (m_FailedToPackLastTime)
{
m_FailedToPackLastTime = false;
Debug.Log("SUCCESS! Shadow packer can now fit all lights into the " + m_Settings.shadowAtlasWidth + "x" + m_Settings.shadowAtlasHeight + " texture!\n\n");
}
return requestedPages.Count != 0;
}
static List<InputShadowLightData> GetInputShadowLightData(CullResults cullResults)
{
var shadowCasters = new List<InputShadowLightData>();
var lights = cullResults.visibleLights;
int directionalLightCount = 0;
for (int i = 0; i < lights.Length; i++)
{
//@TODO: ignore baked. move this logic to c++...
if (lights[i].light.shadows == LightShadows.None)
continue;
// Only a single directional shadow casting light is supported
if (lights[i].lightType == LightType.Directional)
{
directionalLightCount++;
if (directionalLightCount != 1)
continue;
}
AdditionalLightData additionalLight = lights[i].light.GetComponent<AdditionalLightData>();
InputShadowLightData light;
light.lightIndex = i;
light.shadowResolution = AdditionalLightData.GetShadowResolution(additionalLight);
shadowCasters.Add(light);
}
return shadowCasters;
}
public void UpdateCullingParameters(ref CullingParameters parameters)
{
parameters.shadowDistance = Mathf.Min(m_Settings.maxShadowDistance, parameters.shadowDistance);
}
public void Render(ScriptableRenderContext loop, CullResults cullResults, out ShadowOutput packedShadows)
{
if (!m_Settings.enabled)
{
ClearPackedShadows(cullResults.visibleLights, out packedShadows);
return;
}
// Pack all shadow quads into the texture
if (!AutoPackLightsIntoShadowTexture(GetInputShadowLightData(cullResults), cullResults.visibleLights, out packedShadows))
{
// No shadowing lights found, so skip all rendering
return;
}
RenderPackedShadows(loop, cullResults, ref packedShadows);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
// Render shadows
//---------------------------------------------------------------------------------------------------------------------------------------------------
void RenderPackedShadows(ScriptableRenderContext loop, CullResults cullResults, ref ShadowOutput packedShadows)
{
var setRenderTargetCommandBuffer = new CommandBuffer();
setRenderTargetCommandBuffer.name = "Render packed shadows";
setRenderTargetCommandBuffer.GetTemporaryRT(m_ShadowTexName, m_Settings.shadowAtlasWidth, m_Settings.shadowAtlasHeight, k_DepthBuffer, FilterMode.Bilinear, RenderTextureFormat.Shadowmap, RenderTextureReadWrite.Linear);
setRenderTargetCommandBuffer.SetRenderTarget(new RenderTargetIdentifier(m_ShadowTexName));
setRenderTargetCommandBuffer.ClearRenderTarget(true, true, Color.green);
loop.ExecuteCommandBuffer(setRenderTargetCommandBuffer);
setRenderTargetCommandBuffer.Dispose();
VisibleLight[] visibleLights = cullResults.visibleLights;
var shadowSlices = packedShadows.shadowSlices;
// Render each light's shadow buffer into a subrect of the shared depth texture
for (int lightIndex = 0; lightIndex < packedShadows.shadowLights.Length; lightIndex++)
{
int shadowSliceCount = packedShadows.shadowLights[lightIndex].shadowSliceCount;
if (shadowSliceCount == 0)
continue;
Profiler.BeginSample("Shadows.GetShadowCasterBounds");
Bounds bounds;
if (!cullResults.GetShadowCasterBounds(lightIndex, out bounds))
{
Profiler.EndSample();
continue;
}
Profiler.EndSample();
Profiler.BeginSample("Shadows.DrawShadows");
Matrix4x4 proj;
Matrix4x4 view;
var lightType = visibleLights[lightIndex].lightType;
var lightDirection = visibleLights[lightIndex].light.transform.forward;
int shadowSliceIndex = packedShadows.GetShadowSliceIndex(lightIndex, 0);
if (lightType == LightType.Spot)
{
var settings = new DrawShadowsSettings(cullResults, lightIndex);
bool needRendering = cullResults.ComputeSpotShadowMatricesAndCullingPrimitives(lightIndex, out view, out proj, out settings.splitData);
SetupShadowSplitMatrices(ref packedShadows.shadowSlices[shadowSliceIndex], proj, view);
if (needRendering)
RenderShadowSplit(ref shadowSlices[shadowSliceIndex], lightDirection, proj, view, ref loop, settings);
}
else if (lightType == LightType.Directional)
{
Vector3 splitRatio = m_Settings.directionalLightCascades;
for (int s = 0; s < 4; ++s)
packedShadows.directionalShadowSplitSphereSqr[s] = new Vector4(0, 0, 0, float.NegativeInfinity);
for (int s = 0; s < shadowSliceCount; ++s, shadowSliceIndex++)
{
var settings = new DrawShadowsSettings(cullResults, lightIndex);
var shadowResolution = shadowSlices[shadowSliceIndex].shadowResolution;
bool needRendering = cullResults.ComputeDirectionalShadowMatricesAndCullingPrimitives(lightIndex, s, shadowSliceCount, splitRatio,
shadowResolution, m_Settings.directionalLightNearPlaneOffset, out view, out proj, out settings.splitData);
packedShadows.directionalShadowSplitSphereSqr[s] = settings.splitData.cullingSphere;
packedShadows.directionalShadowSplitSphereSqr[s].w *= packedShadows.directionalShadowSplitSphereSqr[s].w;
SetupShadowSplitMatrices(ref shadowSlices[shadowSliceIndex], proj, view);
if (needRendering)
RenderShadowSplit(ref shadowSlices[shadowSliceIndex], lightDirection, proj, view, ref loop, settings);
}
}
else if (lightType == LightType.Point)
{
for (int s = 0; s < shadowSliceCount; ++s, shadowSliceIndex++)
{
var settings = new DrawShadowsSettings(cullResults, lightIndex);
bool needRendering = cullResults.ComputePointShadowMatricesAndCullingPrimitives(lightIndex, (CubemapFace)s, 2.0f, out view, out proj, out settings.splitData);
// The view matrix for point lights flips primitives. We fix it here (by making it left-handed).
view.SetRow(1, -view.GetRow(1));
SetupShadowSplitMatrices(ref shadowSlices[shadowSliceIndex], proj, view);
if (needRendering)
RenderShadowSplit(ref shadowSlices[shadowSliceIndex], lightDirection, proj, view, ref loop, settings);
}
}
Profiler.EndSample();
}
}
private void SetupShadowSplitMatrices(ref ShadowSliceData lightData, Matrix4x4 proj, Matrix4x4 view)
{
var matScaleBias = Matrix4x4.identity;
matScaleBias.m00 = 0.5f;
matScaleBias.m11 = 0.5f;
matScaleBias.m22 = 0.5f;
matScaleBias.m03 = 0.5f;
matScaleBias.m13 = 0.5f;
matScaleBias.m23 = 0.5f;
var matTile = Matrix4x4.identity;
matTile.m00 = (float)lightData.shadowResolution / (float)m_Settings.shadowAtlasWidth;
matTile.m11 = (float)lightData.shadowResolution / (float)m_Settings.shadowAtlasHeight;
matTile.m03 = (float)lightData.atlasX / (float)m_Settings.shadowAtlasWidth;
matTile.m13 = (float)lightData.atlasY / (float)m_Settings.shadowAtlasHeight;
lightData.shadowTransform = matTile * matScaleBias * proj * view;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
private void RenderShadowSplit(ref ShadowSliceData slice, Vector3 lightDirection, Matrix4x4 proj, Matrix4x4 view, ref ScriptableRenderContext loop, DrawShadowsSettings settings)
{
var commandBuffer = new CommandBuffer { name = "ShadowSetup" };
// Set viewport / matrices etc
commandBuffer.SetViewport(new Rect(slice.atlasX, slice.atlasY, slice.shadowResolution, slice.shadowResolution));
//commandBuffer.ClearRenderTarget (true, true, Color.green);
commandBuffer.SetGlobalVector("g_vLightDirWs", new Vector4(lightDirection.x, lightDirection.y, lightDirection.z));
commandBuffer.SetViewProjectionMatrices(view, proj);
// commandBuffer.SetGlobalDepthBias (1.0F, 1.0F);
loop.ExecuteCommandBuffer(commandBuffer);
commandBuffer.Dispose();
// Render
loop.DrawShadows(ref settings);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using Xunit;
namespace System.Net.Http.Tests
{
public class CacheControlHeaderValueTest
{
[Fact]
public void Properties_SetAndGetAllProperties_SetValueReturnedInGetter()
{
CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
// Bool properties
cacheControl.NoCache = true;
Assert.True(cacheControl.NoCache);
cacheControl.NoStore = true;
Assert.True(cacheControl.NoStore);
cacheControl.MaxStale = true;
Assert.True(cacheControl.MaxStale);
cacheControl.NoTransform = true;
Assert.True(cacheControl.NoTransform);
cacheControl.OnlyIfCached = true;
Assert.True(cacheControl.OnlyIfCached);
cacheControl.Public = true;
Assert.True(cacheControl.Public);
cacheControl.Private = true;
Assert.True(cacheControl.Private);
cacheControl.MustRevalidate = true;
Assert.True(cacheControl.MustRevalidate);
cacheControl.ProxyRevalidate = true;
Assert.True(cacheControl.ProxyRevalidate);
// TimeSpan properties
TimeSpan timeSpan = new TimeSpan(1, 2, 3);
cacheControl.MaxAge = timeSpan;
Assert.Equal(timeSpan, cacheControl.MaxAge);
cacheControl.SharedMaxAge = timeSpan;
Assert.Equal(timeSpan, cacheControl.SharedMaxAge);
cacheControl.MaxStaleLimit = timeSpan;
Assert.Equal(timeSpan, cacheControl.MaxStaleLimit);
cacheControl.MinFresh = timeSpan;
Assert.Equal(timeSpan, cacheControl.MinFresh);
// String collection properties
Assert.NotNull(cacheControl.NoCacheHeaders);
Assert.Throws<ArgumentException>(() => { cacheControl.NoCacheHeaders.Add(null); });
Assert.Throws<FormatException>(() => { cacheControl.NoCacheHeaders.Add("invalid token"); });
cacheControl.NoCacheHeaders.Add("token");
Assert.Equal(1, cacheControl.NoCacheHeaders.Count);
Assert.Equal("token", cacheControl.NoCacheHeaders.First());
Assert.NotNull(cacheControl.PrivateHeaders);
Assert.Throws<ArgumentException>(() => { cacheControl.PrivateHeaders.Add(null); });
Assert.Throws<FormatException>(() => { cacheControl.PrivateHeaders.Add("invalid token"); });
cacheControl.PrivateHeaders.Add("token");
Assert.Equal(1, cacheControl.PrivateHeaders.Count);
Assert.Equal("token", cacheControl.PrivateHeaders.First());
// NameValueHeaderValue collection property
Assert.NotNull(cacheControl.Extensions);
Assert.Throws<ArgumentNullException>(() => { cacheControl.Extensions.Add(null); });
cacheControl.Extensions.Add(new NameValueHeaderValue("name", "value"));
Assert.Equal(1, cacheControl.Extensions.Count);
Assert.Equal(new NameValueHeaderValue("name", "value"), cacheControl.Extensions.First());
}
[Fact]
public void ToString_UseRequestDirectiveValues_AllSerializedCorrectly()
{
CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
Assert.Equal("", cacheControl.ToString());
// Note that we allow all combinations of all properties even though the RFC specifies rules what value
// can be used together.
// Also for property pairs (bool property + collection property) like 'NoCache' and 'NoCacheHeaders' the
// caller needs to set the bool property in order for the collection to be populated as string.
// Cache Request Directive sample
cacheControl.NoStore = true;
Assert.Equal("no-store", cacheControl.ToString());
cacheControl.NoCache = true;
Assert.Equal("no-store, no-cache", cacheControl.ToString());
cacheControl.MaxAge = new TimeSpan(0, 1, 10);
Assert.Equal("no-store, no-cache, max-age=70", cacheControl.ToString());
cacheControl.MaxStale = true;
Assert.Equal("no-store, no-cache, max-age=70, max-stale", cacheControl.ToString());
cacheControl.MaxStaleLimit = new TimeSpan(0, 2, 5);
Assert.Equal("no-store, no-cache, max-age=70, max-stale=125", cacheControl.ToString());
cacheControl.MinFresh = new TimeSpan(0, 3, 0);
Assert.Equal("no-store, no-cache, max-age=70, max-stale=125, min-fresh=180", cacheControl.ToString());
cacheControl = new CacheControlHeaderValue();
cacheControl.NoTransform = true;
Assert.Equal("no-transform", cacheControl.ToString());
cacheControl.OnlyIfCached = true;
Assert.Equal("no-transform, only-if-cached", cacheControl.ToString());
cacheControl.Extensions.Add(new NameValueHeaderValue("custom"));
cacheControl.Extensions.Add(new NameValueHeaderValue("customName", "customValue"));
Assert.Equal("no-transform, only-if-cached, custom, customName=customValue", cacheControl.ToString());
cacheControl = new CacheControlHeaderValue();
cacheControl.Extensions.Add(new NameValueHeaderValue("custom"));
Assert.Equal("custom", cacheControl.ToString());
}
[Fact]
public void ToString_UseResponseDirectiveValues_AllSerializedCorrectly()
{
CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();
Assert.Equal("", cacheControl.ToString());
cacheControl.NoCache = true;
Assert.Equal("no-cache", cacheControl.ToString());
cacheControl.NoCacheHeaders.Add("token1");
Assert.Equal("no-cache=\"token1\"", cacheControl.ToString());
cacheControl.Public = true;
Assert.Equal("public, no-cache=\"token1\"", cacheControl.ToString());
cacheControl = new CacheControlHeaderValue();
cacheControl.Private = true;
Assert.Equal("private", cacheControl.ToString());
cacheControl.PrivateHeaders.Add("token2");
cacheControl.PrivateHeaders.Add("token3");
Assert.Equal("private=\"token2, token3\"", cacheControl.ToString());
cacheControl.MustRevalidate = true;
Assert.Equal("must-revalidate, private=\"token2, token3\"", cacheControl.ToString());
cacheControl.ProxyRevalidate = true;
Assert.Equal("must-revalidate, proxy-revalidate, private=\"token2, token3\"", cacheControl.ToString());
}
[Fact]
public void GetHashCode_CompareValuesWithBoolFieldsSet_MatchExpectation()
{
// Verify that different bool fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[9];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].ProxyRevalidate = true;
values[1].NoCache = true;
values[2].NoStore = true;
values[3].MaxStale = true;
values[4].NoTransform = true;
values[5].OnlyIfCached = true;
values[6].Public = true;
values[7].Private = true;
values[8].MustRevalidate = true;
// Only one bool field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareHashCodes(values[i], values[j], false);
}
}
}
// Validate that two instances with the same bool fields set are equal.
values[0].NoCache = true;
CompareHashCodes(values[0], values[1], false);
values[1].ProxyRevalidate = true;
CompareHashCodes(values[0], values[1], true);
}
[Fact]
public void GetHashCode_CompareValuesWithTimeSpanFieldsSet_MatchExpectation()
{
// Verify that different timespan fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[4];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 1);
values[2].MinFresh = new TimeSpan(0, 1, 1);
values[3].SharedMaxAge = new TimeSpan(0, 1, 1);
// Only one timespan field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareHashCodes(values[i], values[j], false);
}
}
}
values[0].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareHashCodes(values[0], values[1], false);
values[1].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareHashCodes(values[0], values[1], true);
}
[Fact]
public void GetHashCode_CompareCollectionFieldsSet_MatchExpectation()
{
CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue();
cacheControl1.NoCache = true;
cacheControl1.NoCacheHeaders.Add("token2");
cacheControl2.NoCache = true;
cacheControl2.NoCacheHeaders.Add("token1");
cacheControl2.NoCacheHeaders.Add("token2");
CompareHashCodes(cacheControl1, cacheControl2, false);
cacheControl1.NoCacheHeaders.Add("token1");
CompareHashCodes(cacheControl1, cacheControl2, true);
// Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders
// have the same values, the hash code will be different.
cacheControl3.Private = true;
cacheControl3.PrivateHeaders.Add("token2");
CompareHashCodes(cacheControl1, cacheControl3, false);
cacheControl4.Extensions.Add(new NameValueHeaderValue("custom"));
CompareHashCodes(cacheControl1, cacheControl4, false);
cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
cacheControl5.Extensions.Add(new NameValueHeaderValue("custom"));
CompareHashCodes(cacheControl4, cacheControl5, false);
cacheControl4.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
CompareHashCodes(cacheControl4, cacheControl5, true);
}
[Fact]
public void Equals_CompareValuesWithBoolFieldsSet_MatchExpectation()
{
// Verify that different bool fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[9];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].ProxyRevalidate = true;
values[1].NoCache = true;
values[2].NoStore = true;
values[3].MaxStale = true;
values[4].NoTransform = true;
values[5].OnlyIfCached = true;
values[6].Public = true;
values[7].Private = true;
values[8].MustRevalidate = true;
// Only one bool field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareValues(values[i], values[j], false);
}
}
}
// Validate that two instances with the same bool fields set are equal.
values[0].NoCache = true;
CompareValues(values[0], values[1], false);
values[1].ProxyRevalidate = true;
CompareValues(values[0], values[1], true);
}
[Fact]
public void Equals_CompareValuesWithTimeSpanFieldsSet_MatchExpectation()
{
// Verify that different timespan fields return different hash values.
CacheControlHeaderValue[] values = new CacheControlHeaderValue[4];
for (int i = 0; i < values.Length; i++)
{
values[i] = new CacheControlHeaderValue();
}
values[0].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 1);
values[2].MinFresh = new TimeSpan(0, 1, 1);
values[3].SharedMaxAge = new TimeSpan(0, 1, 1);
// Only one timespan field set. All hash codes should differ
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
if (i != j)
{
CompareValues(values[i], values[j], false);
}
}
}
values[0].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareValues(values[0], values[1], false);
values[1].MaxAge = new TimeSpan(0, 1, 1);
values[1].MaxStaleLimit = new TimeSpan(0, 1, 2);
CompareValues(values[0], values[1], true);
CacheControlHeaderValue value1 = new CacheControlHeaderValue();
value1.MaxStale = true;
CacheControlHeaderValue value2 = new CacheControlHeaderValue();
value2.MaxStale = true;
CompareValues(value1, value2, true);
value2.MaxStaleLimit = new TimeSpan(1, 2, 3);
CompareValues(value1, value2, false);
}
[Fact]
public void Equals_CompareCollectionFieldsSet_MatchExpectation()
{
CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue();
CacheControlHeaderValue cacheControl6 = new CacheControlHeaderValue();
cacheControl1.NoCache = true;
cacheControl1.NoCacheHeaders.Add("token2");
Assert.False(cacheControl1.Equals(null), "Compare with 'null'");
cacheControl2.NoCache = true;
cacheControl2.NoCacheHeaders.Add("token1");
cacheControl2.NoCacheHeaders.Add("token2");
CompareValues(cacheControl1, cacheControl2, false);
cacheControl1.NoCacheHeaders.Add("token1");
CompareValues(cacheControl1, cacheControl2, true);
// Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders
// have the same values, the hash code will be different.
cacheControl3.Private = true;
cacheControl3.PrivateHeaders.Add("token2");
CompareValues(cacheControl1, cacheControl3, false);
cacheControl4.Private = true;
cacheControl4.PrivateHeaders.Add("token3");
CompareValues(cacheControl3, cacheControl4, false);
cacheControl5.Extensions.Add(new NameValueHeaderValue("custom"));
CompareValues(cacheControl1, cacheControl5, false);
cacheControl6.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
cacheControl6.Extensions.Add(new NameValueHeaderValue("custom"));
CompareValues(cacheControl5, cacheControl6, false);
cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
CompareValues(cacheControl5, cacheControl6, true);
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
CacheControlHeaderValue source = new CacheControlHeaderValue();
source.Extensions.Add(new NameValueHeaderValue("custom"));
source.Extensions.Add(new NameValueHeaderValue("customN", "customV"));
source.MaxAge = new TimeSpan(1, 1, 1);
source.MaxStale = true;
source.MaxStaleLimit = new TimeSpan(1, 1, 2);
source.MinFresh = new TimeSpan(1, 1, 3);
source.MustRevalidate = true;
source.NoCache = true;
source.NoCacheHeaders.Add("token1");
source.NoStore = true;
source.NoTransform = true;
source.OnlyIfCached = true;
source.Private = true;
source.PrivateHeaders.Add("token2");
source.ProxyRevalidate = true;
source.Public = true;
source.SharedMaxAge = new TimeSpan(1, 1, 4);
CacheControlHeaderValue clone = (CacheControlHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source, clone);
}
[Fact]
public void GetCacheControlLength_DifferentValidScenariosAndNoExistingCacheControl_AllReturnNonZero()
{
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoCache = true;
CheckGetCacheControlLength("X , , no-cache ,,", 1, null, 16, expected);
expected = new CacheControlHeaderValue();
expected.NoCache = true;
expected.NoCacheHeaders.Add("token1");
expected.NoCacheHeaders.Add("token2");
CheckGetCacheControlLength("no-cache=\"token1, token2\"", 0, null, 25, expected);
expected = new CacheControlHeaderValue();
expected.NoStore = true;
expected.MaxAge = new TimeSpan(0, 0, 125);
expected.MaxStale = true;
CheckGetCacheControlLength("X no-store , max-age = 125, max-stale,", 1, null, 37, expected);
expected = new CacheControlHeaderValue();
expected.MinFresh = new TimeSpan(0, 0, 123);
expected.NoTransform = true;
expected.OnlyIfCached = true;
expected.Extensions.Add(new NameValueHeaderValue("custom"));
CheckGetCacheControlLength("min-fresh=123, no-transform, only-if-cached, custom", 0, null, 51, expected);
expected = new CacheControlHeaderValue();
expected.Public = true;
expected.Private = true;
expected.PrivateHeaders.Add("token1");
expected.MustRevalidate = true;
expected.ProxyRevalidate = true;
expected.Extensions.Add(new NameValueHeaderValue("c", "d"));
expected.Extensions.Add(new NameValueHeaderValue("a", "b"));
CheckGetCacheControlLength(",public, , private=\"token1\", must-revalidate, c=d, proxy-revalidate, a=b", 0,
null, 72, expected);
expected = new CacheControlHeaderValue();
expected.Private = true;
expected.SharedMaxAge = new TimeSpan(0, 0, 1234567890);
expected.MaxAge = new TimeSpan(0, 0, 987654321);
CheckGetCacheControlLength("s-maxage=1234567890, private, max-age = 987654321,", 0, null, 50, expected);
}
[Fact]
public void GetCacheControlLength_DifferentValidScenariosAndExistingCacheControl_AllReturnNonZero()
{
CacheControlHeaderValue storeValue = new CacheControlHeaderValue();
storeValue.NoStore = true;
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoCache = true;
expected.NoStore = true;
CheckGetCacheControlLength("X no-cache", 1, storeValue, 9, expected);
storeValue = new CacheControlHeaderValue();
storeValue.Private = true;
storeValue.PrivateHeaders.Add("token1");
storeValue.NoCache = true;
expected.NoCacheHeaders.Add("token1");
expected.NoCacheHeaders.Clear(); // just make sure we have an assigned (empty) collection.
expected = new CacheControlHeaderValue();
expected.Private = true;
expected.PrivateHeaders.Add("token1");
expected.PrivateHeaders.Add("token2");
expected.NoCache = true;
expected.NoCacheHeaders.Add("token1");
expected.NoCacheHeaders.Add("token2");
CheckGetCacheControlLength("private=\"token2\", no-cache=\"token1, , token2,\"", 0, storeValue, 46,
expected);
storeValue = new CacheControlHeaderValue();
storeValue.Extensions.Add(new NameValueHeaderValue("x", "y"));
storeValue.NoTransform = true;
storeValue.OnlyIfCached = true;
expected = new CacheControlHeaderValue();
expected.Public = true;
expected.Private = true;
expected.PrivateHeaders.Add("token1");
expected.MustRevalidate = true;
expected.ProxyRevalidate = true;
expected.NoTransform = true;
expected.OnlyIfCached = true;
expected.Extensions.Add(new NameValueHeaderValue("a", "\"b\""));
expected.Extensions.Add(new NameValueHeaderValue("c", "d"));
expected.Extensions.Add(new NameValueHeaderValue("x", "y")); // from store result
CheckGetCacheControlLength(",public, , private=\"token1\", must-revalidate, c=d, proxy-revalidate, a=\"b\"",
0, storeValue, 74, expected);
storeValue = new CacheControlHeaderValue();
storeValue.MaxStale = true;
storeValue.MinFresh = new TimeSpan(1, 2, 3);
expected = new CacheControlHeaderValue();
expected.MaxStale = true;
expected.MaxStaleLimit = new TimeSpan(0, 0, 5);
expected.MinFresh = new TimeSpan(0, 0, 10); // note that the last header value overwrites existing ones
CheckGetCacheControlLength(" ,,max-stale=5,,min-fresh = 10,,", 0, storeValue, 33, expected);
storeValue = new CacheControlHeaderValue();
storeValue.SharedMaxAge = new TimeSpan(1, 2, 3);
storeValue.NoTransform = true;
expected = new CacheControlHeaderValue();
expected.SharedMaxAge = new TimeSpan(1, 2, 3);
expected.NoTransform = true;
}
[Fact]
public void GetCacheControlLength_DifferentInvalidScenarios_AllReturnZero()
{
// Token-only values
CheckInvalidCacheControlLength("no-store=15", 0);
CheckInvalidCacheControlLength("no-store=", 0);
CheckInvalidCacheControlLength("no-transform=a", 0);
CheckInvalidCacheControlLength("no-transform=", 0);
CheckInvalidCacheControlLength("only-if-cached=\"x\"", 0);
CheckInvalidCacheControlLength("only-if-cached=", 0);
CheckInvalidCacheControlLength("public=\"x\"", 0);
CheckInvalidCacheControlLength("public=", 0);
CheckInvalidCacheControlLength("must-revalidate=\"1\"", 0);
CheckInvalidCacheControlLength("must-revalidate=", 0);
CheckInvalidCacheControlLength("proxy-revalidate=x", 0);
CheckInvalidCacheControlLength("proxy-revalidate=", 0);
// Token with optional field-name list
CheckInvalidCacheControlLength("no-cache=", 0);
CheckInvalidCacheControlLength("no-cache=token", 0);
CheckInvalidCacheControlLength("no-cache=\"token", 0);
CheckInvalidCacheControlLength("no-cache=\"\"", 0); // at least one token expected as value
CheckInvalidCacheControlLength("private=", 0);
CheckInvalidCacheControlLength("private=token", 0);
CheckInvalidCacheControlLength("private=\"token", 0);
CheckInvalidCacheControlLength("private=\",\"", 0); // at least one token expected as value
CheckInvalidCacheControlLength("private=\"=\"", 0);
// Token with delta-seconds value
CheckInvalidCacheControlLength("max-age", 0);
CheckInvalidCacheControlLength("max-age=", 0);
CheckInvalidCacheControlLength("max-age=a", 0);
CheckInvalidCacheControlLength("max-age=\"1\"", 0);
CheckInvalidCacheControlLength("max-age=1.5", 0);
CheckInvalidCacheControlLength("max-stale=", 0);
CheckInvalidCacheControlLength("max-stale=a", 0);
CheckInvalidCacheControlLength("max-stale=\"1\"", 0);
CheckInvalidCacheControlLength("max-stale=1.5", 0);
CheckInvalidCacheControlLength("min-fresh", 0);
CheckInvalidCacheControlLength("min-fresh=", 0);
CheckInvalidCacheControlLength("min-fresh=a", 0);
CheckInvalidCacheControlLength("min-fresh=\"1\"", 0);
CheckInvalidCacheControlLength("min-fresh=1.5", 0);
CheckInvalidCacheControlLength("s-maxage", 0);
CheckInvalidCacheControlLength("s-maxage=", 0);
CheckInvalidCacheControlLength("s-maxage=a", 0);
CheckInvalidCacheControlLength("s-maxage=\"1\"", 0);
CheckInvalidCacheControlLength("s-maxage=1.5", 0);
// Invalid Extension values
CheckInvalidCacheControlLength("custom=", 0);
CheckInvalidCacheControlLength("custom value", 0);
CheckInvalidCacheControlLength(null, 0);
CheckInvalidCacheControlLength("", 0);
CheckInvalidCacheControlLength("", 1);
}
[Fact]
public void Parse_SetOfValidValueStrings_ParsedCorrectly()
{
// Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue.
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoStore = true;
expected.MinFresh = new TimeSpan(0, 2, 3);
CheckValidParse(" , no-store, min-fresh=123", expected);
expected = new CacheControlHeaderValue();
expected.MaxStale = true;
expected.NoCache = true;
expected.NoCacheHeaders.Add("t");
CheckValidParse("max-stale, no-cache=\"t\", ,,", expected);
}
[Fact]
public void Parse_SetOfInvalidValueStrings_Throws()
{
CheckInvalidParse("no-cache,=", 0);
CheckInvalidParse("max-age=123x", 0);
CheckInvalidParse("=no-cache", 0);
CheckInvalidParse("no-cache no-store", 0);
CheckInvalidParse("invalid =", 0);
CheckInvalidParse("\u4F1A", 0);
}
[Fact]
public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
{
// Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue.
CacheControlHeaderValue expected = new CacheControlHeaderValue();
expected.NoStore = true;
expected.MinFresh = new TimeSpan(0, 2, 3);
CheckValidTryParse(" , no-store, min-fresh=123", expected);
expected = new CacheControlHeaderValue();
expected.MaxStale = true;
expected.NoCache = true;
expected.NoCacheHeaders.Add("t");
CheckValidTryParse("max-stale, no-cache=\"t\", ,,", expected);
}
[Fact]
public void TryParse_SetOfInvalidValueStrings_ReturnsFalse()
{
CheckInvalidTryParse("no-cache,=", 0);
CheckInvalidTryParse("max-age=123x", 0);
CheckInvalidTryParse("=no-cache", 0);
CheckInvalidTryParse("no-cache no-store", 0);
CheckInvalidTryParse("invalid =", 0);
CheckInvalidTryParse("\u4F1A", 0);
}
#region Helper methods
private void CompareHashCodes(CacheControlHeaderValue x, CacheControlHeaderValue y, bool areEqual)
{
if (areEqual)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
}
else
{
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
}
}
private void CompareValues(CacheControlHeaderValue x, CacheControlHeaderValue y, bool areEqual)
{
Assert.Equal(areEqual, x.Equals(y));
Assert.Equal(areEqual, y.Equals(x));
}
private static void CheckGetCacheControlLength(string input, int startIndex, CacheControlHeaderValue storeValue,
int expectedLength, CacheControlHeaderValue expectedResult)
{
CacheControlHeaderValue result = null;
Assert.Equal(expectedLength, CacheControlHeaderValue.GetCacheControlLength(input, startIndex, storeValue, out result));
if (storeValue == null)
{
Assert.Equal(expectedResult, result);
}
else
{
// If we provide a 'storeValue', then that instance will be updated and result will be 'null'
Assert.Null(result);
Assert.Equal(expectedResult, storeValue);
}
}
private static void CheckInvalidCacheControlLength(string input, int startIndex)
{
CacheControlHeaderValue result = null;
Assert.Equal(0, CacheControlHeaderValue.GetCacheControlLength(input, startIndex, null, out result));
Assert.Null(result);
}
private void CheckValidParse(string input, CacheControlHeaderValue expectedResult)
{
CacheControlHeaderValue result = CacheControlHeaderValue.Parse(input);
Assert.Equal(expectedResult, result);
}
private void CheckInvalidParse(string input, int startIndex)
{
Assert.Throws<FormatException>(() => { CacheControlHeaderValue.Parse(input); });
}
private void CheckValidTryParse(string input, CacheControlHeaderValue expectedResult)
{
CacheControlHeaderValue result = null;
Assert.True(CacheControlHeaderValue.TryParse(input, out result));
Assert.Equal(expectedResult, result);
}
private void CheckInvalidTryParse(string input, int startIndex)
{
CacheControlHeaderValue result = null;
Assert.False(CacheControlHeaderValue.TryParse(input, out result));
Assert.Null(result);
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
using NPOI.Util;
namespace NPOI.SS.Formula.Functions
{
using System;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula;
/*
* Implementation for the Excel function SUMPRODUCT<p/>
*
* Syntax : <br/>
* SUMPRODUCT ( array1[, array2[, array3[, ...]]])
* <table border="0" cellpAdding="1" cellspacing="0" summary="Parameter descriptions">
* <tr><th>array1, ... arrayN </th><td>typically area references,
* possibly cell references or scalar values</td></tr>
* </table><br/>
*
* Let A<b>n</b><sub>(<b>i</b>,<b>j</b>)</sub> represent the element in the <b>i</b>th row <b>j</b>th column
* of the <b>n</b>th array<br/>
* Assuming each array has the same dimensions (W, H), the result Is defined as:<br/>
* SUMPRODUCT = Σ<sub><b>i</b>: 1..H</sub>
* ( Σ<sub><b>j</b>: 1..W</sub>
* ( Π<sub><b>n</b>: 1..N</sub>
* A<b>n</b><sub>(<b>i</b>,<b>j</b>)</sub>
* )
* )
*
* @author Josh Micich
*/
public class Sumproduct : Function
{
public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol)
{
int maxN = args.Length;
if (maxN < 1)
{
return ErrorEval.VALUE_INVALID;
}
ValueEval firstArg = args[0];
try
{
if (firstArg is NumericValueEval)
{
return EvaluateSingleProduct(args);
}
if (firstArg is RefEval)
{
return EvaluateSingleProduct(args);
}
if (firstArg is TwoDEval)
{
TwoDEval ae = (TwoDEval)firstArg;
if (ae.IsRow && ae.IsColumn)
{
return EvaluateSingleProduct(args);
}
return EvaluateAreaSumProduct(args);
}
}
catch (EvaluationException e)
{
return e.GetErrorEval();
}
throw new RuntimeException("Invalid arg type for SUMPRODUCT: ("
+ firstArg.GetType().Name + ")");
}
private ValueEval EvaluateSingleProduct(ValueEval[] evalArgs)
{
int maxN = evalArgs.Length;
double term = 1D;
for (int n = 0; n < maxN; n++)
{
double val = GetScalarValue(evalArgs[n]);
term *= val;
}
return new NumberEval(term);
}
private static double GetScalarValue(ValueEval arg)
{
ValueEval eval;
if (arg is RefEval)
{
RefEval re = (RefEval)arg;
if (re.NumberOfSheets > 1)
{
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
eval = re.GetInnerValueEval(re.FirstSheetIndex);
}
else
{
eval = arg;
}
if (eval == null)
{
throw new ArgumentException("parameter may not be null");
}
if (eval is AreaEval)
{
AreaEval ae = (AreaEval)eval;
// an area ref can work as a scalar value if it is 1x1
if (!ae.IsColumn || !ae.IsRow)
{
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
eval = ae.GetRelativeValue(0, 0);
}
if (!(eval is ValueEval))
{
throw new ArgumentException("Unexpected value eval class ("
+ eval.GetType().Name + ")");
}
return GetProductTerm((ValueEval)eval, true);
}
private ValueEval EvaluateAreaSumProduct(ValueEval[] evalArgs)
{
int maxN = evalArgs.Length;
AreaEval[] args = new AreaEval[maxN];
try
{
Array.Copy(evalArgs, 0, args, 0, maxN);
}
catch (Exception)
{
// one of the other args was not an AreaRef
return ErrorEval.VALUE_INVALID;
}
AreaEval firstArg = args[0];
int height = firstArg.LastRow - firstArg.FirstRow + 1;
int width = firstArg.LastColumn - firstArg.FirstColumn + 1; // TODO - junit
// first check dimensions
if (!AreasAllSameSize(args, height, width))
{
// normally this results in #VALUE!,
// but errors in individual cells take precedence
for (int i = 1; i < args.Length; i++)
{
ThrowFirstError(args[i]);
}
return ErrorEval.VALUE_INVALID;
}
double acc = 0;
for (int rrIx = 0; rrIx < height; rrIx++)
{
for (int rcIx = 0; rcIx < width; rcIx++)
{
double term = 1D;
for (int n = 0; n < maxN; n++)
{
double val = GetProductTerm(args[n].GetRelativeValue(rrIx, rcIx), false);
term *= val;
}
acc += term;
}
}
return new NumberEval(acc);
}
private static void ThrowFirstError(TwoDEval areaEval)
{
int height = areaEval.Height;
int width = areaEval.Width;
for (int rrIx = 0; rrIx < height; rrIx++)
{
for (int rcIx = 0; rcIx < width; rcIx++)
{
ValueEval ve = areaEval.GetValue(rrIx, rcIx);
if (ve is ErrorEval)
{
throw new EvaluationException((ErrorEval)ve);
}
}
}
}
private static bool AreasAllSameSize(TwoDEval[] args, int height, int width)
{
for (int i = 0; i < args.Length; i++)
{
TwoDEval areaEval = args[i];
// check that height and width match
if (areaEval.Height != height)
{
return false;
}
if (areaEval.Width != width)
{
return false;
}
}
return true;
}
/**
* Determines a <c>double</c> value for the specified <c>ValueEval</c>.
* @param IsScalarProduct <c>false</c> for SUMPRODUCTs over area refs.
* @throws EvalEx if <c>ve</c> represents an error value.
* <p/>
* Note - string values and empty cells are interpreted differently depending on
* <c>isScalarProduct</c>. For scalar products, if any term Is blank or a string, the
* error (#VALUE!) Is raised. For area (sum)products, if any term Is blank or a string, the
* result Is zero.
*/
private static double GetProductTerm(ValueEval ve, bool IsScalarProduct)
{
if (ve is BlankEval || ve == null)
{
// TODO - shouldn't BlankEval.INSTANCE be used always instead of null?
// null seems to occur when the blank cell Is part of an area ref (but not reliably)
if (IsScalarProduct)
{
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
return 0;
}
if (ve is ErrorEval)
{
throw new EvaluationException((ErrorEval)ve);
}
if (ve is StringEval)
{
if (IsScalarProduct)
{
throw new EvaluationException(ErrorEval.VALUE_INVALID);
}
// Note for area SUMPRODUCTs, string values are interpreted as zero
// even if they would Parse as valid numeric values
return 0;
}
if (ve is NumericValueEval)
{
NumericValueEval nve = (NumericValueEval)ve;
return nve.NumberValue;
}
throw new RuntimeException("Unexpected value eval class ("
+ ve.GetType().Name + ")");
}
}
}
| |
(>=
(f0
(var x1)
(0)
(var x3)
(var x4)
(var x5))
(+ (0) 1))
(>=
(f0
(var x1)
(S (var x))
(var x3)
(0)
(var x5))
(+ (0) 1))
(>=
(f0
(var x1)
(S (var x'))
(var x3)
(S (var x))
(var x5))
(+
(f1
(var x')
(S (var x'))
(var x)
(S (var x))
(S (var x)))
1))
(>=
(f1
(var x1)
(var x2)
(var x3)
(var x4)
(0))
(+ (0) 1))
(>=
(f1
(var x1)
(var x2)
(var x3)
(var x4)
(S (var x)))
(+
(f2
(var x2)
(var x1)
(var x3)
(var x4)
(var x))
1))
(>=
(f2
(var x1)
(var x2)
(0)
(var x4)
(var x5))
(+ (0) 1))
(>=
(f2
(var x1)
(var x2)
(S (var x))
(0)
(0))
(+ (0) 1))
(>=
(f2
(var x1)
(var x2)
(S (var x'))
(0)
(S (var x)))
(+
(f3
(var x1)
(var x2)
(var x')
(0)
(var x))
1))
(>=
(f2
(var x1)
(var x2)
(S (var x'))
(S (var x))
(0))
(+ (0) 1))
(>=
(f2
(var x1)
(var x2)
(S (var x''))
(S (var x'))
(S (var x)))
(+
(f5
(var x1)
(var x2)
(S (var x''))
(var x')
(var x))
1))
(>=
(f3
(var x1)
(var x2)
(var x3)
(var x4)
(0))
(+ (0) 1))
(>=
(f3
(var x1)
(var x2)
(var x3)
(var x4)
(S (var x)))
(+
(f4
(var x1)
(var x2)
(var x4)
(var x3)
(var x))
1))
(>=
(f4
(0)
(var x2)
(var x3)
(var x4)
(var x5))
(+ (0) 1))
(>=
(f4
(S (var x))
(0)
(var x3)
(var x4)
(0))
(+ (0) 1))
(>=
(f4
(S (var x'))
(0)
(var x3)
(var x4)
(S (var x)))
(+
(f3
(var x')
(0)
(var x3)
(var x4)
(var x))
1))
(>=
(f4
(S (var x'))
(S (var x))
(var x3)
(var x4)
(0))
(+ (0) 1))
(>=
(f4
(S (var x''))
(S (var x'))
(var x3)
(var x4)
(S (var x)))
(+
(f2
(S (var x''))
(var x')
(var x3)
(var x4)
(var x))
1))
(>=
(f5
(var x1)
(var x2)
(var x3)
(var x4)
(0))
(+ (0) 1))
(>=
(f5
(var x1)
(var x2)
(var x3)
(var x4)
(S (var x)))
(+
(f6
(var x2)
(var x1)
(var x3)
(var x4)
(var x))
1))
(>=
(f6
(var x1)
(var x2)
(var x3)
(var x4)
(0))
(+ (0) 1))
(>=
(f6
(var x1)
(var x2)
(var x3)
(var x4)
(S (var x)))
(+
(f0
(var x1)
(var x2)
(var x4)
(var x3)
(var x))
1))
(>= (0) 0)
(>= (S (var _x1)) 0)
(>=
(f0
(var _x1)
(var _x2)
(var _x3)
(var _x4)
(var _x5))
0)
(>=
(f1
(var _x1)
(var _x2)
(var _x3)
(var _x4)
(var _x5))
0)
(>=
(f2
(var _x1)
(var _x2)
(var _x3)
(var _x4)
(var _x5))
0)
(>=
(f3
(var _x1)
(var _x2)
(var _x3)
(var _x4)
(var _x5))
0)
(>=
(f4
(var _x1)
(var _x2)
(var _x3)
(var _x4)
(var _x5))
0)
(>=
(f5
(var _x1)
(var _x2)
(var _x3)
(var _x4)
(var _x5))
0)
(>=
(f6
(var _x1)
(var _x2)
(var _x3)
(var _x4)
(var _x5))
0)
(>= (_f1) (0))
(>=
(+ (var _x1) (_f2))
(S (var _x1)))
| |
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace PlayFab.PfEditor
{
public class PlayFabEditorSDKTools : UnityEditor.Editor
{
public static bool IsInstalled { get { return GetPlayFabSettings() != null; } }
private static Type playFabSettingsType = null;
private static string installedSdkVersion = string.Empty;
private static string latestSdkVersion = string.Empty;
private static UnityEngine.Object sdkFolder;
private static UnityEngine.Object _previoussSdkFolderPath;
private static bool isObjectFieldActive;
private static bool isInitialized; //used to check once, gets reset after each compile;
public static bool isSdkSupported = true;
public static void DrawSdkPanel()
{
if (!isInitialized)
{
//SDK is installed.
CheckSdkVersion();
isInitialized = true;
GetLatestSdkVersion();
sdkFolder = FindSdkAsset();
if (sdkFolder != null)
{
PlayFabEditorDataService.EnvDetails.sdkPath = AssetDatabase.GetAssetPath(sdkFolder);
PlayFabEditorDataService.SaveEnvDetails();
}
}
if (IsInstalled)
ShowSdkInstalledMenu();
else
ShowSdkNotInstalledMenu();
}
private static void ShowSdkInstalledMenu()
{
isObjectFieldActive = sdkFolder == null;
if (_previoussSdkFolderPath != sdkFolder)
{
// something changed, better save the result.
_previoussSdkFolderPath = sdkFolder;
PlayFabEditorDataService.EnvDetails.sdkPath = (AssetDatabase.GetAssetPath(sdkFolder));
PlayFabEditorDataService.SaveEnvDetails();
isObjectFieldActive = false;
}
var labelStyle = new GUIStyle(PlayFabEditorHelper.uiStyle.GetStyle("titleLabel"));
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
EditorGUILayout.LabelField(string.Format("SDK {0} is installed", string.IsNullOrEmpty(installedSdkVersion) ? "Unknown" : installedSdkVersion),
labelStyle, GUILayout.MinWidth(EditorGUIUtility.currentViewWidth));
if (!isObjectFieldActive)
{
GUI.enabled = false;
}
else
{
EditorGUILayout.LabelField(
"An SDK was detected, but we were unable to find the directory. Drag-and-drop the top-level PlayFab SDK folder below.",
PlayFabEditorHelper.uiStyle.GetStyle("orTxt"));
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
sdkFolder = EditorGUILayout.ObjectField(sdkFolder, typeof(UnityEngine.Object), false, GUILayout.MaxWidth(200));
GUILayout.FlexibleSpace();
}
if (!isObjectFieldActive)
{
// this is a hack to prevent our "block while loading technique" from breaking up at this point.
GUI.enabled = !EditorApplication.isCompiling && PlayFabEditor.blockingRequests.Count == 0;
}
if (isSdkSupported && sdkFolder != null)
{
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("REMOVE SDK", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32), GUILayout.MinWidth(200)))
{
RemoveSdk();
}
GUILayout.FlexibleSpace();
}
}
}
if (sdkFolder != null)
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
isSdkSupported = false;
string[] versionNumber = !string.IsNullOrEmpty(installedSdkVersion) ? installedSdkVersion.Split('.') : new string[0];
var numerical = 0;
if (string.IsNullOrEmpty(installedSdkVersion) || versionNumber == null || versionNumber.Length == 0 ||
(versionNumber.Length > 0 && int.TryParse(versionNumber[0], out numerical) && numerical < 2))
{
//older version of the SDK
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
EditorGUILayout.LabelField("Most of the Editor Extensions depend on SDK versions >2.0. Consider upgrading to the get most features.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt"));
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("READ THE UPGRADE GUIDE", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32)))
{
Application.OpenURL("https://github.com/PlayFab/UnitySDK/blob/master/UPGRADE.md");
}
GUILayout.FlexibleSpace();
}
}
else if (numerical >= 2)
{
isSdkSupported = true;
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
if (ShowSDKUpgrade() && isSdkSupported)
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("Upgrade to " + latestSdkVersion, PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MinHeight(32)))
{
UpgradeSdk();
}
GUILayout.FlexibleSpace();
}
else if (isSdkSupported)
{
GUILayout.FlexibleSpace();
EditorGUILayout.LabelField("You have the latest SDK!", labelStyle, GUILayout.MinHeight(32));
GUILayout.FlexibleSpace();
}
}
}
}
if (isSdkSupported && string.IsNullOrEmpty(PlayFabEditorDataService.SharedSettings.TitleId))
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
EditorGUILayout.LabelField("Before making PlayFab API calls, the SDK must be configured to your PlayFab Title.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt"));
using (new UnityHorizontal())
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("SET MY TITLE", PlayFabEditorHelper.uiStyle.GetStyle("textButton")))
{
PlayFabEditorMenu.OnSettingsClicked();
}
GUILayout.FlexibleSpace();
}
}
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
GUILayout.FlexibleSpace();
if (GUILayout.Button("VIEW RELEASE NOTES", PlayFabEditorHelper.uiStyle.GetStyle("textButton"), GUILayout.MinHeight(32), GUILayout.MinWidth(200)))
{
Application.OpenURL("https://api.playfab.com/releaseNotes/");
}
GUILayout.FlexibleSpace();
}
}
private static void ShowSdkNotInstalledMenu()
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
var labelStyle = new GUIStyle(PlayFabEditorHelper.uiStyle.GetStyle("titleLabel"));
EditorGUILayout.LabelField("No SDK is installed.", labelStyle, GUILayout.MinWidth(EditorGUIUtility.currentViewWidth));
GUILayout.Space(20);
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
var buttonWidth = 150;
GUILayout.FlexibleSpace();
if (GUILayout.Button("Install PlayFab SDK", PlayFabEditorHelper.uiStyle.GetStyle("Button"), GUILayout.MaxWidth(buttonWidth),
GUILayout.MinHeight(32)))
{
ImportLatestSDK();
}
GUILayout.FlexibleSpace();
}
}
}
public static void ImportLatestSDK()
{
PlayFabEditorHttp.MakeDownloadCall("https://api.playfab.com/sdks/download/unity-via-edex", (fileName) =>
{
Debug.Log("PlayFab SDK Install: Complete");
AssetDatabase.ImportPackage(fileName, false);
PlayFabEditorDataService.EnvDetails.sdkPath = PlayFabEditorHelper.DEFAULT_SDK_LOCATION;
PlayFabEditorDataService.SaveEnvDetails();
});
}
public static Type GetPlayFabSettings()
{
if (playFabSettingsType == typeof(object))
return null; // Sentinel value to indicate that PlayFabSettings doesn't exist
if (playFabSettingsType != null)
return playFabSettingsType;
playFabSettingsType = typeof(object); // Sentinel value to indicate that PlayFabSettings doesn't exist
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
foreach (var eachType in assembly.GetTypes())
if (eachType.Name == PlayFabEditorHelper.PLAYFAB_SETTINGS_TYPENAME)
playFabSettingsType = eachType;
return playFabSettingsType == typeof(object) ? null : playFabSettingsType;
}
private static void CheckSdkVersion()
{
if (!string.IsNullOrEmpty(installedSdkVersion))
return;
var types = new List<Type>();
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
foreach (var type in assembly.GetTypes())
if (type.Name == "PlayFabVersion" || type.Name == PlayFabEditorHelper.PLAYFAB_SETTINGS_TYPENAME)
types.Add(type);
foreach (var type in types)
{
foreach (var property in type.GetProperties())
if (property.Name == "SdkVersion" || property.Name == "SdkRevision")
installedSdkVersion += property.GetValue(property, null).ToString();
foreach (var field in type.GetFields())
if (field.Name == "SdkVersion" || field.Name == "SdkRevision")
installedSdkVersion += field.GetValue(field).ToString();
}
}
private static UnityEngine.Object FindSdkAsset()
{
UnityEngine.Object sdkAsset = null;
// look in editor prefs
if (PlayFabEditorDataService.EnvDetails.sdkPath != null)
{
sdkAsset = AssetDatabase.LoadAssetAtPath(PlayFabEditorDataService.EnvDetails.sdkPath, typeof(UnityEngine.Object));
}
if (sdkAsset != null)
return sdkAsset;
sdkAsset = AssetDatabase.LoadAssetAtPath(PlayFabEditorHelper.DEFAULT_SDK_LOCATION, typeof(UnityEngine.Object));
if (sdkAsset != null)
return sdkAsset;
var fileList = Directory.GetDirectories(Application.dataPath, "*PlayFabSdk", SearchOption.AllDirectories);
if (fileList.Length == 0)
return null;
var relPath = fileList[0].Substring(fileList[0].LastIndexOf("Assets/"));
return AssetDatabase.LoadAssetAtPath(relPath, typeof(UnityEngine.Object));
}
private static bool ShowSDKUpgrade()
{
if (string.IsNullOrEmpty(latestSdkVersion) || latestSdkVersion == "Unknown")
{
return false;
}
if (string.IsNullOrEmpty(installedSdkVersion) || installedSdkVersion == "Unknown")
{
return true;
}
string[] currrent = installedSdkVersion.Split('.');
string[] latest = latestSdkVersion.Split('.');
if (int.Parse(currrent[0]) < 2)
{
return false;
}
return int.Parse(latest[0]) > int.Parse(currrent[0])
|| int.Parse(latest[1]) > int.Parse(currrent[1])
|| int.Parse(latest[2]) > int.Parse(currrent[2]);
}
private static void UpgradeSdk()
{
if (EditorUtility.DisplayDialog("Confirm SDK Upgrade", "This action will remove the current PlayFab SDK and install the lastet version. Related plug-ins will need to be manually upgraded.", "Confirm", "Cancel"))
{
RemoveSdk(false);
ImportLatestSDK();
}
}
private static void RemoveSdk(bool prompt = true)
{
if (prompt && !EditorUtility.DisplayDialog("Confirm SDK Removal", "This action will remove the current PlayFab SDK. Related plug-ins will need to be manually removed.", "Confirm", "Cancel"))
return;
//try to clean-up the plugin dirs
if (Directory.Exists(Application.dataPath + "/Plugins"))
{
var folders = Directory.GetDirectories(Application.dataPath + "/Plugins", "PlayFabShared", SearchOption.AllDirectories);
foreach (var folder in folders)
FileUtil.DeleteFileOrDirectory(folder);
//try to clean-up the plugin files (if anything is left)
var files = Directory.GetFiles(Application.dataPath + "/Plugins", "PlayFabErrors.cs", SearchOption.AllDirectories);
foreach (var file in files)
FileUtil.DeleteFileOrDirectory(file);
}
if (FileUtil.DeleteFileOrDirectory(PlayFabEditorDataService.EnvDetails.sdkPath))
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnSuccess, "PlayFab SDK Removed!");
// HACK for 5.4, AssetDatabase.Refresh(); seems to cause the install to fail.
if (prompt)
{
AssetDatabase.Refresh();
}
}
else
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, "An unknown error occured and the PlayFab SDK could not be removed.");
}
}
private static void GetLatestSdkVersion()
{
var threshold = PlayFabEditorDataService.EditorSettings.lastSdkVersionCheck != DateTime.MinValue ? PlayFabEditorDataService.EditorSettings.lastSdkVersionCheck.AddHours(1) : DateTime.MinValue;
if (DateTime.Today > threshold)
{
PlayFabEditorHttp.MakeGitHubApiCall("https://api.github.com/repos/PlayFab/UnitySDK/git/refs/tags", (version) =>
{
latestSdkVersion = version ?? "Unknown";
PlayFabEditorDataService.EditorSettings.latestSdkVersion = latestSdkVersion;
});
}
else
{
latestSdkVersion = PlayFabEditorDataService.EditorSettings.latestSdkVersion;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate declaration at top level or under namespaces</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
// <Code>
using System;
public delegate dynamic D001(dynamic d);
public delegate object D002(dynamic d, object o);
public delegate dynamic D003(ref dynamic d1, object o, out dynamic d3);
public delegate void D004(ref int n, dynamic[] d1, params dynamic[] d2);
namespace DynNamespace01
{
public interface DynInterface01
{
}
public class DynClass01
{
public int n = 0;
}
public struct DynStruct01
{
}
public delegate dynamic D101(dynamic d, DynInterface01 i);
public delegate void D102(ref DynClass01 c, dynamic d1, ref object d2);
namespace DynNamespace02
{
public delegate void D201(ref dynamic d1, DynClass01 c, out dynamic[] d2, DynStruct01 st);
public delegate dynamic D202(DynStruct01 st, params object[] d2);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate001.dlgate001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate001.dlgate001;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> interchangeable dynamic and object parameters </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
public class Foo
{
// public delegate dynamic D001(dynamic v);
static public dynamic M01(dynamic v)
{
return 0x01;
}
public object M02(dynamic v)
{
return 0x02;
}
public dynamic M03(object v)
{
return 0x03;
}
static public dynamic M04(object v)
{
return 0x04;
}
// public delegate object D002(dynamic d, object o);
static public object M05(dynamic v1, object v2)
{
return 0x05;
}
public object M06(object v1, dynamic v2)
{
return 0x06;
}
static public dynamic M07(dynamic v1, object v2)
{
return 0x07;
}
public dynamic M08(object v1, dynamic v2)
{
return 0x08;
}
// dynamic D003(ref dynamic d1, object o, out dynamic d3);
static public dynamic M09(ref dynamic v1, object v2, out dynamic v3)
{
v3 = null;
return 0x09;
}
public object M0A(ref object v1, object v2, out object v3)
{
v3 = null;
return 0x0A;
}
public object M0B(ref dynamic v1, dynamic v2, out dynamic v3)
{
v3 = null;
return 0x0B;
}
// public delegate void D004(dynamic[] d1, params dynamic[] d2);
static public void M0C(ref int n, dynamic[] v1, params dynamic[] v2)
{
n += 0x0C;
}
public void M0D(ref int n, object[] v1, params object[] v2)
{
n += 0x0D;
}
}
public class start
{
private static int s_retval = (int)((1 + 0x0D) * 0x0D) / 2;
// field
private static D001 s_del001 = null;
private static D003 s_del003 = null;
private static dynamic s_sd = null;
private static object s_so = new object();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
Foo foo = new Foo();
dynamic d = new object();
object o = null;
s_del001 = new D001(Foo.M01);
s_retval -= (int)s_del001(s_sd);
D001 d001 = new D001(foo.M02);
s_retval -= (int)d001(o);
d001 = new D001(foo.M03);
s_retval -= (int)d001(s_sd);
s_del001 = new D001(Foo.M04);
s_retval -= (int)s_del001(d);
D002 del002 = null;
del002 = new D002(Foo.M05);
s_retval -= (int)del002(d, o);
D002 d002 = new D002(foo.M06);
s_retval -= (int)d002(o, s_sd);
del002 = new D002(Foo.M07);
s_retval -= (int)del002(s_so, o);
d002 = new D002(foo.M08);
s_retval -= (int)d002(s_sd, s_so);
s_del003 = new D003(Foo.M09);
s_retval -= (int)s_del003(ref d, s_so, out s_sd);
D003 d003 = new D003(foo.M0A);
// Ex: Null ref
// retval -= (int)d003(ref o, sd, out so);
s_retval -= (int)d003(ref o, o, out o);
d003 = new D003(foo.M0B);
// Ex: Null ref
// retval -= (int)d003(ref so, d, out d);
s_retval -= (int)d003(ref s_so, s_so, out s_so);
dynamic[] dary = new object[]
{
}
;
int ret = 0;
D004 del004 = new D004(Foo.M0C);
del004(ref ret, new object[]
{
}
, dary);
s_retval -= ret;
del004 = new D004(foo.M0D);
ret = 0;
del004(ref ret, new dynamic[]
{
}
, dary);
s_retval -= ret;
return s_retval;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate002.dlgate002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate002.dlgate002;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> delegate can be assigned by ternary operator| +=, compared for equality
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
public class Foo
{
// DynNamespace01: public delegate dynamic D101(dynamic d, DynInterface01 i);
static public dynamic M01(dynamic v1, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynInterface01 v2)
{
return 0x01;
}
public dynamic M02(object v1, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynInterface01 v2)
{
return 0x01;
}
// DynNamespace01: public delegate void D102(DynClass01 c, ref dynamic d1, ref object d2)
static public void M03(ref ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynClass01 v1, dynamic v2, ref object v3)
{
v1.n = 3;
}
public void M04(ref ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynClass01 v1, object v2, ref dynamic v3)
{
v1.n = 4;
}
// DynNamespace01:
// public delegate void D201(ref dynamic d1, DynClass01[] c, out dynamic d2, DynStruct01 st)
public void M05(ref dynamic v1, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynClass01 v2, out dynamic[] v3, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynStruct01 v4)
{
v1 = 5;
v3 = null;
}
static public void M06(ref object v1, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynClass01 v2, out dynamic[] v3, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynStruct01 v4)
{
v1 = 6;
v3 = null;
}
public void M07(ref object v1, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynClass01 v2, out object[] v3, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynStruct01 v4)
{
v1 = 7;
v3 = null;
}
// DynNamespace01:
// public delegate dynamic D202(DynStruct01 st, params object[] d2)
static public dynamic M08(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynStruct01 v1, params object[] v2)
{
return 0x08;
}
public object M09(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib01.dlgatedeclarelib01.DynNamespace01.DynStruct01 v1, params dynamic[] v2)
{
return 0x09;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate003.dlgate003;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate declaration under other types</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
// <Code>
using System;
namespace DynNamespace01
{
public class DynClass
{
public delegate string D001(object v1, dynamic v2, DynEnum v3);
public struct DynStruct
{
public delegate string D101(DynEnum v1, ref object v2, params dynamic[] v3);
public delegate string D102(DynEnum v1, ref dynamic v2, params object[] v3);
}
}
public enum DynEnum
{
item0,
item1,
item2,
item3,
item4,
item5,
item6
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate003.dlgate003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate003.dlgate003;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> delegates can be aggregated in arrays and compared for equality.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
public class Foo
{
// DynNamespace01.DynClass:
// public delegate string D001(object v1, dynamic v2, ref DynEnum v3)
static public string M01(object v1, object v2, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v3)
{
return v3.ToString();
}
public string M11(object v1, object v2, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v3)
{
return v3.ToString();
}
public string M21(object v1, object v2, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v3)
{
return v3.ToString();
}
static public string M02(dynamic v1, dynamic v2, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v3)
{
return v3.ToString();
}
// DynNamespace01.DynClass.DynStruct:
// public delegate string D101(ref DynEnum v1, ref object v2, params dynamic[] v3);
public string M03(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v1, ref object v2, params dynamic[] v3)
{
return v1.ToString();
}
// DynNamespace01.DynClass.DynStruct:
// blic delegate string D101(ref DynEnum v1, ref dynamic v2, params object[] v3)
public string M04(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum v1, ref dynamic v2, params object[] v3)
{
return v1.ToString();
}
}
public class start
{
// field
private static ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001[] s_d001 = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001[3];
private static dynamic s_sd = null;
private static object s_so = new object();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
bool ret = true;
Foo foo = new Foo();
dynamic d = new object();
object o = null;
s_d001[0] = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(foo.M11);
s_d001[1] = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(foo.M21);
s_d001[2] = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(Foo.M01);
ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001[] ary101 =
{
new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(Foo.M01), new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(foo.M21), new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(foo.M11)}
;
if (s_d001[0] != ary101[2])
{
ret = false;
}
if (s_d001[1] != ary101[1])
{
ret = false;
}
if (s_d001[2] != ary101[0])
{
ret = false;
}
ary101[0] = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.D001(Foo.M02);
string st1 = ary101[0](s_so, s_sd, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item1);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item1.ToString() != s_d001[0](s_so, d, ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item1))
{
ret = false;
}
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item1.ToString() != st1)
{
ret = false;
}
dynamic[] dary = new object[]
{
}
;
object[] oary = new object[]
{
}
;
ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D101 d101 = null;
d101 = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D101(foo.M03);
ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D101 d111 = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D101(foo.M04);
st1 = d101(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item2, ref d, dary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item2.ToString() != st1)
{
ret = false;
}
st1 = d101(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item3, ref o, oary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item3.ToString() != st1)
{
ret = false;
}
st1 = d111(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item3, ref o, oary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item3.ToString() != st1)
{
ret = false;
}
st1 = d111(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item4, ref s_so, dary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item4.ToString() != st1)
{
ret = false;
}
ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D102 d102 = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D102(foo.M04);
st1 = d102(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item5, ref d, dary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item5.ToString() != st1)
{
ret = false;
}
ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D102 d122 = new ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynClass.DynStruct.D102(foo.M03);
st1 = d122(ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item6, ref s_so, oary);
if (ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib02.dlgatedeclarelib02.DynNamespace01.DynEnum.item6.ToString() != st1)
{
ret = false;
}
return ret ? 0 : 1;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib03.dlgatedeclarelib03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib03.dlgatedeclarelib03;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate004.dlgate004;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate declaration with different modifiers</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
// <Code>
using System;
namespace DynNamespace31
{
public class DynClassBase
{
public delegate void PublicDel(dynamic v, ref int n);
private delegate void PrivateDel(dynamic d);
}
public class DynClassDrived : DynClassBase
{
private new delegate void PublicDel(dynamic v, ref int n);
// protected: can not access if in dll
public delegate long InternalDel(sbyte v1, dynamic v2, short v3, dynamic v4, int v5, dynamic v6, long v7, dynamic v8, dynamic v9);
protected delegate void ProtectedDel(dynamic d);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate004.dlgate004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib03.dlgatedeclarelib03;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate004.dlgate004;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> delegates can be combined by using +, - +=, -=
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib03.dlgatedeclarelib03.DynNamespace31;
namespace nms
{
public class Foo
{
// DynNamespace31.DynClassBase: public delegate void PublicDel(dynamic v, ref int n)
// DynNamespace31.DynClassDrived: new delegate void NewPublicDel(dynamic v, ref int n);
public void M01(dynamic v, ref int n)
{
n = 1;
}
internal void M02(dynamic v, ref int n)
{
n = 2;
}
public void M03(object v, ref int n)
{
n = 4;
}
internal void M04(object v, ref int n)
{
n = 8;
}
// DynNamespace31.DynClassDrived:
// internal delegate long InternalDel(sbyte v1, dynamic v2, short v3, dynamic v4, int v5, dynamic v6, long v7, dynamic v8, dynamic v9)
static public long M11(sbyte v1, dynamic v2, short v3, dynamic v4, int v5, dynamic v6, long v7, dynamic v8, dynamic v9)
{
return v1 + (int)v2 + v3 + (int)v4 + v5 + (int)v6 + v7 + (int)v8 + (int)v9;
}
static internal long M12(sbyte v1, dynamic v2, short v3, dynamic v4, int v5, dynamic v6, long v7, dynamic v8, object v9)
{
return v1 + v3 + v5 + v7 + (int)v9;
}
static public long M13(sbyte v1, dynamic v2, short v3, object v4, int v5, dynamic v6, long v7, dynamic v8, object v9)
{
return (int)v2 + (int)v4 + (int)v6 + (int)v8;
}
// DynNamespace31.DynClassDrived:
// static public delegate int StPublicDel(dynamic v1, decimal v2);
internal int M21(dynamic v1, decimal v2)
{
return 33;
}
internal int M22(object v1, decimal v2)
{
return 66;
}
internal int M23(dynamic v1, decimal v2)
{
return 99;
}
internal int M24(object v1, decimal v2)
{
return -1;
}
}
public struct start
{
// field
private static DynClassDrived.InternalDel s_interDel;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
bool ret = true;
Foo foo = new Foo();
dynamic d = new object();
object o = new object();
DynClassBase.PublicDel pd01 = new DynClassBase.PublicDel(foo.M01);
DynClassDrived.PublicDel pd02 = new DynClassBase.PublicDel(foo.M02);
DynClassBase.PublicDel pd03 = new DynClassBase.PublicDel(foo.M03);
DynClassDrived.PublicDel pd04 = new DynClassBase.PublicDel(foo.M04);
DynClassBase.PublicDel pd05 = pd01 + pd02;
pd05 += new DynClassBase.PublicDel(pd01);
DynClassBase.PublicDel pd06 = pd03 + new DynClassDrived.PublicDel(foo.M04);
pd06 = pd04 + pd05 + pd06; // M04+M01+M02+M01+M03+M04 => 8 (last one)
int n = 0;
pd06(d, ref n);
if (8 != n)
{
ret = false;
}
pd06 -= pd04;
pd06(d, ref n);
if (4 != n)
{
ret = false;
}
pd06 -= pd01;
pd06(d, ref n);
if (4 != n)
{
ret = false;
}
//
s_interDel = new DynClassDrived.InternalDel(Foo.M11);
DynClassDrived.InternalDel dd01 = new DynClassDrived.InternalDel(s_interDel); //45
DynClassDrived.InternalDel dd02 = new DynClassDrived.InternalDel(Foo.M12); // 25
DynClassDrived.InternalDel dd03 = new DynClassDrived.InternalDel(Foo.M13); // 20
DynClassDrived.InternalDel dd04 = dd01; // 45
dd04 += dd02; // 25
DynClassDrived.InternalDel dd05 = dd02 + dd03;
dd04 += dd05 + new DynClassDrived.InternalDel(dd05); // new(1)+2+ 2+3 + new(2+3)
long lg = dd04(1, 2, 3, 4, 5, 6, 7, 8, 9);
if (20 != lg) // dd03
{
ret = false;
}
dd04 = dd04 - dd02 - dd02 - dd03; // new(1)+ new(2+3)
lg = dd04(1, 2, 3, 4, 5, 6, 7, 8, 9);
if (20 != lg) // dd03
{
ret = false;
}
dd04 -= new DynClassDrived.InternalDel(dd05); // new(1)
lg = dd04(1, 2, 3, 4, 5, 6, 7, 8, 9);
if (45 != lg)
{
ret = false;
}
return ret ? 0 : 1;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib04.dlgatedeclarelib04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib04.dlgatedeclarelib04;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate declaration with generic types</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
// <Code>
using System;
public delegate R D001<R>(dynamic d);
namespace DynNamespace41
{
public delegate void D002<T1, T2>(T1 t1, T2 t2);
public class DynClass
{
public delegate R D011<T, R>(T[] v1, dynamic v2);
// internal: can not access if in dll
public delegate dynamic D012<T>(ref T v1, ref dynamic[] v2);
}
public struct DynStruct
{
public delegate R D021<T, R>(out dynamic d, out T t);
// internal: can not access if in dll
public delegate dynamic D022<T1, T2, T3>(T1 t1, ref T2 t2, out T3 t3, params dynamic[] d);
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib05.dlgatedeclarelib05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib05.dlgatedeclarelib05;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate006.dlgate006;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate declaration with optional parameters</Title>
// <Description></Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
// <Code>
using System;
public delegate void D001(dynamic d = null); // not allow init with values other than null:(
public delegate void D002(dynamic v1, object v2 = null, dynamic v3 = null /*DynNamespace51.DynClass.strDyn*/);
namespace DynNamespace51
{
public delegate void D011(dynamic d1 = null, params dynamic[] d2);
public class DynClass
{
public const string strDyn = "dynamic";
// internal: can not access if in dll
public delegate int D021(params dynamic[] d);
public delegate void D022(DynStruct01 v1, dynamic v2 = null, int v3 = -1);
public struct DynStruct
{
public delegate dynamic D031(DynClass01 v1, DynStruct01 v2 = new DynStruct01(), dynamic[] v3 = null);
}
}
public class DynClass01
{
}
public struct DynStruct01
{
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate006.dlgate006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib05.dlgatedeclarelib05;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate006.dlgate006;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> delegates can has optional parameters
// default value of dynamic can only be set to null :(
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgatedeclarelib05.dlgatedeclarelib05.DynNamespace51;
namespace nms
{
public class Foo
{
static public int val = -1;
static public int? nval = -1;
static public string str = string.Empty;
// public delegate void D001(dynamic d = null);
public void M01(dynamic d = null)
{
val = d;
}
internal void M02(dynamic d)
{
nval = d;
}
// internal delegate void D002(dynamic v1, object v2 = null, dynamic v3 = null)
static internal void M11(dynamic v1, object v2, dynamic v3 = null)
{
str = v3;
}
// public delegate void D011(dynamic d1 = null, params dynamic[] d2);
public void M21(dynamic d1, params dynamic[] d2)
{
nval = d1;
}
// internal delegate int D021(params dynamic[] d);
static internal int M31(params dynamic[] d)
{
return 31;
}
// public delegate void D022(DynStruct01 v1, dynamic v2 = 0.123f, int v3 = -1);
static internal void M41(DynStruct01 v1, dynamic v2 = null, int v3 = 41)
{
val = v3;
}
// public delegate dynamic D031(DynClass01 v1, DynStruct01 v2 = new DynStruct01(), dynamic[] v3 = null);
static public dynamic M51(DynClass01 v1, DynStruct01 v2 = new DynStruct01(), dynamic[] v3 = null)
{
return 51;
}
}
public class TestClass
{
[Fact]
public void RunTest()
{
start.DynamicCSharpRunTest();
}
}
public struct start
{
// field
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
bool ret = true;
Foo foo = new Foo();
dynamic d = new object();
D001 dd01 = new D001(foo.M01);
dd01(123); // use delegate's default value
if (123 != Foo.val)
{
ret = false;
}
dd01(100);
if (100 != Foo.val)
{
ret = false;
}
Foo.val = -1;
D001 dd11 = new D001(foo.M02);
dd11();
if (null != Foo.nval)
{
ret = false;
}
dd11(101);
if (101 != Foo.nval)
{
ret = false;
}
D002 dd021;
dd021 = new D002(Foo.M11);
dd021(88);
if (null != Foo.str)
{
ret = false;
}
dd021(66, "boo", "Dah");
if (0 != String.CompareOrdinal("Dah", Foo.str))
{
ret = false;
}
dynamic dstr = "Hello";
dd021(88, null, dstr);
if ((string)dstr != Foo.str)
{
ret = false;
}
D011 dd011 = new D011(foo.M21);
dd011();
if (Foo.nval.HasValue)
{
ret = false;
}
dd011(102);
if (!Foo.nval.HasValue || 102 != Foo.nval)
{
ret = false;
}
DynClass.D021 dd21 = new DynClass.D021(Foo.M31);
int n = dd21();
n = dd21(d);
DynClass.D022 dd22 = null;
dd22 = new DynClass.D022(Foo.M41);
dd22(new DynStruct01());
if (-1 != Foo.val) // 41
{
ret = false;
}
dd22(new DynStruct01(), 0.780f, 103);
if (103 != Foo.val)
{
ret = false;
}
DynClass.DynStruct.D031 dd31 = new DynClass.DynStruct.D031(Foo.M51);
n = dd31(new DynClass01());
if (51 != n)
{
ret = false;
}
n = dd31(null, new DynStruct01());
if (51 != n)
{
ret = false;
}
n = dd31(new DynClass01(), new DynStruct01(), null);
if (51 != n)
{
ret = false;
}
return ret ? 0 : 1;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate007bug.dlgate007bug
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate007bug.dlgate007bug;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description> Assert and NullRef Exception when call with delegate 2nd as out param </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
public delegate void DelOut(object v1, out object v2);
public class Foo
{
static public void M01(object v1, out object v2)
{
v2 = null;
}
static public void M02(object v1, out dynamic v2)
{
v2 = null;
}
static public void M03(dynamic v1, out object v2)
{
v2 = null;
}
static internal void M04(dynamic v1, out dynamic v2)
{
v2 = null;
}
}
public class start
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
dynamic nd = null;
dynamic d = new object();
object no = null;
object o = new object();
DelOut d_oo = new DelOut(Foo.M01);
DelOut d_od = new DelOut(Foo.M02);
DelOut d_do = new DelOut(Foo.M03);
DelOut d_dd = new DelOut(Foo.M03);
// object, object
d_oo(no, out o);
d_od(o, out no);
d_do(no, out o);
d_od(o, out no);
// object, dynamic
d_oo(o, out nd);
d_od(no, out d);
d_do(o, out nd);
d_od(no, out d);
// Assert and Null Ref Exception
// dynamic, object
d_oo(nd, out o);
d_od(nd, out no);
d_do(d, out o);
d_od(d, out no);
// dynamic, dynamic
d_oo(d, out d);
d_od(d, out nd);
d_do(nd, out d);
d_od(nd, out nd);
return 0;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate008bug.dlgate008bug
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate008bug.dlgate008bug;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation (Behavior is 'by design' as they are 2 different boxed instances)</Title>
// <Description> Delegate: compare same delegates return false if the method is struct's not static method </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
public delegate void Del(dynamic v1);
public struct Foo
{
public void MinStruct(dynamic v1)
{
}
static public void SMinStruct(dynamic v1)
{
}
}
public class Bar
{
public void MinClass(dynamic v1)
{
}
static public void SMinClass(dynamic v1)
{
}
}
public class start
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
bool ret = true;
Bar bar = new Bar();
Del[] ary01 =
{
new Del(Foo.SMinStruct), new Del(bar.MinClass), new Del(Bar.SMinClass)}
;
Del[] ary02 =
{
new Del(Foo.SMinStruct), new Del(bar.MinClass), new Del(Bar.SMinClass)}
;
int idx = 0;
foreach (Del d in ary01)
{
if (d != ary02[idx])
{
ret = false;
}
idx++;
}
return ret ? 0 : 1;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate009bug.dlgate009bug
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.dlgate009bug.dlgate009bug;
// <Area> Dynamic type in delegates </Area>
// <Title> Delegate instantiation</Title>
// <Description>
// Delegate with params: ASSERT FAILED,(result) ? (GetOutputContext().m_bHadNamedAndOptionalArguments) : true, File: ... transformpass.cpp, Line: 234
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects status=success></Expects>
using System;
namespace nms
{
internal delegate void DOptObj(params object[] ary);
internal delegate void DOptDyn(params dynamic[] ary);
public class Foo
{
public void M01(params dynamic[] d)
{
}
public void M02(params object[] d)
{
}
}
public class TestClass
{
[Fact]
public void RunTest()
{
start.DynamicCSharpRunTest();
}
}
public struct start
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
static public int MainMethod()
{
Foo foo = new Foo();
DOptObj dobj01 = new DOptObj(foo.M01);
DOptObj dobj02 = new DOptObj(foo.M02);
DOptDyn ddyn01 = new DOptDyn(foo.M01);
DOptDyn ddyn02 = new DOptDyn(foo.M02);
// Assert
dobj01(1, 2, 3);
dobj02(1, 2, 3);
ddyn01(1, 2, 3);
ddyn02(1, 2, 3);
return 0;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic001.generic001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic001.generic001;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic d = new SubGenericClass<int>();
d.myDel += (GenDlg<int>)null;
d.myDel -= (GenDlg<int>)null;
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<T>(int t);
public class SubGenericClass<T>
{
public GenDlg<T> myDel;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic002.generic002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic002.generic002;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(39,28\).*CS0067</Expects>
using System;
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new SubGenericClass<int>();
t.Foo(4);
var p = new Program();
dynamic d = new SubGenericClass<int>();
d.myDel += (GenDlg<int>)p.GetMe();
d.myDel -= (GenDlg<int>)p.GetMe();
d = new SubGenericClass<string>();
d.vEv += (GenDlg<string>)null;
d.vEv -= (GenDlg<string>)null;
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<out T>(int t);
public class SubGenericClass<T>
{
public GenDlg<T> myDel;
public event GenDlg<T> vEv;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic003.generic003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic003.generic003;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(42,31\).*CS0067</Expects>
using System;
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new SubGenericClass<int>();
t.Foo(4);
dynamic d = new SubGenericClass<int>();
d.myDel += (GenDlg<C<int>>)null;
d.myDel -= (GenDlg<C<int>>)null;
d = new SubGenericClass<string>();
d.vEv += (GenDlg<C<string>>)null;
d.vEv -= (GenDlg<C<string>>)null;
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<T>(int t);
public class C<T>
{
}
public class SubGenericClass<T>
{
public GenDlg<C<T>> myDel;
public event GenDlg<C<T>> vEv;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic004.generic004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic004.generic004;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(41,28\).*CS0067</Expects>
using System;
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new SubGenericClass<int>();
t.Foo(4);
dynamic d = new SubGenericClass<int>();
d.myDel += (GenDlg<int>)(x => 4);
d.myDel -= (GenDlg<int>)(x => 4);
d = new SubGenericClass<string>();
d.vEv += (GenDlg<string>)(x => "");
d.vEv -= (GenDlg<string>)(x => "");
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<T>(int t);
public class SubGenericClass<T>
{
public GenDlg<T> myDel;
public event GenDlg<T> vEv;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic005.generic005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic005.generic005;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(48,28\).*CS0067</Expects>
using System;
public class C
{
public static implicit operator GenDlg<int>(C c)
{
return null;
}
}
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new SubGenericClass<int>();
t.Foo(4);
dynamic d = new SubGenericClass<int>();
d.myDel += (GenDlg<int>)new C(); //RuntimeBinderException
d.myDel -= (GenDlg<int>)(x => 4); //RuntimeBinderException
d = new SubGenericClass<string>();
d.vEv += (GenDlg<string>)(x => ""); //RuntimeBinderException
d.vEv -= (GenDlg<string>)(x => ""); //RuntimeBinderException
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<T>(int t);
public class SubGenericClass<T>
{
public GenDlg<T> myDel;
public event GenDlg<T> vEv;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic006.generic006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.dlgateEvent.dlgate.generic006.generic006;
// <Title>+= on a generic event does work</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(43,35\).*CS0067</Expects>
using System;
public class C
{
public static implicit operator GenDlg<int>(C c)
{
return null;
}
}
public class Program
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new SubGenericClass<int>();
t.Foo(4);
dynamic d = new SubGenericClass<int>();
SubGenericClass<int>.myDel += (GenDlg<int>)(dynamic)new C();
SubGenericClass<int>.vEv += (GenDlg<int>)(dynamic)new C();
return 0;
}
public GenDlg<int> GetMe()
{
return null;
}
}
public delegate T GenDlg<T>(int t);
public class SubGenericClass<T>
{
public static GenDlg<T> myDel;
public static event GenDlg<T> vEv;
public void Foo<U>(U x)
{
GenDlg<U> d = null;
d += (GenDlg<U>)null;
}
}
// </Code>
}
| |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.ServiceModel;
using System.Threading;
using L4p.Common.DumpToLogs;
using L4p.Common.Extensions;
using L4p.Common.Helpers;
using L4p.Common.IoCs;
using L4p.Common.Json;
using L4p.Common.Loggers;
using L4p.Common.PubSub.client.Io;
namespace L4p.Common.PubSub.client
{
interface IMessengerEngine : IHaveDump
{
void SendHelloMsg(comm.HelloMsg msg);
void SendGoodbyeMsg(string agentUri);
void SendPublishMsg(string agentUri, comm.PublishMsg msg);
void FilterTopicMsgs(string agentUri, comm.TopicFilterMsg msg);
void AgentIsHere(string agentUri);
void AgentIsGone(string agentUri);
void IoFailed(IAgentWriter proxy, comm.IoMsg msg, Exception ex, string at);
void Idle();
}
class MessengerEngine : IMessengerEngine
{
#region counters
class Counters
{
public long HelloMsgSent;
public long GoodbyeMsgSent;
public long PublishMsgSent;
public long FilterTopicMsgSent;
public long HeartbeatMsgSent;
public long HubMsgSent;
public long HubMsgFailed;
public long IoFailed;
public long MsgNotSent;
public long IoRetry;
public long PublishMsgIoFailed;
public long FilterInfoIoMsgFailed;
public long TopicFilterMsgIoFailed;
public long HeartbeatMsgIoFailed;
public long UnknownMsgIoFailed;
public long EndpointNotFound;
}
#endregion
#region members
private static readonly comm.HeartbeatMsg _heartbeatMsg = new comm.HeartbeatMsg();
private readonly Dictionary<Type, Action<comm.IoMsg>> _msg2failureHandler;
private readonly Counters _counters;
private readonly string _hubUri;
private readonly ILogFile _log;
private readonly ISignalsConfigRa _configRa;
private readonly IAgentConnector _connector;
private readonly IAgentsRepo _agents;
private readonly SignalsConfig _cachedConfig;
#endregion
#region construction
public static IMessengerEngine New(IIoC ioc)
{
return
new MessengerEngine(ioc);
}
private MessengerEngine(IIoC ioc)
{
_msg2failureHandler = new Dictionary<Type, Action<comm.IoMsg>> {
{typeof(comm.PublishMsg), msg => update_failure_counters((comm.PublishMsg) msg)},
{typeof(comm.FilterInfo), msg => update_failure_counters((comm.FilterInfo) msg)},
{typeof(comm.TopicFilterMsg), msg => update_failure_counters((comm.TopicFilterMsg) msg)},
{typeof(comm.HeartbeatMsg), msg => update_failure_counters((comm.HeartbeatMsg) msg)}
};
_counters = new Counters();
_configRa = ioc.Resolve<ISignalsConfigRa>();
var config = _configRa.Values;
_cachedConfig = config;
_log = ThrottledLog.NewSync(config.ThrottledLogTtl, ioc.Resolve<ILogFile>());
_hubUri = _configRa.MakeHubUri();
_connector = ioc.Resolve<IAgentConnector>();
_agents = AgentsRepo.NewSync();
}
#endregion
#region private
private void update_failure_counters(comm.PublishMsg msg)
{
Interlocked.Increment(ref _counters.PublishMsgIoFailed);
var topic = msg.Topic;
Interlocked.Increment(ref topic.Details.Counters.IoFailed);
if (msg.RetryCount == 0)
Interlocked.Increment(ref topic.Details.Counters.MsgNotSent);
}
private void update_failure_counters(comm.FilterInfo msg)
{
Interlocked.Increment(ref _counters.FilterInfoIoMsgFailed);
}
private void update_failure_counters(comm.TopicFilterMsg msg)
{
Interlocked.Increment(ref _counters.TopicFilterMsgIoFailed);
}
private void update_failure_counters(comm.HeartbeatMsg msg)
{
Interlocked.Increment(ref _counters.HeartbeatMsgIoFailed);
}
private void update_failure_counters(comm.IoMsg msg)
{
Action<comm.IoMsg> handler;
if (!_msg2failureHandler.TryGetValue(msg.GetType(), out handler))
{
Interlocked.Increment(ref _counters.UnknownMsgIoFailed);
return;
}
try
{
handler(msg);
}
catch (Exception ex)
{
_log.Warn(ex, "Failed to handle failed message");
}
}
private void set_agent_proxy(string uri, IAgentWriter proxy)
{
var prev = _agents.SetAgentProxy(uri, proxy);
if (prev == null)
return;
_connector.DisconnectAgent(prev);
}
private IAgentWriter get_agent_proxy(string agentUri)
{
var proxy = _agents.GetAgentProxy(agentUri);
if (proxy != null)
return proxy;
proxy = _connector.ConnectAgent(agentUri, this);
set_agent_proxy(agentUri, proxy);
return proxy;
}
private comm.ISignalsHub create_hub_proxy(string uri)
{
var proxy = wcf.SignalsHub.New(uri);
return proxy;
}
private void send_message(string agentUri, string tag, Action action)
{
try
{
action();
Interlocked.Increment(ref _counters.HubMsgSent);
}
catch (EndpointNotFoundException)
{
Interlocked.Increment(ref _counters.EndpointNotFound);
Interlocked.Increment(ref _counters.HubMsgFailed);
}
catch (Exception ex)
{
_log.Error(ex, "Failure while sending message '{0}' to '{1}'", tag, agentUri);
Interlocked.Increment(ref _counters.HubMsgFailed);
}
}
private void retry_io(comm.IoMsg msg)
{
var retryIt = msg.Retry;
for (;;) // do only once
{
if (retryIt == null)
break;
if (msg.RetryCount == 0)
break;
Interlocked.Increment(ref _counters.IoRetry);
msg.RetryCount--;
retryIt();
return;
}
Interlocked.Increment(ref _counters.MsgNotSent);
}
#endregion
#region interface
void IMessengerEngine.SendHelloMsg(comm.HelloMsg msg)
{
using (var hub = create_hub_proxy(_hubUri))
{
send_message(_hubUri, "client.hello",
() => hub.Hello(msg));
}
Interlocked.Increment(ref _counters.HelloMsgSent);
}
void IMessengerEngine.SendGoodbyeMsg(string agentUri)
{
using (var hub = create_hub_proxy(_hubUri))
{
send_message(_hubUri, "client.goodbye",
() => hub.Goodbye(agentUri));
}
Interlocked.Increment(ref _counters.GoodbyeMsgSent);
}
void IMessengerEngine.SendPublishMsg(string agentUri, comm.PublishMsg msg)
{
Action sendIt = () => {
var proxy = get_agent_proxy(agentUri);
proxy.Publish(msg);
};
msg.Retry = sendIt;
msg.RetryCount = _cachedConfig.Client.PublishRetryCount;
sendIt();
Interlocked.Increment(ref _counters.PublishMsgSent);
}
void IMessengerEngine.FilterTopicMsgs(string agentUri, comm.TopicFilterMsg msg)
{
var proxy = get_agent_proxy(agentUri);
proxy.FilterTopicMsgs(msg);
Interlocked.Increment(ref _counters.FilterTopicMsgSent);
}
void IMessengerEngine.AgentIsHere(string agentUri)
{
var proxy = get_agent_proxy(agentUri);
proxy.Heartbeat(_heartbeatMsg);
Interlocked.Increment(ref _counters.HeartbeatMsgSent);
}
void IMessengerEngine.AgentIsGone(string agentUri)
{
var proxy = _agents.RemoveAgent(agentUri);
if (proxy == null)
return;
_connector.DisconnectAgent(proxy);
}
void IMessengerEngine.IoFailed(IAgentWriter proxy, comm.IoMsg msg, Exception ex, string at)
{
Interlocked.Increment(ref _counters.IoFailed);
update_failure_counters(msg);
var msgType = msg.GetType().Name;
_log.Error("Msg ({0}): io error in '{1}' of '{2}' (retryCount={3}) to agent '{4}' (agent will be reconnected); {5}",
msg.Guid.AsStr(), at, msgType, msg.RetryCount, msg.AgentUri, ex.Message);
var removedAgent = _agents.RemoveAgent(proxy);
if (removedAgent == null)
return;
_connector.DisconnectAgent(removedAgent);
retry_io(msg);
}
void IMessengerEngine.Idle()
{
var config = _configRa.Values;
var proxies = _agents.GetAll();
foreach (var proxy in proxies)
{
if (proxy.NonActiveSpan < config.Client.HeartbeatSpan)
continue;
proxy.Heartbeat(_heartbeatMsg);
Interlocked.Increment(ref _counters.HeartbeatMsgSent);
}
}
ExpandoObject IHaveDump.Dump(dynamic root)
{
if (root == null)
root = new ExpandoObject();
root.HubUri = _hubUri;
root.Counters = _counters;
var agents = _agents.GetAll();
var list = new List<object>();
foreach (var proxy in agents)
{
list.Add(proxy.Dump());
}
root.Agents = list.ToArray();
return root;
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.DDF
{
using System;
using System.IO;
using System.Text;
using System.Collections;
using NPOI.Util;
using NPOI.HSSF.Record;
/// <summary>
/// This record defines the drawing groups used for a particular sheet.
/// </summary>
internal class EscherDggRecord : EscherRecord
{
public const short RECORD_ID = unchecked((short)0xF006);
public const String RECORD_DESCRIPTION = "MsofbtDgg";
private int field_1_shapeIdMax;
// private int field_2_numIdClusters; // for some reason the number of clusters is actually the real number + 1
private int field_3_numShapesSaved;
private int field_4_drawingsSaved;
private FileIdCluster[] field_5_fileIdClusters;
private int maxDgId;
internal class FileIdCluster
{
public FileIdCluster(int drawingGroupId, int numShapeIdsUsed)
{
this.field_1_drawingGroupId = drawingGroupId;
this.field_2_numShapeIdsUsed = numShapeIdsUsed;
}
private int field_1_drawingGroupId;
private int field_2_numShapeIdsUsed;
public int DrawingGroupId
{
get { return field_1_drawingGroupId; }
}
public int NumShapeIdsUsed
{
get { return field_2_numShapeIdsUsed; }
}
public void IncrementShapeId()
{
this.field_2_numShapeIdsUsed++;
}
}
/// <summary>
/// This method deSerializes the record from a byte array.
/// </summary>
/// <param name="data">The byte array containing the escher record information</param>
/// <param name="offset">The starting offset into data</param>
/// <param name="recordFactory">May be null since this is not a container record.</param>
/// <returns>The number of bytes Read from the byte array.</returns>
public override int FillFields(byte[] data, int offset, EscherRecordFactory recordFactory)
{
int bytesRemaining = ReadHeader(data, offset);
int pos = offset + 8;
int size = 0;
field_1_shapeIdMax = LittleEndian.GetInt(data, pos + size); size += 4;
int field_2_numIdClusters = LittleEndian.GetInt(data, pos + size); size += 4;
field_3_numShapesSaved = LittleEndian.GetInt(data, pos + size); size += 4;
field_4_drawingsSaved = LittleEndian.GetInt(data, pos + size); size += 4;
field_5_fileIdClusters = new FileIdCluster[(bytesRemaining - size) / 8]; // Can't rely on field_2_numIdClusters
for (int i = 0; i < field_5_fileIdClusters.Length; i++)
{
field_5_fileIdClusters[i] = new FileIdCluster(LittleEndian.GetInt(data, pos + size), LittleEndian.GetInt(data, pos + size + 4));
maxDgId = Math.Max(maxDgId, field_5_fileIdClusters[i].DrawingGroupId);
size += 8;
}
bytesRemaining -= size;
if (bytesRemaining != 0)
throw new RecordFormatException("Expecting no remaining data but got " + bytesRemaining + " byte(s).");
return 8 + size + bytesRemaining;
}
/// <summary>
/// This method Serializes this escher record into a byte array.
/// </summary>
/// <param name="offset">The offset into data to start writing the record data to.</param>
/// <param name="data">The byte array to Serialize to.</param>
/// <param name="listener">a listener for begin and end serialization events.</param>
/// <returns>The number of bytes written.</returns>
public override int Serialize(int offset, byte[] data, EscherSerializationListener listener)
{
listener.BeforeRecordSerialize(offset, RecordId, this);
int pos = offset;
LittleEndian.PutShort(data, pos, Options); pos += 2;
LittleEndian.PutShort(data, pos, RecordId); pos += 2;
int remainingBytes = RecordSize - 8;
LittleEndian.PutInt(data, pos, remainingBytes); pos += 4;
LittleEndian.PutInt(data, pos, field_1_shapeIdMax); pos += 4;
LittleEndian.PutInt(data, pos, NumIdClusters); pos += 4;
LittleEndian.PutInt(data, pos, field_3_numShapesSaved); pos += 4;
LittleEndian.PutInt(data, pos, field_4_drawingsSaved); pos += 4;
for (int i = 0; i < field_5_fileIdClusters.Length; i++)
{
LittleEndian.PutInt(data, pos, field_5_fileIdClusters[i].DrawingGroupId); pos += 4;
LittleEndian.PutInt(data, pos, field_5_fileIdClusters[i].NumShapeIdsUsed); pos += 4;
}
listener.AfterRecordSerialize(pos, RecordId, RecordSize, this);
return RecordSize;
}
/// <summary>
/// Returns the number of bytes that are required to Serialize this record.
/// </summary>
/// <value>Number of bytes</value>
public override int RecordSize
{
get { return 8 + 16 + (8 * field_5_fileIdClusters.Length); }
}
/// <summary>
/// Return the current record id.
/// </summary>
/// <value>The 16 bit record id.</value>
public override short RecordId
{
get { return RECORD_ID; }
}
/// <summary>
/// The short name for this record
/// </summary>
/// <value></value>
public override String RecordName
{
get { return "Dgg"; }
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
String nl = Environment.NewLine;
// String extraData;
// MemoryStream b = new MemoryStream();
// try
// {
// HexDump.dump(this.remainingData, 0, b, 0);
// extraData = b.ToString();
// }
// catch ( Exception e )
// {
// extraData = "error";
// }
StringBuilder field_5_string = new StringBuilder();
for (int i = 0; i < field_5_fileIdClusters.Length; i++)
{
field_5_string.Append(" DrawingGroupId").Append(i + 1).Append(": ");
field_5_string.Append(field_5_fileIdClusters[i].DrawingGroupId);
field_5_string.Append(nl);
field_5_string.Append(" NumShapeIdsUsed").Append(i + 1).Append(": ");
field_5_string.Append(field_5_fileIdClusters[i].NumShapeIdsUsed);
field_5_string.Append(nl);
}
return GetType().Name + ":" + nl +
" RecordId: 0x" + HexDump.ToHex(RECORD_ID) + nl +
" Options: 0x" + HexDump.ToHex(Options) + nl +
" ShapeIdMax: " + field_1_shapeIdMax + nl +
" NumIdClusters: " + NumIdClusters + nl +
" NumShapesSaved: " + field_3_numShapesSaved + nl +
" DrawingsSaved: " + field_4_drawingsSaved + nl +
"" + field_5_string.ToString();
}
/// <summary>
/// Gets or sets the shape id max.
/// </summary>
/// <value>The shape id max.</value>
public int ShapeIdMax
{
get { return field_1_shapeIdMax; }
set { field_1_shapeIdMax = value; }
}
/// <summary>
/// Gets the Number of id clusters + 1
/// </summary>
/// <value>The num id clusters.</value>
public int NumIdClusters
{
get { return field_5_fileIdClusters.Length + 1; }
}
/// <summary>
/// Gets or sets the num shapes saved.
/// </summary>
/// <value>The num shapes saved.</value>
public int NumShapesSaved
{
get { return field_3_numShapesSaved; }
set { field_3_numShapesSaved = value; }
}
/// <summary>
/// Gets or sets the drawings saved.
/// </summary>
/// <value>The drawings saved.</value>
public int DrawingsSaved
{
get { return field_4_drawingsSaved; }
set { field_4_drawingsSaved = value; }
}
/// <summary>
/// Gets or sets the max drawing group id.
/// </summary>
/// <value>The max drawing group id.</value>
public int MaxDrawingGroupId
{
get { return maxDgId; }
set { maxDgId = value; }
}
/// <summary>
/// Gets or sets the file id clusters.
/// </summary>
/// <value>The file id clusters.</value>
public FileIdCluster[] FileIdClusters
{
get { return field_5_fileIdClusters; }
set { field_5_fileIdClusters = value; }
}
/// <summary>
/// Adds the cluster.
/// </summary>
/// <param name="dgId">The dg id.</param>
/// <param name="numShapedUsed">The num shaped used.</param>
public void AddCluster(int dgId, int numShapedUsed)
{
AddCluster(dgId, numShapedUsed, true);
}
private class EscherDggRecordComparer : IComparer
{
#region IComparer Members
public int Compare(object o1, object o2)
{
FileIdCluster f1 = (FileIdCluster)o1;
FileIdCluster f2 = (FileIdCluster)o2;
if (f1.DrawingGroupId == f2.DrawingGroupId)
return 0;
if (f1.DrawingGroupId < f2.DrawingGroupId)
return -1;
else
return +1;
}
#endregion
}
/// <summary>
/// Adds the cluster.
/// </summary>
/// <param name="dgId">id of the drawing group (stored in the record options)</param>
/// <param name="numShapedUsed">initial value of the numShapedUsed field</param>
/// <param name="sort">if set to <c>true</c> if true then sort clusters by drawing group id.(
/// In Excel the clusters are sorted but in PPT they are not).</param>
public void AddCluster(int dgId, int numShapedUsed, bool sort)
{
ArrayList clusters = new ArrayList(field_5_fileIdClusters);
clusters.Add(new FileIdCluster(dgId, numShapedUsed));
clusters.Sort(new EscherDggRecordComparer());
maxDgId = Math.Min(maxDgId, dgId);
field_5_fileIdClusters = (FileIdCluster[])clusters.ToArray(typeof(FileIdCluster));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Text.RegularExpressions.Tests
{
public class RegexMultipleMatchTests
{
[Fact]
public void Matches_MultipleCapturingGroups()
{
string[] expectedGroupValues = { "abracadabra", "abra", "cad" };
string[] expectedGroupCaptureValues = { "abracad", "abra" };
// Another example - given by Brad Merril in an article on RegularExpressions
Regex regex = new Regex(@"(abra(cad)?)+");
string input = "abracadabra1abracadabra2abracadabra3";
Match match = regex.Match(input);
while (match.Success)
{
string expected = "abracadabra";
Assert.Equal(expected, match.Value);
Assert.Equal(3, match.Groups.Count);
for (int i = 0; i < match.Groups.Count; i++)
{
Assert.Equal(expectedGroupValues[i], match.Groups[i].Value);
if (i == 1)
{
Assert.Equal(2, match.Groups[i].Captures.Count);
for (int j = 0; j < match.Groups[i].Captures.Count; j++)
{
Assert.Equal(expectedGroupCaptureValues[j], match.Groups[i].Captures[j].Value);
}
}
else if (i == 2)
{
Assert.Equal(1, match.Groups[i].Captures.Count);
Assert.Equal("cad", match.Groups[i].Captures[0].Value);
}
}
Assert.Equal(1, match.Captures.Count);
Assert.Equal("abracadabra", match.Captures[0].Value);
match = match.NextMatch();
}
}
public static IEnumerable<object[]> Matches_TestData()
{
yield return new object[]
{
"[0-9]", "12345asdfasdfasdfljkhsda67890", RegexOptions.None,
new CaptureData[]
{
new CaptureData("1", 0, 1),
new CaptureData("2", 1, 1),
new CaptureData("3", 2, 1),
new CaptureData("4", 3, 1),
new CaptureData("5", 4, 1),
new CaptureData("6", 24, 1),
new CaptureData("7", 25, 1),
new CaptureData("8", 26, 1),
new CaptureData("9", 27, 1),
new CaptureData("0", 28, 1),
}
};
yield return new object[]
{
"[a-z0-9]+", "[token1]? GARBAGEtoken2GARBAGE ;token3!", RegexOptions.None,
new CaptureData[]
{
new CaptureData("token1", 1, 6),
new CaptureData("token2", 17, 6),
new CaptureData("token3", 32, 6)
}
};
yield return new object[]
{
"(abc){2}", " !abcabcasl dkfjasiduf 12343214-//asdfjzpiouxoifzuoxpicvql23r\\` #$3245,2345278 :asdfas & 100% @daeeffga (ryyy27343) poiweurwabcabcasdfalksdhfaiuyoiruqwer{234}/[(132387 + x)]'aaa''?", RegexOptions.None,
new CaptureData[]
{
new CaptureData("abcabc", 2, 6),
new CaptureData("abcabc", 125, 6)
}
};
yield return new object[]
{
@"foo\d+", "0123456789foo4567890foo1foo 0987", RegexOptions.RightToLeft,
new CaptureData[]
{
new CaptureData("foo1", 20, 4),
new CaptureData("foo4567890", 10, 10),
}
};
yield return new object[]
{
"[a-z]", "a", RegexOptions.None,
new CaptureData[]
{
new CaptureData("a", 0, 1)
}
};
yield return new object[]
{
"[a-z]", "a1bc", RegexOptions.None,
new CaptureData[]
{
new CaptureData("a", 0, 1),
new CaptureData("b", 2, 1),
new CaptureData("c", 3, 1)
}
};
}
[Theory]
[MemberData(nameof(Matches_TestData))]
public void Matches(string pattern, string input, RegexOptions options, CaptureData[] expected)
{
if (options == RegexOptions.None)
{
Regex regexBasic = new Regex(pattern);
VerifyMatches(regexBasic.Matches(input), expected);
VerifyMatches(regexBasic.Match(input), expected);
VerifyMatches(Regex.Matches(input, pattern), expected);
VerifyMatches(Regex.Match(input, pattern), expected);
}
Regex regexAdvanced = new Regex(pattern, options);
VerifyMatches(regexAdvanced.Matches(input), expected);
VerifyMatches(regexAdvanced.Match(input), expected);
VerifyMatches(Regex.Matches(input, pattern, options), expected);
VerifyMatches(Regex.Match(input, pattern, options), expected);
}
public static void VerifyMatches(Match match, CaptureData[] expected)
{
for (int i = 0; match.Success; i++, match = match.NextMatch())
{
VerifyMatch(match, expected[i]);
}
}
public static void VerifyMatches(MatchCollection matches, CaptureData[] expected)
{
Assert.Equal(expected.Length, matches.Count);
for (int i = 0; i < matches.Count; i++)
{
VerifyMatch(matches[i], expected[i]);
}
}
public static void VerifyMatch(Match match, CaptureData expected)
{
Assert.True(match.Success);
Assert.Equal(expected.Value, match.Value);
Assert.Equal(expected.Index, match.Index);
Assert.Equal(expected.Length, match.Length);
Assert.Equal(expected.Value, match.Groups[0].Value);
Assert.Equal(expected.Index, match.Groups[0].Index);
Assert.Equal(expected.Length, match.Groups[0].Length);
Assert.Equal(1, match.Captures.Count);
Assert.Equal(expected.Value, match.Captures[0].Value);
Assert.Equal(expected.Index, match.Captures[0].Index);
Assert.Equal(expected.Length, match.Captures[0].Length);
}
[Fact]
public void Matches_Invalid()
{
// Input is null
Assert.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern"));
Assert.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern", RegexOptions.None));
Assert.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1)));
Assert.Throws<ArgumentNullException>("input", () => new Regex("pattern").Matches(null));
Assert.Throws<ArgumentNullException>("input", () => new Regex("pattern").Matches(null, 0));
// Pattern is null
Assert.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null));
Assert.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null, RegexOptions.None));
Assert.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null, RegexOptions.None, TimeSpan.FromSeconds(1)));
// Options are invalid
Assert.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)(-1)));
Assert.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)(-1), TimeSpan.FromSeconds(1)));
Assert.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)0x400));
Assert.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)0x400, TimeSpan.FromSeconds(1)));
// MatchTimeout is invalid
Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Matches("input", "pattern", RegexOptions.None, TimeSpan.Zero));
Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Matches("input", "pattern", RegexOptions.None, TimeSpan.Zero));
// Start is invalid
Assert.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Matches("input", -1));
Assert.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Matches("input", 6));
}
[Fact]
public void NextMatch_EmptyMatch_ReturnsEmptyMatch()
{
Assert.Same(Match.Empty, Match.Empty.NextMatch());
}
}
}
| |
#region License
/**
* Copyright (c) 2011 Kerry Snyder
* Copyright (c) 2012 Luigi Grilli
*
* 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.Threading;
using System.Runtime.InteropServices;
namespace Libuv
{
[StructLayout(LayoutKind.Sequential)]
internal struct uv_req_t
{
internal IntPtr data;
internal uv_req_type type;
}
[StructLayout(LayoutKind.Sequential)]
internal struct uv_process_options_t
{
internal uv_exit_cb exit_cb;
internal string file;
internal IntPtr[] args;
internal IntPtr[] env;
internal string cwd;
internal int windows_verbatim_arguments;
internal IntPtr stdin_stream;
internal IntPtr stdout_stream;
internal IntPtr stderr_stream;
}
[StructLayout(LayoutKind.Sequential)]
internal struct uv_buf_t
{
internal IntPtr len;
internal IntPtr data;
}
// From: http://www.elitepvpers.com/forum/co2-programming/159327-advanced-winsock-c.html
[StructLayout(LayoutKind.Sequential, Size = 16)]
internal struct sockaddr_in
{
internal short sin_family;
internal ushort sin_port;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
byte[] data;
}
// From: http://www.pinvoke.net/default.aspx/Structures/sockaddr_in6.html
[StructLayout(LayoutKind.Sequential, Size = 28)]
internal struct sockaddr_in6
{
internal short sin6_family;
internal ushort sin6_port;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 24)]
byte[] data;
}
internal enum uv_err_code
{
UV_UNKNOWN = -1,
UV_OK = 0,
UV_EOF,
UV_EACCESS,
UV_EAGAIN,
UV_EADDRINUSE,
UV_EADDRNOTAVAIL,
UV_EAFNOSUPPORT,
UV_EALREADY,
UV_EBADF,
UV_EBUSY,
UV_ECONNABORTED,
UV_ECONNREFUSED,
UV_ECONNRESET,
UV_EDESTADDRREQ,
UV_EFAULT,
UV_EHOSTUNREACH,
UV_EINTR,
UV_EINVAL,
UV_EISCONN,
UV_EMFILE,
UV_ENETDOWN,
UV_ENETUNREACH,
UV_ENFILE,
UV_ENOBUFS,
UV_ENOMEM,
UV_ENONET,
UV_ENOPROTOOPT,
UV_ENOTCONN,
UV_ENOTSOCK,
UV_ENOTSUP,
UV_EPROTO,
UV_EPROTONOSUPPORT,
UV_EPROTOTYPE,
UV_ETIMEDOUT,
UV_ECHARSET,
UV_EAIFAMNOSUPPORT,
UV_EAINONAME,
UV_EAISERVICE,
UV_EAISOCKTYPE,
UV_ESHUTDOWN
}
internal enum uv_handle_type
{
UV_UNKNOWN_HANDLE = 0,
UV_ASYNC,
UV_CHECK,
UV_FS_EVENT,
UV_FS_POLL,
UV_HANDLE,
UV_IDLE,
UV_NAMED_PIPE,
UV_POLL,
UV_PREPARE,
UV_PROCESS,
UV_STREAM,
UV_TCP,
UV_TIMER,
UV_TTY,
UV_UDP,
UV_SIGNAL
}
internal enum uv_req_type
{
UV_UNKNOWN_REQ = 0,
UV_REQ,
UV_CONNECT,
UV_WRITE,
UV_SHUTDOWN,
UV_UDP_SEND,
UV_FS,
UV_WORK,
UV_GETADDRINFO
}
[Flags]
public enum uv_tcp_flags : uint
{
/// <summary>
/// Used with uv_tcp_bind, when an IPv6 address is used
/// </summary>
UV_TCP_IPV6ONLY = 1
}
#region Callbacks
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_shutdown_cb(IntPtr req, int status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_alloc_cb(
IntPtr stream,
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalType = "Libuv.SizeTMarshaler")]
SizeT suggested_size,
IntPtr buf
);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_read_cb(
IntPtr req,
int nread,
IntPtr buf
); //buf = uv_buf_t
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_write_cb(IntPtr req, int status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_connect_cb(IntPtr conn, int status); //uv_connect_t*
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_close_cb(IntPtr conn);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_connection_cb(IntPtr server, int status); //uv_stream_t* server
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_watcher_cb(IntPtr watcher, int status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_timer_cb(IntPtr timer);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_exit_cb(IntPtr handle, int exit_status, int term_signal); // uv_process_t*
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_fs_cb(IntPtr req); // uv_fs_t*
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_thread_run(IntPtr arg);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_work_cb(IntPtr req); //uv_work_t* req
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_after_work_cb(IntPtr req, int status); //uv_work_t* req
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void uv_getaddrinfo_cb(IntPtr req, int status, IntPtr res); //uv_getaddrinfo_t* req, struct addrinfo* res
#endregion
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
namespace NUnit.Framework.Assertions
{
[TestFixture, Category("Generics")]
public class NullableTypesTests
{
[Test]
public void CanTestForNull()
{
int? nullInt = null;
int? five = 5;
Assert.IsNull(nullInt);
Assert.IsNotNull(five);
Assert.That(nullInt, Is.Null);
Assert.That(five, Is.Not.Null);
}
[Test]
public void CanCompareNullableInts()
{
int? five = 5;
int? answer = 2 + 3;
Assert.AreEqual(five, answer);
Assert.AreEqual(five, 5);
Assert.AreEqual(5, five);
Assert.That(five, Is.EqualTo(answer));
Assert.That(five, Is.EqualTo(5));
Assert.That(5, Is.EqualTo(five));
// Assert.Greater(five, 3);
// Assert.GreaterOrEqual(five, 5);
// Assert.Less(3, five);
// Assert.LessOrEqual(5, five);
Assert.That(five, Is.GreaterThan(3));
Assert.That(five, Is.GreaterThanOrEqualTo(5));
//Assert.That(3, Is.LessThan(five));
//Assert.That(5, Is.LessThanOrEqualTo(five));
}
[Test]
public void CanCompareNullableDoubles()
{
double? five = 5.0;
double? answer = 2.0 + 3.0;
Assert.AreEqual(five, answer);
Assert.AreEqual(five, 5.0);
Assert.AreEqual(5.0, five);
Assert.That(five, Is.EqualTo(answer));
Assert.That(five, Is.EqualTo(5.0));
Assert.That(5.0, Is.EqualTo(five));
// Assert.Greater(five, 3.0);
// Assert.GreaterOrEqual(five, 5.0);
// Assert.Less(3.0, five);
// Assert.LessOrEqual(5.0, five);
Assert.That(five, Is.GreaterThan(3.0));
Assert.That(five, Is.GreaterThanOrEqualTo(5.0));
//Assert.That(3.0, Is.LessThan(five));
//Assert.That(5.0, Is.LessThanOrEqualTo(five));
}
[Test]
public void CanTestForNaN()
{
double? anNaN = Double.NaN;
Assert.IsNaN(anNaN);
Assert.That(anNaN, Is.NaN);
}
[Test]
public void CanCompareNullableDecimals()
{
decimal? five = 5m;
decimal? answer = 2m + 3m;
Assert.AreEqual(five, answer);
Assert.AreEqual(five, 5m);
Assert.AreEqual(5m, five);
Assert.That(five, Is.EqualTo(answer));
Assert.That(five, Is.EqualTo(5m));
Assert.That(5m, Is.EqualTo(five));
// Assert.Greater(five, 3m);
// Assert.GreaterOrEqual(five, 5m);
// Assert.Less(3m, five);
// Assert.LessOrEqual(5m, five);
Assert.That(five, Is.GreaterThan(3m));
Assert.That(five, Is.GreaterThanOrEqualTo(5m));
//Assert.That(3m, Is.LessThan(five));
//Assert.That(5m, Is.LessThanOrEqualTo(five));
}
[Test]
public void CanCompareWithTolerance()
{
double? five = 5.0;
Assert.AreEqual(5.0000001, five, .0001);
Assert.That( five, Is.EqualTo(5.0000001).Within(.0001));
float? three = 3.0f;
Assert.AreEqual(3.00001f, three, .001);
Assert.That( three, Is.EqualTo(3.00001f).Within(.001));
}
private enum Colors
{
Red,
Blue,
Green
}
[Test]
public void CanCompareNullableEnums()
{
Colors? color = Colors.Red;
Colors? other = Colors.Red;
Assert.AreEqual(color, other);
Assert.AreEqual(color, Colors.Red);
Assert.AreEqual(Colors.Red, color);
}
[Test]
public void CanCompareNullableMixedNumerics()
{
int? int5 = 5;
double? double5 = 5.0;
decimal? decimal5 = 5.00m;
Assert.AreEqual(int5, double5);
Assert.AreEqual(int5, decimal5);
Assert.AreEqual(double5, int5);
Assert.AreEqual(double5, decimal5);
Assert.AreEqual(decimal5, int5);
Assert.AreEqual(decimal5, double5);
Assert.That(int5, Is.EqualTo(double5));
Assert.That(int5, Is.EqualTo(decimal5));
Assert.That(double5, Is.EqualTo(int5));
Assert.That(double5, Is.EqualTo(decimal5));
Assert.That(decimal5, Is.EqualTo(int5));
Assert.That(decimal5, Is.EqualTo(double5));
Assert.AreEqual(5, double5);
Assert.AreEqual(5, decimal5);
Assert.AreEqual(5.0, int5);
Assert.AreEqual(5.0, decimal5);
Assert.AreEqual(5m, int5);
Assert.AreEqual(5m, double5);
Assert.That(5, Is.EqualTo(double5));
Assert.That(5, Is.EqualTo(decimal5));
Assert.That(5.0, Is.EqualTo(int5));
Assert.That(5.0, Is.EqualTo(decimal5));
Assert.That(5m, Is.EqualTo(int5));
Assert.That(5m, Is.EqualTo(double5));
Assert.AreEqual(double5, 5);
Assert.AreEqual(decimal5, 5);
Assert.AreEqual(int5, 5.0);
Assert.AreEqual(decimal5, 5.0);
Assert.AreEqual(int5, 5m);
Assert.AreEqual(double5, 5m);
Assert.That(double5, Is.EqualTo(5));
Assert.That(decimal5, Is.EqualTo(5));
Assert.That(int5, Is.EqualTo(5.0));
Assert.That(decimal5, Is.EqualTo(5.0));
Assert.That(int5, Is.EqualTo(5m));
Assert.That(double5, Is.EqualTo(5m));
// Assert.Greater(int5, 3.0);
// Assert.Greater(int5, 3m);
// Assert.Greater(double5, 3);
// Assert.Greater(double5, 3m);
// Assert.Greater(decimal5, 3);
// Assert.Greater(decimal5, 3.0);
Assert.That(int5, Is.GreaterThan(3.0));
Assert.That(int5, Is.GreaterThan(3m));
Assert.That(double5, Is.GreaterThan(3));
Assert.That(double5, Is.GreaterThan(3m));
Assert.That(decimal5, Is.GreaterThan(3));
Assert.That(decimal5, Is.GreaterThan(3.0));
// Assert.Less(3.0, int5);
// Assert.Less(3m, int5);
// Assert.Less(3, double5);
// Assert.Less(3m, double5);
// Assert.Less(3, decimal5);
// Assert.Less(3.0, decimal5);
//Assert.That(3.0, Is.LessThan(int5));
//Assert.That(3m, Is.LessThan(int5));
//Assert.That(3, Is.LessThan(double5));
//Assert.That(3m, Is.LessThan(double5));
//Assert.That(3, Is.LessThan(decimal5));
//Assert.That(3.0, Is.LessThan(decimal5));
}
private struct MyStruct
{
int i;
string s;
public MyStruct(int i, string s)
{
this.i = i;
this.s = s;
}
}
[Test]
public void CanCompareNullableStructs()
{
MyStruct struct1 = new MyStruct(5, "Hello");
MyStruct struct2 = new MyStruct(5, "Hello");
Nullable<MyStruct> one = new MyStruct(5, "Hello");
Nullable<MyStruct> two = new MyStruct(5, "Hello");
Assert.AreEqual(struct1, struct2); // Control
Assert.AreEqual(one, two);
Assert.AreEqual(one, struct1);
Assert.AreEqual(struct2, two);
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using gagr = Google.Api.Gax.ResourceNames;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.RecaptchaEnterprise.V1Beta1
{
/// <summary>Settings for <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/> instances.</summary>
public sealed partial class RecaptchaEnterpriseServiceV1Beta1Settings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/>.
/// </summary>
/// <returns>A new instance of the default <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/>.</returns>
public static RecaptchaEnterpriseServiceV1Beta1Settings GetDefault() =>
new RecaptchaEnterpriseServiceV1Beta1Settings();
/// <summary>
/// Constructs a new <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/> object with default settings.
/// </summary>
public RecaptchaEnterpriseServiceV1Beta1Settings()
{
}
private RecaptchaEnterpriseServiceV1Beta1Settings(RecaptchaEnterpriseServiceV1Beta1Settings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CreateAssessmentSettings = existing.CreateAssessmentSettings;
AnnotateAssessmentSettings = existing.AnnotateAssessmentSettings;
CreateKeySettings = existing.CreateKeySettings;
ListKeysSettings = existing.ListKeysSettings;
GetKeySettings = existing.GetKeySettings;
UpdateKeySettings = existing.UpdateKeySettings;
DeleteKeySettings = existing.DeleteKeySettings;
OnCopy(existing);
}
partial void OnCopy(RecaptchaEnterpriseServiceV1Beta1Settings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.CreateAssessment</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.CreateAssessmentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateAssessmentSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.AnnotateAssessment</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.AnnotateAssessmentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings AnnotateAssessmentSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.CreateKey</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.CreateKeyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateKeySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.ListKeys</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.ListKeysAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListKeysSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.GetKey</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.GetKeyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetKeySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.UpdateKey</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.UpdateKeyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateKeySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.DeleteKey</c> and
/// <c>RecaptchaEnterpriseServiceV1Beta1Client.DeleteKeyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteKeySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/> object.</returns>
public RecaptchaEnterpriseServiceV1Beta1Settings Clone() => new RecaptchaEnterpriseServiceV1Beta1Settings(this);
}
/// <summary>
/// Builder class for <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
public sealed partial class RecaptchaEnterpriseServiceV1Beta1ClientBuilder : gaxgrpc::ClientBuilderBase<RecaptchaEnterpriseServiceV1Beta1Client>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public RecaptchaEnterpriseServiceV1Beta1Settings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public RecaptchaEnterpriseServiceV1Beta1ClientBuilder()
{
UseJwtAccessWithScopes = RecaptchaEnterpriseServiceV1Beta1Client.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref RecaptchaEnterpriseServiceV1Beta1Client client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<RecaptchaEnterpriseServiceV1Beta1Client> task);
/// <summary>Builds the resulting client.</summary>
public override RecaptchaEnterpriseServiceV1Beta1Client Build()
{
RecaptchaEnterpriseServiceV1Beta1Client client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<RecaptchaEnterpriseServiceV1Beta1Client> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<RecaptchaEnterpriseServiceV1Beta1Client> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private RecaptchaEnterpriseServiceV1Beta1Client BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return RecaptchaEnterpriseServiceV1Beta1Client.Create(callInvoker, Settings);
}
private async stt::Task<RecaptchaEnterpriseServiceV1Beta1Client> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return RecaptchaEnterpriseServiceV1Beta1Client.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => RecaptchaEnterpriseServiceV1Beta1Client.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
RecaptchaEnterpriseServiceV1Beta1Client.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => RecaptchaEnterpriseServiceV1Beta1Client.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>RecaptchaEnterpriseServiceV1Beta1 client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to determine the likelihood an event is legitimate.
/// </remarks>
public abstract partial class RecaptchaEnterpriseServiceV1Beta1Client
{
/// <summary>
/// The default endpoint for the RecaptchaEnterpriseServiceV1Beta1 service, which is a host of
/// "recaptchaenterprise.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "recaptchaenterprise.googleapis.com:443";
/// <summary>The default RecaptchaEnterpriseServiceV1Beta1 scopes.</summary>
/// <remarks>
/// The default RecaptchaEnterpriseServiceV1Beta1 scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
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="RecaptchaEnterpriseServiceV1Beta1Client"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="RecaptchaEnterpriseServiceV1Beta1ClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/>.</returns>
public static stt::Task<RecaptchaEnterpriseServiceV1Beta1Client> CreateAsync(st::CancellationToken cancellationToken = default) =>
new RecaptchaEnterpriseServiceV1Beta1ClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="RecaptchaEnterpriseServiceV1Beta1ClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/>.</returns>
public static RecaptchaEnterpriseServiceV1Beta1Client Create() =>
new RecaptchaEnterpriseServiceV1Beta1ClientBuilder().Build();
/// <summary>
/// Creates a <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/> 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="RecaptchaEnterpriseServiceV1Beta1Settings"/>.</param>
/// <returns>The created <see cref="RecaptchaEnterpriseServiceV1Beta1Client"/>.</returns>
internal static RecaptchaEnterpriseServiceV1Beta1Client Create(grpccore::CallInvoker callInvoker, RecaptchaEnterpriseServiceV1Beta1Settings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client grpcClient = new RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client(callInvoker);
return new RecaptchaEnterpriseServiceV1Beta1ClientImpl(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 RecaptchaEnterpriseServiceV1Beta1 client</summary>
public virtual RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </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 Assessment CreateAssessment(CreateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </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<Assessment> CreateAssessmentAsync(CreateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </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<Assessment> CreateAssessmentAsync(CreateAssessmentRequest request, st::CancellationToken cancellationToken) =>
CreateAssessmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Assessment CreateAssessment(string parent, Assessment assessment, gaxgrpc::CallSettings callSettings = null) =>
CreateAssessment(new CreateAssessmentRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
Assessment = gax::GaxPreconditions.CheckNotNull(assessment, nameof(assessment)),
}, callSettings);
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </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<Assessment> CreateAssessmentAsync(string parent, Assessment assessment, gaxgrpc::CallSettings callSettings = null) =>
CreateAssessmentAsync(new CreateAssessmentRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
Assessment = gax::GaxPreconditions.CheckNotNull(assessment, nameof(assessment)),
}, callSettings);
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </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<Assessment> CreateAssessmentAsync(string parent, Assessment assessment, st::CancellationToken cancellationToken) =>
CreateAssessmentAsync(parent, assessment, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Assessment CreateAssessment(gagr::ProjectName parent, Assessment assessment, gaxgrpc::CallSettings callSettings = null) =>
CreateAssessment(new CreateAssessmentRequest
{
ParentAsProjectName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
Assessment = gax::GaxPreconditions.CheckNotNull(assessment, nameof(assessment)),
}, callSettings);
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </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<Assessment> CreateAssessmentAsync(gagr::ProjectName parent, Assessment assessment, gaxgrpc::CallSettings callSettings = null) =>
CreateAssessmentAsync(new CreateAssessmentRequest
{
ParentAsProjectName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
Assessment = gax::GaxPreconditions.CheckNotNull(assessment, nameof(assessment)),
}, callSettings);
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </summary>
/// <param name="parent">
/// Required. The name of the project in which the assessment will be created,
/// in the format "projects/{project_number}".
/// </param>
/// <param name="assessment">
/// Required. The assessment details.
/// </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<Assessment> CreateAssessmentAsync(gagr::ProjectName parent, Assessment assessment, st::CancellationToken cancellationToken) =>
CreateAssessmentAsync(parent, assessment, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </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 AnnotateAssessmentResponse AnnotateAssessment(AnnotateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </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<AnnotateAssessmentResponse> AnnotateAssessmentAsync(AnnotateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </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<AnnotateAssessmentResponse> AnnotateAssessmentAsync(AnnotateAssessmentRequest request, st::CancellationToken cancellationToken) =>
AnnotateAssessmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual AnnotateAssessmentResponse AnnotateAssessment(string name, AnnotateAssessmentRequest.Types.Annotation annotation, gaxgrpc::CallSettings callSettings = null) =>
AnnotateAssessment(new AnnotateAssessmentRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
Annotation = annotation,
}, callSettings);
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </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<AnnotateAssessmentResponse> AnnotateAssessmentAsync(string name, AnnotateAssessmentRequest.Types.Annotation annotation, gaxgrpc::CallSettings callSettings = null) =>
AnnotateAssessmentAsync(new AnnotateAssessmentRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
Annotation = annotation,
}, callSettings);
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </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<AnnotateAssessmentResponse> AnnotateAssessmentAsync(string name, AnnotateAssessmentRequest.Types.Annotation annotation, st::CancellationToken cancellationToken) =>
AnnotateAssessmentAsync(name, annotation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual AnnotateAssessmentResponse AnnotateAssessment(AssessmentName name, AnnotateAssessmentRequest.Types.Annotation annotation, gaxgrpc::CallSettings callSettings = null) =>
AnnotateAssessment(new AnnotateAssessmentRequest
{
AssessmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
Annotation = annotation,
}, callSettings);
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </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<AnnotateAssessmentResponse> AnnotateAssessmentAsync(AssessmentName name, AnnotateAssessmentRequest.Types.Annotation annotation, gaxgrpc::CallSettings callSettings = null) =>
AnnotateAssessmentAsync(new AnnotateAssessmentRequest
{
AssessmentName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
Annotation = annotation,
}, callSettings);
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </summary>
/// <param name="name">
/// Required. The resource name of the Assessment, in the format
/// "projects/{project_number}/assessments/{assessment_id}".
/// </param>
/// <param name="annotation">
/// Required. The annotation that will be assigned to the Event.
/// </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<AnnotateAssessmentResponse> AnnotateAssessmentAsync(AssessmentName name, AnnotateAssessmentRequest.Types.Annotation annotation, st::CancellationToken cancellationToken) =>
AnnotateAssessmentAsync(name, annotation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a new reCAPTCHA Enterprise key.
/// </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 Key CreateKey(CreateKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a new reCAPTCHA Enterprise key.
/// </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<Key> CreateKeyAsync(CreateKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a new reCAPTCHA Enterprise key.
/// </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<Key> CreateKeyAsync(CreateKeyRequest request, st::CancellationToken cancellationToken) =>
CreateKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the list of all keys that belong to a project.
/// </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 pageable sequence of <see cref="Key"/> resources.</returns>
public virtual gax::PagedEnumerable<ListKeysResponse, Key> ListKeys(ListKeysRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the list of all keys that belong to a project.
/// </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 pageable asynchronous sequence of <see cref="Key"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListKeysResponse, Key> ListKeysAsync(ListKeysRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified key.
/// </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 Key GetKey(GetKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified key.
/// </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<Key> GetKeyAsync(GetKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified key.
/// </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<Key> GetKeyAsync(GetKeyRequest request, st::CancellationToken cancellationToken) =>
GetKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates the specified key.
/// </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 Key UpdateKey(UpdateKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the specified key.
/// </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<Key> UpdateKeyAsync(UpdateKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the specified key.
/// </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<Key> UpdateKeyAsync(UpdateKeyRequest request, st::CancellationToken cancellationToken) =>
UpdateKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes the specified key.
/// </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 void DeleteKey(DeleteKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified key.
/// </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 DeleteKeyAsync(DeleteKeyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified key.
/// </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 DeleteKeyAsync(DeleteKeyRequest request, st::CancellationToken cancellationToken) =>
DeleteKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>RecaptchaEnterpriseServiceV1Beta1 client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to determine the likelihood an event is legitimate.
/// </remarks>
public sealed partial class RecaptchaEnterpriseServiceV1Beta1ClientImpl : RecaptchaEnterpriseServiceV1Beta1Client
{
private readonly gaxgrpc::ApiCall<CreateAssessmentRequest, Assessment> _callCreateAssessment;
private readonly gaxgrpc::ApiCall<AnnotateAssessmentRequest, AnnotateAssessmentResponse> _callAnnotateAssessment;
private readonly gaxgrpc::ApiCall<CreateKeyRequest, Key> _callCreateKey;
private readonly gaxgrpc::ApiCall<ListKeysRequest, ListKeysResponse> _callListKeys;
private readonly gaxgrpc::ApiCall<GetKeyRequest, Key> _callGetKey;
private readonly gaxgrpc::ApiCall<UpdateKeyRequest, Key> _callUpdateKey;
private readonly gaxgrpc::ApiCall<DeleteKeyRequest, wkt::Empty> _callDeleteKey;
/// <summary>
/// Constructs a client wrapper for the RecaptchaEnterpriseServiceV1Beta1 service, with the specified gRPC
/// client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="RecaptchaEnterpriseServiceV1Beta1Settings"/> used within this client.
/// </param>
public RecaptchaEnterpriseServiceV1Beta1ClientImpl(RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client grpcClient, RecaptchaEnterpriseServiceV1Beta1Settings settings)
{
GrpcClient = grpcClient;
RecaptchaEnterpriseServiceV1Beta1Settings effectiveSettings = settings ?? RecaptchaEnterpriseServiceV1Beta1Settings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callCreateAssessment = clientHelper.BuildApiCall<CreateAssessmentRequest, Assessment>(grpcClient.CreateAssessmentAsync, grpcClient.CreateAssessment, effectiveSettings.CreateAssessmentSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateAssessment);
Modify_CreateAssessmentApiCall(ref _callCreateAssessment);
_callAnnotateAssessment = clientHelper.BuildApiCall<AnnotateAssessmentRequest, AnnotateAssessmentResponse>(grpcClient.AnnotateAssessmentAsync, grpcClient.AnnotateAssessment, effectiveSettings.AnnotateAssessmentSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callAnnotateAssessment);
Modify_AnnotateAssessmentApiCall(ref _callAnnotateAssessment);
_callCreateKey = clientHelper.BuildApiCall<CreateKeyRequest, Key>(grpcClient.CreateKeyAsync, grpcClient.CreateKey, effectiveSettings.CreateKeySettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateKey);
Modify_CreateKeyApiCall(ref _callCreateKey);
_callListKeys = clientHelper.BuildApiCall<ListKeysRequest, ListKeysResponse>(grpcClient.ListKeysAsync, grpcClient.ListKeys, effectiveSettings.ListKeysSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListKeys);
Modify_ListKeysApiCall(ref _callListKeys);
_callGetKey = clientHelper.BuildApiCall<GetKeyRequest, Key>(grpcClient.GetKeyAsync, grpcClient.GetKey, effectiveSettings.GetKeySettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetKey);
Modify_GetKeyApiCall(ref _callGetKey);
_callUpdateKey = clientHelper.BuildApiCall<UpdateKeyRequest, Key>(grpcClient.UpdateKeyAsync, grpcClient.UpdateKey, effectiveSettings.UpdateKeySettings).WithGoogleRequestParam("key.name", request => request.Key?.Name);
Modify_ApiCall(ref _callUpdateKey);
Modify_UpdateKeyApiCall(ref _callUpdateKey);
_callDeleteKey = clientHelper.BuildApiCall<DeleteKeyRequest, wkt::Empty>(grpcClient.DeleteKeyAsync, grpcClient.DeleteKey, effectiveSettings.DeleteKeySettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callDeleteKey);
Modify_DeleteKeyApiCall(ref _callDeleteKey);
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_CreateAssessmentApiCall(ref gaxgrpc::ApiCall<CreateAssessmentRequest, Assessment> call);
partial void Modify_AnnotateAssessmentApiCall(ref gaxgrpc::ApiCall<AnnotateAssessmentRequest, AnnotateAssessmentResponse> call);
partial void Modify_CreateKeyApiCall(ref gaxgrpc::ApiCall<CreateKeyRequest, Key> call);
partial void Modify_ListKeysApiCall(ref gaxgrpc::ApiCall<ListKeysRequest, ListKeysResponse> call);
partial void Modify_GetKeyApiCall(ref gaxgrpc::ApiCall<GetKeyRequest, Key> call);
partial void Modify_UpdateKeyApiCall(ref gaxgrpc::ApiCall<UpdateKeyRequest, Key> call);
partial void Modify_DeleteKeyApiCall(ref gaxgrpc::ApiCall<DeleteKeyRequest, wkt::Empty> call);
partial void OnConstruction(RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client grpcClient, RecaptchaEnterpriseServiceV1Beta1Settings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC RecaptchaEnterpriseServiceV1Beta1 client</summary>
public override RecaptchaEnterpriseServiceV1Beta1.RecaptchaEnterpriseServiceV1Beta1Client GrpcClient { get; }
partial void Modify_CreateAssessmentRequest(ref CreateAssessmentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_AnnotateAssessmentRequest(ref AnnotateAssessmentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_CreateKeyRequest(ref CreateKeyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListKeysRequest(ref ListKeysRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetKeyRequest(ref GetKeyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateKeyRequest(ref UpdateKeyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteKeyRequest(ref DeleteKeyRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </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 Assessment CreateAssessment(CreateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateAssessmentRequest(ref request, ref callSettings);
return _callCreateAssessment.Sync(request, callSettings);
}
/// <summary>
/// Creates an Assessment of the likelihood an event is legitimate.
/// </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<Assessment> CreateAssessmentAsync(CreateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateAssessmentRequest(ref request, ref callSettings);
return _callCreateAssessment.Async(request, callSettings);
}
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </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 AnnotateAssessmentResponse AnnotateAssessment(AnnotateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_AnnotateAssessmentRequest(ref request, ref callSettings);
return _callAnnotateAssessment.Sync(request, callSettings);
}
/// <summary>
/// Annotates a previously created Assessment to provide additional information
/// on whether the event turned out to be authentic or fradulent.
/// </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<AnnotateAssessmentResponse> AnnotateAssessmentAsync(AnnotateAssessmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_AnnotateAssessmentRequest(ref request, ref callSettings);
return _callAnnotateAssessment.Async(request, callSettings);
}
/// <summary>
/// Creates a new reCAPTCHA Enterprise key.
/// </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 Key CreateKey(CreateKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateKeyRequest(ref request, ref callSettings);
return _callCreateKey.Sync(request, callSettings);
}
/// <summary>
/// Creates a new reCAPTCHA Enterprise key.
/// </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<Key> CreateKeyAsync(CreateKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateKeyRequest(ref request, ref callSettings);
return _callCreateKey.Async(request, callSettings);
}
/// <summary>
/// Returns the list of all keys that belong to a project.
/// </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 pageable sequence of <see cref="Key"/> resources.</returns>
public override gax::PagedEnumerable<ListKeysResponse, Key> ListKeys(ListKeysRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListKeysRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListKeysRequest, ListKeysResponse, Key>(_callListKeys, request, callSettings);
}
/// <summary>
/// Returns the list of all keys that belong to a project.
/// </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 pageable asynchronous sequence of <see cref="Key"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListKeysResponse, Key> ListKeysAsync(ListKeysRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListKeysRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListKeysRequest, ListKeysResponse, Key>(_callListKeys, request, callSettings);
}
/// <summary>
/// Returns the specified key.
/// </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 Key GetKey(GetKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeyRequest(ref request, ref callSettings);
return _callGetKey.Sync(request, callSettings);
}
/// <summary>
/// Returns the specified key.
/// </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<Key> GetKeyAsync(GetKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeyRequest(ref request, ref callSettings);
return _callGetKey.Async(request, callSettings);
}
/// <summary>
/// Updates the specified key.
/// </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 Key UpdateKey(UpdateKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateKeyRequest(ref request, ref callSettings);
return _callUpdateKey.Sync(request, callSettings);
}
/// <summary>
/// Updates the specified key.
/// </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<Key> UpdateKeyAsync(UpdateKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateKeyRequest(ref request, ref callSettings);
return _callUpdateKey.Async(request, callSettings);
}
/// <summary>
/// Deletes the specified key.
/// </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 void DeleteKey(DeleteKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteKeyRequest(ref request, ref callSettings);
_callDeleteKey.Sync(request, callSettings);
}
/// <summary>
/// Deletes the specified key.
/// </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 DeleteKeyAsync(DeleteKeyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteKeyRequest(ref request, ref callSettings);
return _callDeleteKey.Async(request, callSettings);
}
}
public partial class ListKeysRequest : gaxgrpc::IPageRequest
{
}
public partial class ListKeysResponse : gaxgrpc::IPageResponse<Key>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Key> GetEnumerator() => Keys.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
//
// StackTest.cs
//
// Author:
// Ben Maurer (bmaurer@ximian.com)
//
#if NET_2_0
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
namespace MonoTests.System.Collections.Generic {
[TestFixture]
public class StackTest: Assertion
{
[Test]
public void TestCtor ()
{
Stack <int> a = new Stack <int> ();
Stack <int> b = new Stack <int> (1);
Stack <object> c = new Stack <object> ();
Stack <object> d = new Stack <object> (1);
Stack <object> e = new Stack <object> (0);
}
[Test]
[ExpectedException (typeof (ArgumentOutOfRangeException))]
public void TestCtorEx ()
{
Stack <int> a = new Stack <int> (-1);
}
[Test]
public void TestCtorEnum ()
{
List <int> l = new List <int> ();
l.Add (1);
l.Add (2);
l.Add (3);
Stack <int> s = new Stack <int> (l);
// Things get pop'd in reverse
AssertPop (s, 3);
AssertPop (s, 2);
AssertPop (s, 1);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void TestCtorEnumNull ()
{
Stack <int> s = new Stack <int> (null);
}
[Test]
public void TestClear()
{
Stack <int> s = new Stack <int> ();
s.Clear ();
AssertEquals (s.Count, 0);
s.Push (1);
s.Push (2);
AssertEquals (s.Count, 2);
s.Clear ();
AssertEquals (s.Count, 0);
}
[Test]
public void TestContains ()
{
Stack <int> s = new Stack <int> ();
AssertEquals (s.Contains (1), false);
s.Push (1);
AssertEquals (s.Contains (1), true);
AssertEquals (s.Contains (0), false);
}
[Test]
public void TestCopyTo ()
{
int [] x = new int [3];
Stack <int> z = new Stack <int> ();
z.Push (1);
z.Push (2);
x [0] = 10;
z.CopyTo (x, 1);
AssertEquals (x [0], 10);
AssertEquals (x [1], 2);
AssertEquals (x [2], 1);
}
[Test]
public void TestPeek ()
{
Stack <int> s = new Stack <int> ();
s.Push (1);
AssertEquals (s.Peek (), 1);
AssertEquals (s.Count, 1);
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void TestPeekEx ()
{
Stack <int> s = new Stack <int> ();
s.Peek ();
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void TestPeekEx2 ()
{
Stack <int> s = new Stack <int> ();
s.Push (1);
s.Pop ();
s.Peek ();
}
[Test]
public void TestPop ()
{
Stack <int> s = new Stack <int> ();
s.Push (1);
AssertEquals (s.Pop (), 1);
AssertEquals (s.Count, 0);
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void TestPopEx ()
{
Stack <int> s = new Stack <int> ();
s.Pop ();
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void TestPopEx2 ()
{
Stack <int> s = new Stack <int> ();
s.Push (1);
s.Pop ();
s.Pop ();
}
[Test]
public void TestPush ()
{
Stack <int> s = new Stack <int> ();
s.Push (1);
AssertEquals (s.Count, 1);
s.Push (2);
AssertEquals (s.Count, 2);
for (int i = 0; i < 100; i ++)
s.Push (i);
AssertEquals (s.Count, 102);
}
[Test]
public void TestToArray ()
{
Stack <int> s = new Stack <int> ();
int [] x = s.ToArray ();
AssertEquals (x.Length, 0);
s.Push (1);
x = s.ToArray ();
AssertEquals (x.Length, 1);
AssertEquals (x [0], 1);
}
[Test]
public void TestTrimToSize ()
{
Stack <int> s = new Stack <int> ();
s.TrimToSize ();
s.Push (1);
s.TrimToSize ();
}
[Test]
public void TestEnumerator ()
{
Stack <int> s = new Stack <int> ();
foreach (int x in s)
Fail ();
s.Push (1);
int i = 0;
foreach (int x in s) {
AssertEquals (i, 0);
AssertEquals (x, 1);
i ++;
}
i = 0;
s.Push (2);
s.Push (3);
foreach (int x in s) {
AssertEquals (x, 3 - i);
Assert (i < 3);
i ++;
}
}
void AssertPop <T> (Stack <T> s, T t)
{
AssertEquals (s.Pop (), t);
}
}
}
#endif
| |
//
// ListViewAccessible.cs
//
// Authors:
// Eitan Isaacson <eitan@ascender.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
// Copyright (C) 2009 Eitan Isaacson
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Collections.Generic;
using Hyena.Data.Gui;
namespace Hyena.Data.Gui.Accessibility
{
#if ENABLE_ATK
public partial class ListViewAccessible<T> : Hyena.Gui.BaseWidgetAccessible, ICellAccessibleParent
{
private ListView<T> list_view;
private Dictionary<int, ColumnCellAccessible> cell_cache;
public ListViewAccessible (GLib.Object widget) : base (widget as Gtk.Widget)
{
list_view = widget as ListView<T>;
// TODO replace with list_view.Name?
Name = "ListView";
Description = "ListView";
Role = Atk.Role.Table;
Parent = list_view.Parent.RefAccessible ();
cell_cache = new Dictionary<int, ColumnCellAccessible> ();
list_view.ModelChanged += (o, a) => OnModelChanged ();
list_view.Model.Reloaded += (o, a) => OnModelChanged ();
OnModelChanged ();
list_view.Selection.FocusChanged += OnSelectionFocusChanged;
list_view.ActiveColumnChanged += OnSelectionFocusChanged;
ListViewAccessible_Selection ();
ListViewAccessible_Table ();
}
protected override Atk.StateSet OnRefStateSet ()
{
Atk.StateSet states = base.OnRefStateSet ();
states.AddState (Atk.StateType.ManagesDescendants);
return states;
}
protected override int OnGetIndexInParent ()
{
for (int i=0; i < Parent.NAccessibleChildren; i++) {
if (Parent.RefAccessibleChild (i) == this) {
return i;
}
}
return -1;
}
protected override int OnGetNChildren ()
{
return n_columns * n_rows + n_columns;
}
protected override Atk.Object OnRefChild (int index)
{
ColumnCellAccessible child;
if (cell_cache.ContainsKey (index)) {
return cell_cache[index];
}
var columns = list_view.ColumnController.Where (c => c.Visible);
if (index - n_columns < 0) {
child = columns.ElementAtOrDefault (index)
.HeaderCell
.GetAccessible (this) as ColumnCellAccessible;
} else {
int column = (index - n_columns) % n_columns;
int row = (index - n_columns) / n_columns;
var cell = columns.ElementAtOrDefault (column).GetCell (0);
cell.BindListItem (list_view.Model[row]);
child = (ColumnCellAccessible) cell.GetAccessible (this);
}
cell_cache.Add (index, child);
return child;
}
public override Atk.Object RefAccessibleAtPoint (int x, int y, Atk.CoordType coordType)
{
int row, col;
list_view.GetCellAtPoint (x, y, coordType, out row, out col);
return RefAt (row, col);
}
private void OnModelChanged ()
{
GLib.Signal.Emit (this, "model_changed");
cell_cache.Clear ();
/*var handler = ModelChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}*/
}
private void OnSelectionFocusChanged (object o, EventArgs a)
{
GLib.Signal.Emit (this, "active-descendant-changed", ActiveCell.Handle);
}
private Atk.Object ActiveCell {
get {
if (list_view.HeaderFocused)
return OnRefChild (list_view.ActiveColumn);
else
return RefAt (list_view.Selection.FocusedIndex, list_view.ActiveColumn);
}
}
private int n_columns {
get { return list_view.ColumnController.Count (c => c.Visible); }
}
private int n_rows {
get { return list_view.Model.Count; }
}
#region ICellAccessibleParent
public int GetCellIndex (ColumnCellAccessible cell)
{
foreach (KeyValuePair<int, ColumnCellAccessible> kv in cell_cache)
{
if ((ColumnCellAccessible)kv.Value == cell)
return (int)kv.Key;
}
return -1;
}
public Gdk.Rectangle GetCellExtents (ColumnCellAccessible cell, Atk.CoordType coord_type)
{
int cache_index = GetCellIndex (cell);
int minval = Int32.MinValue;
if (cache_index == -1)
return new Gdk.Rectangle (minval, minval, minval, minval);
if (cache_index - n_columns >= 0)
{
int column = (cache_index - NColumns)%NColumns;
int row = (cache_index - NColumns)/NColumns;
return list_view.GetColumnCellExtents (row, column, true, coord_type);
} else
{
return list_view.GetColumnHeaderCellExtents (cache_index, true, coord_type);
}
}
public bool IsCellShowing (ColumnCellAccessible cell)
{
Gdk.Rectangle cell_extents = GetCellExtents (cell, Atk.CoordType.Window);
if (cell_extents.X == Int32.MinValue && cell_extents.Y == Int32.MinValue)
return false;
return true;
}
public bool IsCellFocused (ColumnCellAccessible cell)
{
int cell_index = GetCellIndex (cell);
if (cell_index % NColumns != 0)
return false; // Only 0 column cells get focus now.
int row = cell_index / NColumns;
return row == list_view.Selection.FocusedIndex;
}
public bool IsCellSelected (ColumnCellAccessible cell)
{
return IsChildSelected (GetCellIndex (cell));
}
public bool IsCellActive (ColumnCellAccessible cell)
{
return (ActiveCell == (Atk.Object)cell);
}
public void InvokeColumnHeaderMenu (ColumnCellAccessible cell)
{
list_view.InvokeColumnHeaderMenu (GetCellIndex (cell));
}
public void ClickColumnHeader (ColumnCellAccessible cell)
{
list_view.ClickColumnHeader (GetCellIndex (cell));
}
public void CellRedrawn (int column, int row)
{
int index;
if (row >= 0)
index = row * n_columns + column + n_columns;
else
index = column;
if (cell_cache.ContainsKey (index)) {
cell_cache[index].Redrawn ();
}
}
#endregion
}
#endif
}
| |
using System.Linq;
using System.Reflection;
using FluentMigrator.Expressions;
using FluentMigrator.Runner;
using FluentMigrator.VersionTableInfo;
using Moq;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Unit
{
public class TestMigrationProcessorOptions : IMigrationProcessorOptions
{
public bool PreviewOnly
{
get { return false; }
}
public int Timeout
{
get { return 30; }
}
public string ProviderSwitches
{
get
{
return string.Empty;
}
}
}
[TestFixture]
public class VersionLoaderTests
{
[Test]
public void CanLoadCustomVersionTableMetaData()
{
var runner = new Mock<IMigrationRunner>();
runner.SetupGet(r => r.Processor.Options).Returns(new TestMigrationProcessorOptions());
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new VersionLoader(runner.Object, asm, conventions);
var versionTableMetaData = loader.GetVersionTableMetaData();
versionTableMetaData.ShouldBeOfType<TestVersionTableMetaData>();
}
[Test]
public void CanLoadDefaultVersionTableMetaData()
{
var runner = new Mock<IMigrationRunner>();
runner.SetupGet(r => r.Processor.Options).Returns(new TestMigrationProcessorOptions());
var conventions = new MigrationConventions();
var asm = "s".GetType().Assembly;
var loader = new VersionLoader(runner.Object, asm, conventions);
var versionTableMetaData = loader.GetVersionTableMetaData();
versionTableMetaData.ShouldBeOfType<DefaultVersionTableMetaData>();
}
[Test]
public void DeleteVersionShouldExecuteDeleteDataExpression()
{
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new VersionLoader(runner.Object, asm, conventions);
processor.Setup(p => p.Process(It.Is<DeleteDataExpression>(expression =>
expression.SchemaName == loader.VersionTableMetaData.SchemaName
&& expression.TableName == loader.VersionTableMetaData.TableName
&& expression.Rows.All(
definition =>
definition.All(
pair =>
pair.Key == loader.VersionTableMetaData.ColumnName && pair.Value.Equals(1L))))))
.Verifiable();
loader.DeleteVersion(1);
processor.VerifyAll();
}
[Test]
public void RemoveVersionTableShouldBehaveAsExpected()
{
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new VersionLoader(runner.Object, asm, conventions);
processor.Setup(p => p.Process(It.Is<DeleteTableExpression>(expression =>
expression.SchemaName == loader.VersionTableMetaData.SchemaName
&& expression.TableName == loader.VersionTableMetaData.TableName)))
.Verifiable();
processor.Setup(p => p.Process(It.Is<DeleteSchemaExpression>(expression =>
expression.SchemaName == loader.VersionTableMetaData.SchemaName)))
.Verifiable();
loader.RemoveVersionTable();
processor.VerifyAll();
}
[Test]
public void RemoveVersionTableShouldNotRemoveSchemaIfItDidNotOwnTheSchema()
{
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new VersionLoader(runner.Object, asm, conventions);
((TestVersionTableMetaData) loader.VersionTableMetaData).OwnsSchema = false;
processor.Setup(p => p.Process(It.Is<DeleteTableExpression>(expression =>
expression.SchemaName == loader.VersionTableMetaData.SchemaName
&& expression.TableName == loader.VersionTableMetaData.TableName)))
.Verifiable();
loader.RemoveVersionTable();
processor.Verify(p => p.Process(It.IsAny<DeleteSchemaExpression>()), Times.Never());
}
[Test]
public void UpdateVersionShouldExecuteInsertDataExpression()
{
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
var conventions = new MigrationConventions();
var asm = Assembly.GetExecutingAssembly();
var loader = new VersionLoader(runner.Object, asm, conventions);
processor.Setup(p => p.Process(It.Is<InsertDataExpression>(expression =>
expression.SchemaName == loader.VersionTableMetaData.SchemaName
&& expression.TableName == loader.VersionTableMetaData.TableName
&& expression.Rows.Any(
definition =>
definition.Any(
pair =>
pair.Key == loader.VersionTableMetaData.ColumnName && pair.Value.Equals(1L))))))
.Verifiable();
loader.UpdateVersionInfo(1);
processor.VerifyAll();
}
[Test]
public void VersionSchemaMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse()
{
var conventions = new MigrationConventions();
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
var asm = Assembly.GetExecutingAssembly();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
processor.Setup(p => p.SchemaExists(It.IsAny<string>())).Returns(false);
var loader = new VersionLoader(runner.Object, asm, conventions);
loader.LoadVersionInfo();
runner.Verify(r => r.Up(loader.VersionSchemaMigration), Times.Once());
}
[Test]
public void VersionMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse()
{
var conventions = new MigrationConventions();
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
var asm = Assembly.GetExecutingAssembly();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
processor.Setup(p => p.TableExists(new TestVersionTableMetaData().SchemaName, TestVersionTableMetaData.TABLENAME)).Returns(false);
var loader = new VersionLoader(runner.Object, asm, conventions);
loader.LoadVersionInfo();
runner.Verify(r => r.Up(loader.VersionMigration), Times.Once());
}
[Test]
public void VersionUniqueMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse()
{
var conventions = new MigrationConventions();
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
var asm = Assembly.GetExecutingAssembly();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
processor.Setup(p => p.ColumnExists(new TestVersionTableMetaData().SchemaName, TestVersionTableMetaData.TABLENAME, "AppliedOn")).Returns(false);
var loader = new VersionLoader(runner.Object, asm, conventions);
loader.LoadVersionInfo();
runner.Verify(r => r.Up(loader.VersionUniqueMigration), Times.Once());
}
[Test]
public void VersionDescriptionMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse()
{
var conventions = new MigrationConventions();
var processor = new Mock<IMigrationProcessor>();
var runner = new Mock<IMigrationRunner>();
var asm = Assembly.GetExecutingAssembly();
runner.SetupGet(r => r.Processor).Returns(processor.Object);
processor.Setup(p => p.ColumnExists(new TestVersionTableMetaData().SchemaName, TestVersionTableMetaData.TABLENAME, "AppliedOn")).Returns(false);
var loader = new VersionLoader(runner.Object, asm, conventions);
loader.LoadVersionInfo();
runner.Verify(r => r.Up(loader.VersionDescriptionMigration), Times.Once());
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Text.RegularExpressions;
using System.Globalization;
using System.IO;
using System.Collections.Generic;
namespace Boo.Lang.Compiler.Ast.Visitors
{
/// <summary>
/// </summary>
public class BooPrinterVisitor : TextEmitter
{
[Flags]
public enum PrintOptions
{
None,
PrintLocals = 1,
WSA = 2,
}
public PrintOptions Options = PrintOptions.None;
public BooPrinterVisitor(TextWriter writer) : base(writer)
{
}
public BooPrinterVisitor(TextWriter writer, PrintOptions options) : this(writer)
{
this.Options = options;
}
public bool IsOptionSet(PrintOptions option)
{
return (option & Options) == option;
}
public void Print(CompileUnit ast)
{
OnCompileUnit(ast);
}
#region overridables
public virtual void WriteKeyword(string text)
{
Write(text);
}
public virtual void WriteOperator(string text)
{
Write(text);
}
#endregion
#region IAstVisitor Members
override public void OnModule(Module m)
{
Visit(m.Namespace);
if (m.Imports.Count > 0)
{
Visit(m.Imports);
WriteLine();
}
foreach (var member in m.Members)
{
Visit(member);
WriteLine();
}
if (m.Globals != null)
Visit(m.Globals.Statements);
foreach (var attribute in m.Attributes)
WriteModuleAttribute(attribute);
foreach (var attribute in m.AssemblyAttributes)
WriteAssemblyAttribute(attribute);
}
private void WriteModuleAttribute(Attribute attribute)
{
WriteAttribute(attribute, "module: ");
WriteLine();
}
private void WriteAssemblyAttribute(Attribute attribute)
{
WriteAttribute(attribute, "assembly: ");
WriteLine();
}
override public void OnNamespaceDeclaration(NamespaceDeclaration node)
{
WriteKeyword("namespace");
WriteLine(" {0}", node.Name);
WriteLine();
}
static bool IsExtendedRE(string s)
{
return s.IndexOfAny(new char[] { ' ', '\t' }) > -1;
}
static bool CanBeRepresentedAsQualifiedName(string s)
{
foreach (char ch in s)
if (!char.IsLetterOrDigit(ch) && ch != '_' && ch != '.')
return false;
return true;
}
override public void OnImport(Import p)
{
WriteKeyword("import");
Write(" {0}", p.Namespace);
if (null != p.AssemblyReference)
{
WriteKeyword(" from ");
var assemblyRef = p.AssemblyReference.Name;
if (CanBeRepresentedAsQualifiedName(assemblyRef))
Write(assemblyRef);
else
WriteStringLiteral(assemblyRef);
}
if (p.Expression.NodeType == NodeType.MethodInvocationExpression)
{
MethodInvocationExpression mie = (MethodInvocationExpression)p.Expression;
Write("(");
WriteCommaSeparatedList(mie.Arguments);
Write(")");
}
if (null != p.Alias)
{
WriteKeyword(" as ");
Write(p.Alias.Name);
}
WriteLine();
}
public bool IsWhiteSpaceAgnostic
{
get { return IsOptionSet(PrintOptions.WSA); }
}
private void WritePass()
{
if (!IsWhiteSpaceAgnostic)
{
WriteIndented();
WriteKeyword("pass");
WriteLine();
}
}
private void WriteBlockStatements(Block b)
{
if (b.IsEmpty)
{
WritePass();
}
else
{
Visit(b.Statements);
}
}
public void WriteBlock(Block b)
{
BeginBlock();
WriteBlockStatements(b);
EndBlock();
}
private void BeginBlock()
{
Indent();
}
private void EndBlock()
{
Dedent();
if (IsWhiteSpaceAgnostic)
{
WriteEnd();
}
}
private void WriteEnd()
{
WriteIndented();
WriteKeyword("end");
WriteLine();
}
override public void OnAttribute(Attribute att)
{
WriteAttribute(att);
}
override public void OnClassDefinition(ClassDefinition c)
{
WriteTypeDefinition("class", c);
}
override public void OnStructDefinition(StructDefinition node)
{
WriteTypeDefinition("struct", node);
}
override public void OnInterfaceDefinition(InterfaceDefinition id)
{
WriteTypeDefinition("interface", id);
}
override public void OnEnumDefinition(EnumDefinition ed)
{
WriteTypeDefinition("enum", ed);
}
override public void OnEvent(Event node)
{
WriteAttributes(node.Attributes, true);
WriteOptionalModifiers(node);
WriteKeyword("event ");
Write(node.Name);
WriteTypeReference(node.Type);
WriteLine();
}
private static bool IsInterfaceMember(TypeMember node)
{
return node.ParentNode != null && node.ParentNode.NodeType == NodeType.InterfaceDefinition;
}
override public void OnField(Field f)
{
WriteAttributes(f.Attributes, true);
WriteModifiers(f);
Write(f.Name);
WriteTypeReference(f.Type);
if (null != f.Initializer)
{
WriteOperator(" = ");
Visit(f.Initializer);
}
WriteLine();
}
override public void OnExplicitMemberInfo(ExplicitMemberInfo node)
{
Visit(node.InterfaceType);
Write(".");
}
override public void OnProperty(Property node)
{
bool interfaceMember = IsInterfaceMember(node);
WriteAttributes(node.Attributes, true);
WriteOptionalModifiers(node);
WriteIndented("");
Visit(node.ExplicitInfo);
Write(node.Name);
if (node.Parameters.Count > 0)
{
WriteParameterList(node.Parameters, "[", "]");
}
WriteTypeReference(node.Type);
WriteLine(":");
BeginBlock();
WritePropertyAccessor(node.Getter, "get", interfaceMember);
WritePropertyAccessor(node.Setter, "set", interfaceMember);
EndBlock();
}
private void WritePropertyAccessor(Method method, string name, bool interfaceMember)
{
if (null == method) return;
WriteAttributes(method.Attributes, true);
if (interfaceMember)
{
WriteIndented();
}
else
{
WriteModifiers(method);
}
WriteKeyword(name);
if (interfaceMember)
{
WriteLine();
}
else
{
WriteLine(":");
WriteBlock(method.Body);
}
}
override public void OnEnumMember(EnumMember node)
{
WriteAttributes(node.Attributes, true);
WriteIndented(node.Name);
if (null != node.Initializer)
{
WriteOperator(" = ");
Visit(node.Initializer);
}
WriteLine();
}
override public void OnConstructor(Constructor c)
{
OnMethod(c);
}
override public void OnDestructor(Destructor c)
{
OnMethod(c);
}
bool IsSimpleClosure(BlockExpression node)
{
switch (node.Body.Statements.Count)
{
case 0:
return true;
case 1:
switch (node.Body.Statements[0].NodeType)
{
case NodeType.IfStatement:
return false;
case NodeType.WhileStatement:
return false;
case NodeType.ForStatement:
return false;
case NodeType.TryStatement:
return false;
}
return true;
}
return false;
}
override public void OnBlockExpression(BlockExpression node)
{
if (IsSimpleClosure(node))
{
DisableNewLine();
Write("{ ");
if (node.Parameters.Count > 0)
{
WriteCommaSeparatedList(node.Parameters);
Write(" | ");
}
if (node.Body.IsEmpty)
Write("return");
else
Visit(node.Body.Statements);
Write(" }");
EnableNewLine();
}
else
{
WriteKeyword("def ");
WriteParameterList(node.Parameters);
WriteTypeReference(node.ReturnType);
WriteLine(":");
WriteBlock(node.Body);
}
}
void WriteCallableDefinitionHeader(string keyword, CallableDefinition node)
{
WriteAttributes(node.Attributes, true);
WriteOptionalModifiers(node);
WriteKeyword(keyword);
IExplicitMember em = node as IExplicitMember;
if (null != em)
{
Visit(em.ExplicitInfo);
}
Write(node.Name);
if (node.GenericParameters.Count > 0)
{
WriteGenericParameterList(node.GenericParameters);
}
WriteParameterList(node.Parameters);
if (node.ReturnTypeAttributes.Count > 0)
{
Write(" ");
WriteAttributes(node.ReturnTypeAttributes, false);
}
WriteTypeReference(node.ReturnType);
}
private void WriteOptionalModifiers(TypeMember node)
{
if (IsInterfaceMember(node))
{
WriteIndented();
}
else
{
WriteModifiers(node);
}
}
override public void OnCallableDefinition(CallableDefinition node)
{
WriteCallableDefinitionHeader("callable ", node);
}
override public void OnMethod(Method m)
{
if (m.IsRuntime) WriteImplementationComment("runtime");
WriteCallableDefinitionHeader("def ", m);
if (IsInterfaceMember(m))
{
WriteLine();
}
else
{
WriteLine(":");
WriteLocals(m);
WriteBlock(m.Body);
}
}
private void WriteImplementationComment(string comment)
{
WriteIndented("// {0}", comment);
WriteLine();
}
public override void OnLocal(Local node)
{
WriteIndented("// Local {0}, {1}, PrivateScope: {2}", node.Name, node.Entity, node.PrivateScope);
WriteLine();
}
void WriteLocals(Method m)
{
if (!IsOptionSet(PrintOptions.PrintLocals)) return;
Visit(m.Locals);
}
void WriteTypeReference(TypeReference t)
{
if (null != t)
{
WriteKeyword(" as ");
Visit(t);
}
}
override public void OnParameterDeclaration(ParameterDeclaration p)
{
WriteAttributes(p.Attributes, false);
if (p.IsByRef)
WriteKeyword("ref ");
if (IsCallableTypeReferenceParameter(p))
{
if (p.IsParamArray) Write("*");
Visit(p.Type);
}
else
{
Write(p.Name);
WriteTypeReference(p.Type);
}
}
private static bool IsCallableTypeReferenceParameter(ParameterDeclaration p)
{
var parentNode = p.ParentNode;
return parentNode != null && parentNode.NodeType == NodeType.CallableTypeReference;
}
override public void OnGenericParameterDeclaration(GenericParameterDeclaration gp)
{
Write(gp.Name);
if (gp.BaseTypes.Count > 0 || gp.Constraints != GenericParameterConstraints.None)
{
Write("(");
WriteCommaSeparatedList(gp.BaseTypes);
if (gp.Constraints != GenericParameterConstraints.None)
{
if (gp.BaseTypes.Count != 0)
{
Write(", ");
}
WriteGenericParameterConstraints(gp.Constraints);
}
Write(")");
}
}
private void WriteGenericParameterConstraints(GenericParameterConstraints constraints)
{
List<string> constraintStrings = new List<string>();
if ((constraints & GenericParameterConstraints.ReferenceType) != GenericParameterConstraints.None)
{
constraintStrings.Add("class");
}
if ((constraints & GenericParameterConstraints.ValueType) != GenericParameterConstraints.None)
{
constraintStrings.Add("struct");
}
if ((constraints & GenericParameterConstraints.Constructable) != GenericParameterConstraints.None)
{
constraintStrings.Add("constructor");
}
Write(string.Join(", ", constraintStrings.ToArray()));
}
private KeyValuePair<T, string> CreateTranslation<T>(T value, string translation)
{
return new KeyValuePair<T, string>(value, translation);
}
override public void OnTypeofExpression(TypeofExpression node)
{
Write("typeof(");
Visit(node.Type);
Write(")");
}
override public void OnSimpleTypeReference(SimpleTypeReference t)
{
Write(t.Name);
}
override public void OnGenericTypeReference(GenericTypeReference node)
{
OnSimpleTypeReference(node);
WriteGenericArguments(node.GenericArguments);
}
override public void OnGenericTypeDefinitionReference(GenericTypeDefinitionReference node)
{
OnSimpleTypeReference(node);
Write("[of *");
for (int i = 1; i < node.GenericPlaceholders; i++)
{
Write(", *");
}
Write("]");
}
override public void OnGenericReferenceExpression(GenericReferenceExpression node)
{
Visit(node.Target);
WriteGenericArguments(node.GenericArguments);
}
void WriteGenericArguments(TypeReferenceCollection arguments)
{
Write("[of ");
WriteCommaSeparatedList(arguments);
Write("]");
}
override public void OnArrayTypeReference(ArrayTypeReference t)
{
Write("(");
Visit(t.ElementType);
if (null != t.Rank && t.Rank.Value > 1)
{
Write(", ");
t.Rank.Accept(this);
}
Write(")");
}
override public void OnCallableTypeReference(CallableTypeReference node)
{
Write("callable(");
WriteCommaSeparatedList(node.Parameters);
Write(")");
WriteTypeReference(node.ReturnType);
}
override public void OnMemberReferenceExpression(MemberReferenceExpression e)
{
Visit(e.Target);
Write(".");
Write(e.Name);
}
override public void OnTryCastExpression(TryCastExpression e)
{
Write("(");
Visit(e.Target);
WriteTypeReference(e.Type);
Write(")");
}
override public void OnCastExpression(CastExpression node)
{
Write("(");
Visit(node.Target);
WriteKeyword(" cast ");
Visit(node.Type);
Write(")");
}
override public void OnNullLiteralExpression(NullLiteralExpression node)
{
WriteKeyword("null");
}
override public void OnSelfLiteralExpression(SelfLiteralExpression node)
{
WriteKeyword("self");
}
override public void OnSuperLiteralExpression(SuperLiteralExpression node)
{
WriteKeyword("super");
}
override public void OnTimeSpanLiteralExpression(TimeSpanLiteralExpression node)
{
WriteTimeSpanLiteral(node.Value, _writer);
}
override public void OnBoolLiteralExpression(BoolLiteralExpression node)
{
if (node.Value)
{
WriteKeyword("true");
}
else
{
WriteKeyword("false");
}
}
override public void OnUnaryExpression(UnaryExpression node)
{
bool addParens = NeedParensAround(node) && !IsMethodInvocationArg(node) && node.Operator != UnaryOperatorType.SafeAccess;
if (addParens)
{
Write("(");
}
bool postOperator = AstUtil.IsPostUnaryOperator(node.Operator);
if (!postOperator)
{
WriteOperator(GetUnaryOperatorText(node.Operator));
}
Visit(node.Operand);
if (postOperator)
{
WriteOperator(GetUnaryOperatorText(node.Operator));
}
if (addParens)
{
Write(")");
}
}
private bool IsMethodInvocationArg(UnaryExpression node)
{
MethodInvocationExpression parent = node.ParentNode as MethodInvocationExpression;
return null != parent && node != parent.Target;
}
override public void OnConditionalExpression(ConditionalExpression e)
{
Write("(");
Visit(e.TrueValue);
WriteKeyword(" if ");
Visit(e.Condition);
WriteKeyword(" else ");
Visit(e.FalseValue);
Write(")");
}
bool NeedParensAround(Expression e)
{
if (e.ParentNode == null) return false;
switch (e.ParentNode.NodeType)
{
case NodeType.ExpressionStatement:
case NodeType.MacroStatement:
case NodeType.IfStatement:
case NodeType.WhileStatement:
case NodeType.UnlessStatement:
return false;
}
return true;
}
override public void OnBinaryExpression(BinaryExpression e)
{
bool needsParens = NeedParensAround(e);
if (needsParens)
{
Write("(");
}
Visit(e.Left);
Write(" ");
WriteOperator(GetBinaryOperatorText(e.Operator));
Write(" ");
if (e.Operator == BinaryOperatorType.TypeTest)
{
// isa rhs is encoded in a typeof expression
Visit(((TypeofExpression)e.Right).Type);
}
else
{
Visit(e.Right);
}
if (needsParens)
{
Write(")");
}
}
override public void OnRaiseStatement(RaiseStatement rs)
{
WriteIndented();
WriteKeyword("raise ");
Visit(rs.Exception);
Visit(rs.Modifier);
WriteLine();
}
override public void OnMethodInvocationExpression(MethodInvocationExpression e)
{
Visit(e.Target);
Write("(");
WriteCommaSeparatedList(e.Arguments);
if (e.NamedArguments.Count > 0)
{
if (e.Arguments.Count > 0)
{
Write(", ");
}
WriteCommaSeparatedList(e.NamedArguments);
}
Write(")");
}
override public void OnArrayLiteralExpression(ArrayLiteralExpression node)
{
WriteArray(node.Items, node.Type);
}
override public void OnListLiteralExpression(ListLiteralExpression node)
{
WriteDelimitedCommaSeparatedList("[", node.Items, "]");
}
private void WriteDelimitedCommaSeparatedList(string opening, IEnumerable<Expression> list, string closing)
{
Write(opening);
WriteCommaSeparatedList(list);
Write(closing);
}
public override void OnCollectionInitializationExpression(CollectionInitializationExpression node)
{
Visit(node.Collection);
Write(" ");
if (node.Initializer is ListLiteralExpression)
WriteDelimitedCommaSeparatedList("{ ", ((ListLiteralExpression) node.Initializer).Items, " }");
else
Visit(node.Initializer);
}
override public void OnGeneratorExpression(GeneratorExpression node)
{
Write("(");
Visit(node.Expression);
WriteGeneratorExpressionBody(node);
Write(")");
}
void WriteGeneratorExpressionBody(GeneratorExpression node)
{
WriteKeyword(" for ");
WriteCommaSeparatedList(node.Declarations);
WriteKeyword(" in ");
Visit(node.Iterator);
Visit(node.Filter);
}
override public void OnExtendedGeneratorExpression(ExtendedGeneratorExpression node)
{
Write("(");
Visit(node.Items[0].Expression);
for (int i=0; i<node.Items.Count; ++i)
{
WriteGeneratorExpressionBody(node.Items[i]);
}
Write(")");
}
override public void OnSlice(Slice node)
{
Visit(node.Begin);
if (null != node.End || WasOmitted(node.Begin))
{
Write(":");
}
Visit(node.End);
if (null != node.Step)
{
Write(":");
Visit(node.Step);
}
}
override public void OnSlicingExpression(SlicingExpression node)
{
Visit(node.Target);
Write("[");
WriteCommaSeparatedList(node.Indices);
Write("]");
}
override public void OnHashLiteralExpression(HashLiteralExpression node)
{
Write("{");
if (node.Items.Count > 0)
{
Write(" ");
WriteCommaSeparatedList(node.Items);
Write(" ");
}
Write("}");
}
override public void OnExpressionPair(ExpressionPair pair)
{
Visit(pair.First);
Write(": ");
Visit(pair.Second);
}
override public void OnRELiteralExpression(RELiteralExpression e)
{
if (IsExtendedRE(e.Value))
{
Write("@");
}
Write(e.Value);
}
override public void OnSpliceExpression(SpliceExpression e)
{
WriteSplicedExpression(e.Expression);
}
private void WriteSplicedExpression(Expression expression)
{
WriteOperator("$(");
Visit(expression);
WriteOperator(")");
}
public override void OnStatementTypeMember(StatementTypeMember node)
{
WriteModifiers(node);
Visit(node.Statement);
}
public override void OnSpliceTypeMember(SpliceTypeMember node)
{
WriteIndented();
Visit(node.TypeMember);
WriteLine();
}
public override void OnSpliceTypeDefinitionBody(SpliceTypeDefinitionBody node)
{
WriteIndented();
WriteSplicedExpression(node.Expression);
WriteLine();
}
override public void OnSpliceTypeReference(SpliceTypeReference node)
{
WriteSplicedExpression(node.Expression);
}
void WriteIndentedOperator(string op)
{
WriteIndented();
WriteOperator(op);
}
override public void OnQuasiquoteExpression(QuasiquoteExpression e)
{
WriteIndentedOperator("[|");
if (e.Node is Expression)
{
Write(" ");
Visit(e.Node);
Write(" ");
WriteIndentedOperator("|]");
}
else
{
WriteLine();
Indent();
Visit(e.Node);
Dedent();
WriteIndentedOperator("|]");
WriteLine();
}
}
override public void OnStringLiteralExpression(StringLiteralExpression e)
{
if (e != null && e.Value != null)
WriteStringLiteral(e.Value);
else
WriteKeyword("null");
}
override public void OnCharLiteralExpression(CharLiteralExpression e)
{
WriteKeyword("char");
Write("(");
WriteStringLiteral(e.Value);
Write(")");
}
override public void OnIntegerLiteralExpression(IntegerLiteralExpression e)
{
Write(e.Value.ToString());
if (e.IsLong)
{
Write("L");
}
}
override public void OnDoubleLiteralExpression(DoubleLiteralExpression e)
{
Write(e.Value.ToString("########0.0##########", CultureInfo.InvariantCulture));
if (e.IsSingle)
{
Write("F");
}
}
override public void OnReferenceExpression(ReferenceExpression node)
{
Write(node.Name);
}
override public void OnExpressionStatement(ExpressionStatement node)
{
WriteIndented();
Visit(node.Expression);
Visit(node.Modifier);
WriteLine();
}
override public void OnExpressionInterpolationExpression(ExpressionInterpolationExpression node)
{
Write("\"");
foreach (var arg in node.Expressions)
{
switch (arg.NodeType)
{
case NodeType.StringLiteralExpression:
WriteStringLiteralContents(((StringLiteralExpression)arg).Value, _writer, false);
break;
case NodeType.ReferenceExpression:
case NodeType.BinaryExpression:
Write("$");
Visit(arg);
break;
default:
Write("$(");
Visit(arg);
Write(")");
break;
}
}
Write("\"");
}
override public void OnStatementModifier(StatementModifier sm)
{
Write(" ");
WriteKeyword(sm.Type.ToString().ToLower());
Write(" ");
Visit(sm.Condition);
}
override public void OnLabelStatement(LabelStatement node)
{
WriteIndented(":");
WriteLine(node.Name);
}
override public void OnGotoStatement(GotoStatement node)
{
WriteIndented();
WriteKeyword("goto ");
Visit(node.Label);
Visit(node.Modifier);
WriteLine();
}
override public void OnMacroStatement(MacroStatement node)
{
WriteIndented(node.Name);
Write(" ");
WriteCommaSeparatedList(node.Arguments);
if (!node.Body.IsEmpty)
{
WriteLine(":");
WriteBlock(node.Body);
}
else
{
Visit(node.Modifier);
WriteLine();
}
}
override public void OnForStatement(ForStatement fs)
{
WriteIndented();
WriteKeyword("for ");
for (int i=0; i<fs.Declarations.Count; ++i)
{
if (i > 0) { Write(", "); }
Visit(fs.Declarations[i]);
}
WriteKeyword(" in ");
Visit(fs.Iterator);
WriteLine(":");
WriteBlock(fs.Block);
if(fs.OrBlock != null)
{
WriteIndented();
WriteKeyword("or:");
WriteLine();
WriteBlock(fs.OrBlock);
}
if(fs.ThenBlock != null)
{
WriteIndented();
WriteKeyword("then:");
WriteLine();
WriteBlock(fs.ThenBlock);
}
}
override public void OnTryStatement(TryStatement node)
{
WriteIndented();
WriteKeyword("try:");
WriteLine();
Indent();
WriteBlockStatements(node.ProtectedBlock);
Dedent();
Visit(node.ExceptionHandlers);
if (null != node.FailureBlock)
{
WriteIndented();
WriteKeyword("failure:");
WriteLine();
Indent();
WriteBlockStatements(node.FailureBlock);
Dedent();
}
if (null != node.EnsureBlock)
{
WriteIndented();
WriteKeyword("ensure:");
WriteLine();
Indent();
WriteBlockStatements(node.EnsureBlock);
Dedent();
}
if(IsWhiteSpaceAgnostic)
{
WriteEnd();
}
}
override public void OnExceptionHandler(ExceptionHandler node)
{
WriteIndented();
WriteKeyword("except");
if ((node.Flags & ExceptionHandlerFlags.Untyped) == ExceptionHandlerFlags.None)
{
if((node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.None)
{
Write(" ");
Visit(node.Declaration);
}
else
{
WriteTypeReference(node.Declaration.Type);
}
}
else if((node.Flags & ExceptionHandlerFlags.Anonymous) == ExceptionHandlerFlags.None)
{
Write(" ");
Write(node.Declaration.Name);
}
if((node.Flags & ExceptionHandlerFlags.Filter) == ExceptionHandlerFlags.Filter)
{
UnaryExpression unless = node.FilterCondition as UnaryExpression;
if(unless != null && unless.Operator == UnaryOperatorType.LogicalNot)
{
WriteKeyword(" unless ");
Visit(unless.Operand);
}
else
{
WriteKeyword(" if ");
Visit(node.FilterCondition);
}
}
WriteLine(":");
Indent();
WriteBlockStatements(node.Block);
Dedent();
}
override public void OnUnlessStatement(UnlessStatement node)
{
WriteConditionalBlock("unless", node.Condition, node.Block);
}
override public void OnBreakStatement(BreakStatement node)
{
WriteIndented();
WriteKeyword("break ");
Visit(node.Modifier);
WriteLine();
}
override public void OnContinueStatement(ContinueStatement node)
{
WriteIndented();
WriteKeyword("continue ");
Visit(node.Modifier);
WriteLine();
}
override public void OnYieldStatement(YieldStatement node)
{
WriteIndented();
WriteKeyword("yield ");
Visit(node.Expression);
Visit(node.Modifier);
WriteLine();
}
override public void OnWhileStatement(WhileStatement node)
{
WriteConditionalBlock("while", node.Condition, node.Block);
if(node.OrBlock != null)
{
WriteIndented();
WriteKeyword("or:");
WriteLine();
WriteBlock(node.OrBlock);
}
if(node.ThenBlock != null)
{
WriteIndented();
WriteKeyword("then:");
WriteLine();
WriteBlock(node.ThenBlock);
}
}
override public void OnIfStatement(IfStatement node)
{
WriteIfBlock("if ", node);
Block elseBlock = WriteElifs(node);
if (null != elseBlock)
{
WriteIndented();
WriteKeyword("else:");
WriteLine();
WriteBlock(elseBlock);
}
else
{
if (IsWhiteSpaceAgnostic)
{
WriteEnd();
}
}
}
private Block WriteElifs(IfStatement node)
{
Block falseBlock = node.FalseBlock;
while (IsElif(falseBlock))
{
IfStatement stmt = (IfStatement) falseBlock.Statements[0];
WriteIfBlock("elif ", stmt);
falseBlock = stmt.FalseBlock;
}
return falseBlock;
}
private void WriteIfBlock(string keyword, IfStatement ifs)
{
WriteIndented();
WriteKeyword(keyword);
Visit(ifs.Condition);
WriteLine(":");
Indent();
WriteBlockStatements(ifs.TrueBlock);
Dedent();
}
private static bool IsElif(Block block)
{
if (block == null) return false;
if (block.Statements.Count != 1) return false;
return block.Statements[0] is IfStatement;
}
override public void OnDeclarationStatement(DeclarationStatement d)
{
WriteIndented();
Visit(d.Declaration);
if (null != d.Initializer)
{
WriteOperator(" = ");
Visit(d.Initializer);
}
WriteLine();
}
override public void OnDeclaration(Declaration d)
{
Write(d.Name);
WriteTypeReference(d.Type);
}
override public void OnReturnStatement(ReturnStatement r)
{
WriteIndented();
WriteKeyword("return");
if (r.Expression != null || r.Modifier != null)
Write(" ");
Visit(r.Expression);
Visit(r.Modifier);
WriteLine();
}
override public void OnUnpackStatement(UnpackStatement us)
{
WriteIndented();
for (int i=0; i<us.Declarations.Count; ++i)
{
if (i > 0)
{
Write(", ");
}
Visit(us.Declarations[i]);
}
WriteOperator(" = ");
Visit(us.Expression);
Visit(us.Modifier);
WriteLine();
}
#endregion
public static string GetUnaryOperatorText(UnaryOperatorType op)
{
switch (op)
{
case UnaryOperatorType.Explode:
{
return "*";
}
case UnaryOperatorType.PostIncrement:
case UnaryOperatorType.Increment:
return "++";
case UnaryOperatorType.PostDecrement:
case UnaryOperatorType.Decrement:
return "--";
case UnaryOperatorType.UnaryNegation:
return "-";
case UnaryOperatorType.LogicalNot:
return "not ";
case UnaryOperatorType.OnesComplement:
return "~";
case UnaryOperatorType.AddressOf:
return "&";
case UnaryOperatorType.Indirection:
return "*";
case UnaryOperatorType.SafeAccess:
return "?";
}
throw new ArgumentException("op");
}
public static string GetBinaryOperatorText(BinaryOperatorType op)
{
switch (op)
{
case BinaryOperatorType.Assign:
return "=";
case BinaryOperatorType.Match:
return "=~";
case BinaryOperatorType.NotMatch:
return "!~";
case BinaryOperatorType.Equality:
return "==";
case BinaryOperatorType.Inequality:
return "!=";
case BinaryOperatorType.Addition:
return "+";
case BinaryOperatorType.Exponentiation:
return "**";
case BinaryOperatorType.InPlaceAddition:
return "+=";
case BinaryOperatorType.InPlaceBitwiseAnd:
return "&=";
case BinaryOperatorType.InPlaceBitwiseOr:
return "|=";
case BinaryOperatorType.InPlaceSubtraction:
return "-=";
case BinaryOperatorType.InPlaceMultiply:
return "*=";
case BinaryOperatorType.InPlaceModulus:
return "%=";
case BinaryOperatorType.InPlaceExclusiveOr:
return "^=";
case BinaryOperatorType.InPlaceDivision:
return "/=";
case BinaryOperatorType.Subtraction:
return "-";
case BinaryOperatorType.Multiply:
return "*";
case BinaryOperatorType.Division:
return "/";
case BinaryOperatorType.GreaterThan:
return ">";
case BinaryOperatorType.GreaterThanOrEqual:
return ">=";
case BinaryOperatorType.LessThan:
return "<";
case BinaryOperatorType.LessThanOrEqual:
return "<=";
case BinaryOperatorType.Modulus:
return "%";
case BinaryOperatorType.Member:
return "in";
case BinaryOperatorType.NotMember:
return "not in";
case BinaryOperatorType.ReferenceEquality:
return "is";
case BinaryOperatorType.ReferenceInequality:
return "is not";
case BinaryOperatorType.TypeTest:
return "isa";
case BinaryOperatorType.Or:
return "or";
case BinaryOperatorType.And:
return "and";
case BinaryOperatorType.BitwiseOr:
return "|";
case BinaryOperatorType.BitwiseAnd:
return "&";
case BinaryOperatorType.ExclusiveOr:
return "^";
case BinaryOperatorType.ShiftLeft:
return "<<";
case BinaryOperatorType.ShiftRight:
return ">>";
case BinaryOperatorType.InPlaceShiftLeft:
return "<<=";
case BinaryOperatorType.InPlaceShiftRight:
return ">>=";
}
throw new NotImplementedException(op.ToString());
}
public virtual void WriteStringLiteral(string text)
{
WriteStringLiteral(text, _writer);
}
public static void WriteTimeSpanLiteral(TimeSpan value, TextWriter writer)
{
double days = value.TotalDays;
if (days >= 1)
{
writer.Write(days.ToString(CultureInfo.InvariantCulture) + "d");
}
else
{
double hours = value.TotalHours;
if (hours >= 1)
{
writer.Write(hours.ToString(CultureInfo.InvariantCulture) + "h");
}
else
{
double minutes = value.TotalMinutes;
if (minutes >= 1)
{
writer.Write(minutes.ToString(CultureInfo.InvariantCulture) + "m");
}
else
{
double seconds = value.TotalSeconds;
if (seconds >= 1)
{
writer.Write(seconds.ToString(CultureInfo.InvariantCulture) + "s");
}
else
{
writer.Write(value.TotalMilliseconds.ToString(CultureInfo.InvariantCulture) + "ms");
}
}
}
}
}
public static void WriteStringLiteral(string text, TextWriter writer)
{
writer.Write("'");
WriteStringLiteralContents(text, writer);
writer.Write("'");
}
public static void WriteStringLiteralContents(string text, TextWriter writer)
{
WriteStringLiteralContents(text, writer, true);
}
public static void WriteStringLiteralContents(string text, TextWriter writer, bool single)
{
foreach (char ch in text)
{
switch (ch)
{
case '\r':
{
writer.Write("\\r");
break;
}
case '\n':
{
writer.Write("\\n");
break;
}
case '\t':
{
writer.Write("\\t");
break;
}
case '\\':
{
writer.Write("\\\\");
break;
}
case '\a':
{
writer.Write(@"\a");
break;
}
case '\b':
{
writer.Write(@"\b");
break;
}
case '\f':
{
writer.Write(@"\f");
break;
}
case '\0':
{
writer.Write(@"\0");
break;
}
case '\'':
{
if (single)
{
writer.Write("\\'");
}
else
{
writer.Write(ch);
}
break;
}
case '"':
{
if (!single)
{
writer.Write("\\\"");
}
else
{
writer.Write(ch);
}
break;
}
default:
{
writer.Write(ch);
break;
}
}
}
}
void WriteConditionalBlock(string keyword, Expression condition, Block block)
{
WriteIndented();
WriteKeyword(keyword + " ");
Visit(condition);
WriteLine(":");
WriteBlock(block);
}
void WriteParameterList(ParameterDeclarationCollection items)
{
WriteParameterList(items, "(", ")");
}
void WriteParameterList(ParameterDeclarationCollection items, string st, string ed)
{
Write(st);
int i = 0;
foreach (ParameterDeclaration item in items)
{
if (i > 0)
{
Write(", ");
}
if (item.IsParamArray)
{
Write("*");
}
Visit(item);
++i;
}
Write(ed);
}
void WriteGenericParameterList(GenericParameterDeclarationCollection items)
{
Write("[of ");
WriteCommaSeparatedList(items);
Write("]");
}
void WriteAttribute(Attribute attribute)
{
WriteAttribute(attribute, null);
}
void WriteAttribute(Attribute attribute, string prefix)
{
WriteIndented("[");
if (null != prefix)
{
Write(prefix);
}
Write(attribute.Name);
if (attribute.Arguments.Count > 0 ||
attribute.NamedArguments.Count > 0)
{
Write("(");
WriteCommaSeparatedList(attribute.Arguments);
if (attribute.NamedArguments.Count > 0)
{
if (attribute.Arguments.Count > 0)
{
Write(", ");
}
WriteCommaSeparatedList(attribute.NamedArguments);
}
Write(")");
}
Write("]");
}
void WriteAttributes(AttributeCollection attributes, bool addNewLines)
{
foreach (Boo.Lang.Compiler.Ast.Attribute attribute in attributes)
{
Visit(attribute);
if (addNewLines)
{
WriteLine();
}
else
{
Write(" ");
}
}
}
void WriteModifiers(TypeMember member)
{
WriteIndented();
if (member.IsPartial)
WriteKeyword("partial ");
if (member.IsPublic)
WriteKeyword("public ");
else if (member.IsProtected)
WriteKeyword("protected ");
else if (member.IsPrivate)
WriteKeyword("private ");
else if (member.IsInternal)
WriteKeyword("internal ");
if (member.IsStatic)
WriteKeyword("static ");
else if (member.IsOverride)
WriteKeyword("override ");
else if (member.IsModifierSet(TypeMemberModifiers.Virtual))
WriteKeyword("virtual ");
else if (member.IsModifierSet(TypeMemberModifiers.Abstract))
WriteKeyword("abstract ");
if (member.IsFinal)
WriteKeyword("final ");
if (member.IsNew)
WriteKeyword("new ");
if (member.HasTransientModifier)
WriteKeyword("transient ");
}
virtual protected void WriteTypeDefinition(string keyword, TypeDefinition td)
{
WriteAttributes(td.Attributes, true);
WriteModifiers(td);
WriteIndented();
WriteKeyword(keyword);
Write(" ");
var splice = td.ParentNode as SpliceTypeMember;
if (splice != null)
WriteSplicedExpression(splice.NameExpression);
else
Write(td.Name);
if (td.GenericParameters.Count != 0)
{
WriteGenericParameterList(td.GenericParameters);
}
if (td.BaseTypes.Count > 0)
{
Write("(");
WriteCommaSeparatedList<TypeReference>(td.BaseTypes);
Write(")");
}
WriteLine(":");
BeginBlock();
if (td.Members.Count > 0)
{
foreach (TypeMember member in td.Members)
{
WriteLine();
Visit(member);
}
}
else
{
WritePass();
}
EndBlock();
}
bool WasOmitted(Expression node)
{
return null != node &&
NodeType.OmittedExpression == node.NodeType;
}
}
}
| |
// 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.Expressions.Tests
{
public static class ArrayArrayLengthTests
{
#region Boolean tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckBoolArrayArrayLengthTest(bool useInterpreter)
{
CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(0), useInterpreter);
CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(1), useInterpreter);
CheckBoolArrayArrayLengthExpression(GenerateBoolArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionBoolArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionBoolArrayArrayLength(null, useInterpreter);
}
#endregion
#region Byte tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckByteArrayArrayLengthTest(bool useInterpreter)
{
CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(0), useInterpreter);
CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(1), useInterpreter);
CheckByteArrayArrayLengthExpression(GenerateByteArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionByteArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionByteArrayArrayLength(null, useInterpreter);
}
#endregion
#region Custom tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(0), useInterpreter);
CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(1), useInterpreter);
CheckCustomArrayArrayLengthExpression(GenerateCustomArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionCustomArrayArrayLength(null, useInterpreter);
}
#endregion
#region Char tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckCharArrayArrayLengthTest(bool useInterpreter)
{
CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(0), useInterpreter);
CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(1), useInterpreter);
CheckCharArrayArrayLengthExpression(GenerateCharArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionCharArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionCharArrayArrayLength(null, useInterpreter);
}
#endregion
#region Custom2 tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckCustom2ArrayArrayLengthTest(bool useInterpreter)
{
CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(0), useInterpreter);
CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(1), useInterpreter);
CheckCustom2ArrayArrayLengthExpression(GenerateCustom2ArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionCustom2ArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionCustom2ArrayArrayLength(null, useInterpreter);
}
#endregion
#region Decimal tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckDecimalArrayArrayLengthTest(bool useInterpreter)
{
CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(0), useInterpreter);
CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(1), useInterpreter);
CheckDecimalArrayArrayLengthExpression(GenerateDecimalArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionDecimalArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionDecimalArrayArrayLength(null, useInterpreter);
}
#endregion
#region Delegate tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckDelegateArrayArrayLengthTest(bool useInterpreter)
{
CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(0), useInterpreter);
CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(1), useInterpreter);
CheckDelegateArrayArrayLengthExpression(GenerateDelegateArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionDelegateArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionDelegateArrayArrayLength(null, useInterpreter);
}
#endregion
#region Double tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckDoubleArrayArrayLengthTest(bool useInterpreter)
{
CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(0), useInterpreter);
CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(1), useInterpreter);
CheckDoubleArrayArrayLengthExpression(GenerateDoubleArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionDoubleArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionDoubleArrayArrayLength(null, useInterpreter);
}
#endregion
#region Enum tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckEnumArrayArrayLengthTest(bool useInterpreter)
{
CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(0), useInterpreter);
CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(1), useInterpreter);
CheckEnumArrayArrayLengthExpression(GenerateEnumArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionEnumArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionEnumArrayArrayLength(null, useInterpreter);
}
#endregion
#region EnumLong tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckEnumLongArrayArrayLengthTest(bool useInterpreter)
{
CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(0), useInterpreter);
CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(1), useInterpreter);
CheckEnumLongArrayArrayLengthExpression(GenerateEnumLongArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionEnumLongArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionEnumLongArrayArrayLength(null, useInterpreter);
}
#endregion
#region Float tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckFloatArrayArrayLengthTest(bool useInterpreter)
{
CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(0), useInterpreter);
CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(1), useInterpreter);
CheckFloatArrayArrayLengthExpression(GenerateFloatArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionFloatArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionFloatArrayArrayLength(null, useInterpreter);
}
#endregion
#region Func tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckFuncArrayArrayLengthTest(bool useInterpreter)
{
CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(0), useInterpreter);
CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(1), useInterpreter);
CheckFuncArrayArrayLengthExpression(GenerateFuncArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionFuncArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionFuncArrayArrayLength(null, useInterpreter);
}
#endregion
#region Interface tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckInterfaceArrayArrayLengthTest(bool useInterpreter)
{
CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(0), useInterpreter);
CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(1), useInterpreter);
CheckInterfaceArrayArrayLengthExpression(GenerateInterfaceArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionInterfaceArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionInterfaceArrayArrayLength(null, useInterpreter);
}
#endregion
#region IEquatableCustom tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(0), useInterpreter);
CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(1), useInterpreter);
CheckIEquatableCustomArrayArrayLengthExpression(GenerateIEquatableCustomArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionIEquatableCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionIEquatableCustomArrayArrayLength(null, useInterpreter);
}
#endregion
#region IEquatableCustom2 tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckIEquatableCustom2ArrayArrayLengthTest(bool useInterpreter)
{
CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(0), useInterpreter);
CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(1), useInterpreter);
CheckIEquatableCustom2ArrayArrayLengthExpression(GenerateIEquatableCustom2ArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionIEquatableCustom2ArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionIEquatableCustom2ArrayArrayLength(null, useInterpreter);
}
#endregion
#region Int tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckIntArrayArrayLengthTest(bool useInterpreter)
{
CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(0), useInterpreter);
CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(1), useInterpreter);
CheckIntArrayArrayLengthExpression(GenerateIntArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionIntArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionIntArrayArrayLength(null, useInterpreter);
}
#endregion
#region Long tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckLongArrayArrayLengthTest(bool useInterpreter)
{
CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(0), useInterpreter);
CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(1), useInterpreter);
CheckLongArrayArrayLengthExpression(GenerateLongArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionLongArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionLongArrayArrayLength(null, useInterpreter);
}
#endregion
#region Object tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckObjectArrayArrayLengthTest(bool useInterpreter)
{
CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(0), useInterpreter);
CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(1), useInterpreter);
CheckObjectArrayArrayLengthExpression(GenerateObjectArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionObjectArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionObjectArrayArrayLength(null, useInterpreter);
}
#endregion
#region Struct tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStructArrayArrayLengthTest(bool useInterpreter)
{
CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(0), useInterpreter);
CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(1), useInterpreter);
CheckStructArrayArrayLengthExpression(GenerateStructArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStructArrayArrayLength(null, useInterpreter);
}
#endregion
#region SByte tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckSByteArrayArrayLengthTest(bool useInterpreter)
{
CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(0), useInterpreter);
CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(1), useInterpreter);
CheckSByteArrayArrayLengthExpression(GenerateSByteArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionSByteArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionSByteArrayArrayLength(null, useInterpreter);
}
#endregion
#region StructWithString tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringArrayArrayLengthTest(bool useInterpreter)
{
CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(0), useInterpreter);
CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(1), useInterpreter);
CheckStructWithStringArrayArrayLengthExpression(GenerateStructWithStringArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithStringArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStructWithStringArrayArrayLength(null, useInterpreter);
}
#endregion
#region StructWithStringAndValue tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)
{
CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(0), useInterpreter);
CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(1), useInterpreter);
CheckStructWithStringAndValueArrayArrayLengthExpression(GenerateStructWithStringAndValueArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStructWithStringAndValueArrayArrayLength(null, useInterpreter);
}
#endregion
#region Short tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckShortArrayArrayLengthTest(bool useInterpreter)
{
CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(0), useInterpreter);
CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(1), useInterpreter);
CheckShortArrayArrayLengthExpression(GenerateShortArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionShortArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionShortArrayArrayLength(null, useInterpreter);
}
#endregion
#region StructWithTwoValues tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStructWithTwoValuesArrayArrayLengthTest(bool useInterpreter)
{
CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(0), useInterpreter);
CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(1), useInterpreter);
CheckStructWithTwoValuesArrayArrayLengthExpression(GenerateStructWithTwoValuesArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithTwoValuesArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStructWithTwoValuesArrayArrayLength(null, useInterpreter);
}
#endregion
#region StructWithValue tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStructWithValueArrayArrayLengthTest(bool useInterpreter)
{
CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(0), useInterpreter);
CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(1), useInterpreter);
CheckStructWithValueArrayArrayLengthExpression(GenerateStructWithValueArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStructWithValueArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStructWithValueArrayArrayLength(null, useInterpreter);
}
#endregion
#region String tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckStringArrayArrayLengthTest(bool useInterpreter)
{
CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(0), useInterpreter);
CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(1), useInterpreter);
CheckStringArrayArrayLengthExpression(GenerateStringArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionStringArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionStringArrayArrayLength(null, useInterpreter);
}
#endregion
#region UInt tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckUIntArrayArrayLengthTest(bool useInterpreter)
{
CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(0), useInterpreter);
CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(1), useInterpreter);
CheckUIntArrayArrayLengthExpression(GenerateUIntArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionUIntArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionUIntArrayArrayLength(null, useInterpreter);
}
#endregion
#region ULong tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckULongArrayArrayLengthTest(bool useInterpreter)
{
CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(0), useInterpreter);
CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(1), useInterpreter);
CheckULongArrayArrayLengthExpression(GenerateULongArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionULongArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionULongArrayArrayLength(null, useInterpreter);
}
#endregion
#region UShort tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckUShortArrayArrayLengthTest(bool useInterpreter)
{
CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(0), useInterpreter);
CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(1), useInterpreter);
CheckUShortArrayArrayLengthExpression(GenerateUShortArrayArray(5), useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionUShortArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionUShortArrayArrayLength(null, useInterpreter);
}
#endregion
#region Generic tests
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericEnumArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayArrayLengthTestHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericEnumArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLengthTestHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericObjectArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayArrayLengthTestHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLengthTestHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericArrayArrayLengthTestHelper<Scs>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructWithStringAndValueArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLengthTestHelper<Scs>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassRestrictionArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericObjectWithClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithSubClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithSubClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithSubClassRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithSubClassRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericObjectWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericObjectWithClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<object>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericCustomWithSubClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericCustomWithSubClassAndNewRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<C>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericEnumWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericEnumWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<E>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<S>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckGenericStructWithStringAndValueWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<Scs>(useInterpreter);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void CheckExceptionGenericStructWithStringAndValueWithStructRestrictionArrayArrayLengthTest(bool useInterpreter)
{
CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<Scs>(useInterpreter);
}
#endregion
#region Generic helpers
private static void CheckGenericArrayArrayLengthTestHelper<T>(bool useInterpreter)
{
CheckGenericArrayArrayLengthExpression<T>(GenerateGenericArrayArray<T>(0), useInterpreter);
CheckGenericArrayArrayLengthExpression<T>(GenerateGenericArrayArray<T>(1), useInterpreter);
CheckGenericArrayArrayLengthExpression<T>(GenerateGenericArrayArray<T>(5), useInterpreter);
}
private static void CheckExceptionGenericArrayArrayLengthTestHelper<T>(bool useInterpreter)
{
CheckExceptionGenericArrayArrayLength<T>(null, useInterpreter);
}
private static void CheckGenericWithClassRestrictionArrayArrayLengthTestHelper<Tc>(bool useInterpreter) where Tc : class
{
CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArrayArray<Tc>(0), useInterpreter);
CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArrayArray<Tc>(1), useInterpreter);
CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(GenerateGenericWithClassRestrictionArrayArray<Tc>(5), useInterpreter);
}
private static void CheckExceptionGenericWithClassRestrictionArrayArrayLengthTestHelper<Tc>(bool useInterpreter) where Tc : class
{
CheckExceptionGenericWithClassRestrictionArrayArrayLength<Tc>(null, useInterpreter);
}
private static void CheckGenericWithSubClassRestrictionArrayArrayLengthTestHelper<TC>(bool useInterpreter) where TC : C
{
CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArrayArray<TC>(0), useInterpreter);
CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArrayArray<TC>(1), useInterpreter);
CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(GenerateGenericWithSubClassRestrictionArrayArray<TC>(5), useInterpreter);
}
private static void CheckExceptionGenericWithSubClassRestrictionArrayArrayLengthTestHelper<TC>(bool useInterpreter) where TC : C
{
CheckExceptionGenericWithSubClassRestrictionArrayArrayLength<TC>(null, useInterpreter);
}
private static void CheckGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(0), useInterpreter);
CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(1), useInterpreter);
CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(5), useInterpreter);
}
private static void CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLengthTestHelper<Tcn>(bool useInterpreter) where Tcn : class, new()
{
CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLength<Tcn>(null, useInterpreter);
}
private static void CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(0), useInterpreter);
CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(1), useInterpreter);
CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(5), useInterpreter);
}
private static void CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLengthTestHelper<TCn>(bool useInterpreter) where TCn : C, new()
{
CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLength<TCn>(null, useInterpreter);
}
private static void CheckGenericWithStructRestrictionArrayArrayLengthTestHelper<Ts>(bool useInterpreter) where Ts : struct
{
CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArrayArray<Ts>(0), useInterpreter);
CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArrayArray<Ts>(1), useInterpreter);
CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(GenerateGenericWithStructRestrictionArrayArray<Ts>(5), useInterpreter);
}
private static void CheckExceptionGenericWithStructRestrictionArrayArrayLengthTestHelper<Ts>(bool useInterpreter) where Ts : struct
{
CheckExceptionGenericWithStructRestrictionArrayArrayLength<Ts>(null, useInterpreter);
}
#endregion
#region Generate array
private static bool[][] GenerateBoolArrayArray(int size)
{
bool[][] array = new bool[][] { null, new bool[0], new bool[] { true, false }, new bool[100] };
bool[][] result = new bool[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static byte[][] GenerateByteArrayArray(int size)
{
byte[][] array = new byte[][] { null, new byte[0], new byte[] { 0, 1, byte.MaxValue }, new byte[100] };
byte[][] result = new byte[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static C[][] GenerateCustomArrayArray(int size)
{
C[][] array = new C[][] { null, new C[0], new C[] { null, new C(), new D(), new D(0), new D(5) }, new C[100] };
C[][] result = new C[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static char[][] GenerateCharArrayArray(int size)
{
char[][] array = new char[][] { null, new char[0], new char[] { '\0', '\b', 'A', '\uffff' }, new char[100] };
char[][] result = new char[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static D[][] GenerateCustom2ArrayArray(int size)
{
D[][] array = new D[][] { null, new D[0], new D[] { null, new D(), new D(0), new D(5) }, new D[100] };
D[][] result = new D[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static decimal[][] GenerateDecimalArrayArray(int size)
{
decimal[][] array = new decimal[][] { null, new decimal[0], new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, new decimal[100] };
decimal[][] result = new decimal[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Delegate[][] GenerateDelegateArrayArray(int size)
{
Delegate[][] array = new Delegate[][] { null, new Delegate[0], new Delegate[] { null, (Func<object>)delegate () { return null; }, (Func<int, int>)delegate (int i) { return i + 1; }, (Action<object>)delegate { } }, new Delegate[100] };
Delegate[][] result = new Delegate[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static double[][] GenerateDoubleArrayArray(int size)
{
double[][] array = new double[][] { null, new double[0], new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }, new double[100] };
double[][] result = new double[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static E[][] GenerateEnumArrayArray(int size)
{
E[][] array = new E[][] { null, new E[0], new E[] { (E)0, E.A, E.B, (E)int.MaxValue, (E)int.MinValue }, new E[100] };
E[][] result = new E[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static El[][] GenerateEnumLongArrayArray(int size)
{
El[][] array = new El[][] { null, new El[0], new El[] { (El)0, El.A, El.B, (El)long.MaxValue, (El)long.MinValue }, new El[100] };
El[][] result = new El[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static float[][] GenerateFloatArrayArray(int size)
{
float[][] array = new float[][] { null, new float[0], new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }, new float[100] };
float[][] result = new float[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Func<object>[][] GenerateFuncArrayArray(int size)
{
Func<object>[][] array = new Func<object>[][] { null, new Func<object>[0], new Func<object>[] { null, (Func<object>)delegate () { return null; } }, new Func<object>[100] };
Func<object>[][] result = new Func<object>[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static I[][] GenerateInterfaceArrayArray(int size)
{
I[][] array = new I[][] { null, new I[0], new I[] { null, new C(), new D(), new D(0), new D(5) }, new I[100] };
I[][] result = new I[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static IEquatable<C>[][] GenerateIEquatableCustomArrayArray(int size)
{
IEquatable<C>[][] array = new IEquatable<C>[][] { null, new IEquatable<C>[0], new IEquatable<C>[] { null, new C(), new D(), new D(0), new D(5) }, new IEquatable<C>[100] };
IEquatable<C>[][] result = new IEquatable<C>[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static IEquatable<D>[][] GenerateIEquatableCustom2ArrayArray(int size)
{
IEquatable<D>[][] array = new IEquatable<D>[][] { null, new IEquatable<D>[0], new IEquatable<D>[] { null, new D(), new D(0), new D(5) }, new IEquatable<D>[100] };
IEquatable<D>[][] result = new IEquatable<D>[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static int[][] GenerateIntArrayArray(int size)
{
int[][] array = new int[][] { null, new int[0], new int[] { 0, 1, -1, int.MinValue, int.MaxValue }, new int[100] };
int[][] result = new int[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static long[][] GenerateLongArrayArray(int size)
{
long[][] array = new long[][] { null, new long[0], new long[] { 0, 1, -1, long.MinValue, long.MaxValue }, new long[100] };
long[][] result = new long[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static object[][] GenerateObjectArrayArray(int size)
{
object[][] array = new object[][] { null, new object[0], new object[] { null, new object(), new C(), new D(3) }, new object[100] };
object[][] result = new object[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static S[][] GenerateStructArrayArray(int size)
{
S[][] array = new S[][] { null, new S[0], new S[] { default(S), new S() }, new S[100] };
S[][] result = new S[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static sbyte[][] GenerateSByteArrayArray(int size)
{
sbyte[][] array = new sbyte[][] { null, new sbyte[0], new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, new sbyte[100] };
sbyte[][] result = new sbyte[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Sc[][] GenerateStructWithStringArrayArray(int size)
{
Sc[][] array = new Sc[][] { null, new Sc[0], new Sc[] { default(Sc), new Sc(), new Sc(null) }, new Sc[100] };
Sc[][] result = new Sc[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Scs[][] GenerateStructWithStringAndValueArrayArray(int size)
{
Scs[][] array = new Scs[][] { null, new Scs[0], new Scs[] { default(Scs), new Scs(), new Scs(null, new S()) }, new Scs[100] };
Scs[][] result = new Scs[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static short[][] GenerateShortArrayArray(int size)
{
short[][] array = new short[][] { null, new short[0], new short[] { 0, 1, -1, short.MinValue, short.MaxValue }, new short[100] };
short[][] result = new short[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Sp[][] GenerateStructWithTwoValuesArrayArray(int size)
{
Sp[][] array = new Sp[][] { null, new Sp[0], new Sp[] { default(Sp), new Sp(), new Sp(5, 5.0) }, new Sp[100] };
Sp[][] result = new Sp[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Ss[][] GenerateStructWithValueArrayArray(int size)
{
Ss[][] array = new Ss[][] { null, new Ss[0], new Ss[] { default(Ss), new Ss(), new Ss(new S()) }, new Ss[100] };
Ss[][] result = new Ss[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static string[][] GenerateStringArrayArray(int size)
{
string[][] array = new string[][] { null, new string[0], new string[] { null, "", "a", "foo" }, new string[100] };
string[][] result = new string[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static uint[][] GenerateUIntArrayArray(int size)
{
uint[][] array = new uint[][] { null, new uint[0], new uint[] { 0, 1, uint.MaxValue }, new uint[100] };
uint[][] result = new uint[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static ulong[][] GenerateULongArrayArray(int size)
{
ulong[][] array = new ulong[][] { null, new ulong[0], new ulong[] { 0, 1, ulong.MaxValue }, new ulong[100] };
ulong[][] result = new ulong[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static ushort[][] GenerateUShortArrayArray(int size)
{
ushort[][] array = new ushort[][] { null, new ushort[0], new ushort[] { 0, 1, ushort.MaxValue }, new ushort[100] };
ushort[][] result = new ushort[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static T[][] GenerateGenericArrayArray<T>(int size)
{
T[][] array = new T[][] { null, new T[0], new T[] { default(T) }, new T[100] };
T[][] result = new T[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Tc[][] GenerateGenericWithClassRestrictionArrayArray<Tc>(int size) where Tc : class
{
Tc[][] array = new Tc[][] { null, new Tc[0], new Tc[] { null, default(Tc) }, new Tc[100] };
Tc[][] result = new Tc[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static TC[][] GenerateGenericWithSubClassRestrictionArrayArray<TC>(int size) where TC : C
{
TC[][] array = new TC[][] { null, new TC[0], new TC[] { null, default(TC), (TC)new C() }, new TC[100] };
TC[][] result = new TC[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Tcn[][] GenerateGenericWithClassAndNewRestrictionArrayArray<Tcn>(int size) where Tcn : class, new()
{
Tcn[][] array = new Tcn[][] { null, new Tcn[0], new Tcn[] { null, default(Tcn), new Tcn() }, new Tcn[100] };
Tcn[][] result = new Tcn[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static TCn[][] GenerateGenericWithSubClassAndNewRestrictionArrayArray<TCn>(int size) where TCn : C, new()
{
TCn[][] array = new TCn[][] { null, new TCn[0], new TCn[] { null, default(TCn), new TCn(), (TCn)new C() }, new TCn[100] };
TCn[][] result = new TCn[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
private static Ts[][] GenerateGenericWithStructRestrictionArrayArray<Ts>(int size) where Ts : struct
{
Ts[][] array = new Ts[][] { null, new Ts[0], new Ts[] { default(Ts), new Ts() }, new Ts[100] };
Ts[][] result = new Ts[size][];
for (int i = 0; i < size; i++)
{
result[i] = array[i % array.Length];
}
return result;
}
#endregion
#region Check length expression
private static void CheckBoolArrayArrayLengthExpression(bool[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(bool[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckByteArrayArrayLengthExpression(byte[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(byte[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckCustomArrayArrayLengthExpression(C[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(C[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckCharArrayArrayLengthExpression(char[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(char[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckCustom2ArrayArrayLengthExpression(D[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(D[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckDecimalArrayArrayLengthExpression(decimal[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(decimal[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckDelegateArrayArrayLengthExpression(Delegate[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Delegate[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckDoubleArrayArrayLengthExpression(double[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(double[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckEnumArrayArrayLengthExpression(E[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(E[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckEnumLongArrayArrayLengthExpression(El[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(El[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckFloatArrayArrayLengthExpression(float[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(float[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckFuncArrayArrayLengthExpression(Func<object>[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Func<object>[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckInterfaceArrayArrayLengthExpression(I[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(I[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckIEquatableCustomArrayArrayLengthExpression(IEquatable<C>[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(IEquatable<C>[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckIEquatableCustom2ArrayArrayLengthExpression(IEquatable<D>[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(IEquatable<D>[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckIntArrayArrayLengthExpression(int[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(int[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckLongArrayArrayLengthExpression(long[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(long[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckObjectArrayArrayLengthExpression(object[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(object[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructArrayArrayLengthExpression(S[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(S[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckSByteArrayArrayLengthExpression(sbyte[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(sbyte[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithStringArrayArrayLengthExpression(Sc[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Sc[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithStringAndValueArrayArrayLengthExpression(Scs[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Scs[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckShortArrayArrayLengthExpression(short[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(short[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithTwoValuesArrayArrayLengthExpression(Sp[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Sp[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStructWithValueArrayArrayLengthExpression(Ss[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Ss[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckStringArrayArrayLengthExpression(string[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(string[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckUIntArrayArrayLengthExpression(uint[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(uint[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckULongArrayArrayLengthExpression(ulong[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(ulong[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckUShortArrayArrayLengthExpression(ushort[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(ushort[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericArrayArrayLengthExpression<T>(T[][] array, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(T[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithClassRestrictionArrayArrayLengthExpression<Tc>(Tc[][] array, bool useInterpreter) where Tc : class
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Tc[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithSubClassRestrictionArrayArrayLengthExpression<TC>(TC[][] array, bool useInterpreter) where TC : C
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(TC[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression<Tcn>(Tcn[][] array, bool useInterpreter) where Tcn : class, new()
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Tcn[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression<TCn>(TCn[][] array, bool useInterpreter) where TCn : C, new()
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(TCn[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
private static void CheckGenericWithStructRestrictionArrayArrayLengthExpression<Ts>(Ts[][] array, bool useInterpreter) where Ts : struct
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.ArrayLength(Expression.Constant(array, typeof(Ts[][]))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(array.Length, f());
}
#endregion
#region Check exception array length
private static void CheckExceptionBoolArrayArrayLength(bool[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckBoolArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckBoolArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionByteArrayArrayLength(byte[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckByteArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckByteArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionCustomArrayArrayLength(C[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckCustomArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckCustomArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionCharArrayArrayLength(char[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckCharArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckCharArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionCustom2ArrayArrayLength(D[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckCustom2ArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckCustom2ArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionDecimalArrayArrayLength(decimal[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckDecimalArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckDecimalArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionDelegateArrayArrayLength(Delegate[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckDelegateArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckDelegateArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionDoubleArrayArrayLength(double[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckDoubleArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckDoubleArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionEnumArrayArrayLength(E[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckEnumArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckEnumArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionEnumLongArrayArrayLength(El[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckEnumLongArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckEnumLongArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionFloatArrayArrayLength(float[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckFloatArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckFloatArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionFuncArrayArrayLength(Func<object>[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckFuncArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckFuncArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionInterfaceArrayArrayLength(I[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckInterfaceArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckInterfaceArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionIEquatableCustomArrayArrayLength(IEquatable<C>[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckIEquatableCustomArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckIEquatableCustomArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionIEquatableCustom2ArrayArrayLength(IEquatable<D>[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckIEquatableCustom2ArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckIEquatableCustom2ArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionIntArrayArrayLength(int[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckIntArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckIntArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionLongArrayArrayLength(long[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckLongArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckLongArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionObjectArrayArrayLength(object[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckObjectArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckObjectArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStructArrayArrayLength(S[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStructArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStructArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionSByteArrayArrayLength(sbyte[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckSByteArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckSByteArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStructWithStringArrayArrayLength(Sc[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStructWithStringArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithStringArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStructWithStringAndValueArrayArrayLength(Scs[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStructWithStringAndValueArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithStringAndValueArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionShortArrayArrayLength(short[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckShortArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckShortArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStructWithTwoValuesArrayArrayLength(Sp[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStructWithTwoValuesArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithTwoValuesArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStructWithValueArrayArrayLength(Ss[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStructWithValueArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStructWithValueArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionStringArrayArrayLength(string[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckStringArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckStringArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionUIntArrayArrayLength(uint[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckUIntArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckUIntArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionULongArrayArrayLength(ulong[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckULongArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckULongArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionUShortArrayArrayLength(ushort[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckUShortArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckUShortArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericArrayArrayLength<T>(T[][] array, bool useInterpreter)
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericWithClassRestrictionArrayArrayLength<Tc>(Tc[][] array, bool useInterpreter) where Tc : class
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericWithClassRestrictionArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithClassRestrictionArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericWithSubClassRestrictionArrayArrayLength<TC>(TC[][] array, bool useInterpreter) where TC : C
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericWithSubClassRestrictionArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithSubClassRestrictionArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericWithClassAndNewRestrictionArrayArrayLength<Tcn>(Tcn[][] array, bool useInterpreter) where Tcn : class, new()
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericWithSubClassAndNewRestrictionArrayArrayLength<TCn>(TCn[][] array, bool useInterpreter) where TCn : C, new()
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithSubClassAndNewRestrictionArrayArrayLengthExpression(array, useInterpreter));
}
private static void CheckExceptionGenericWithStructRestrictionArrayArrayLength<Ts>(Ts[][] array, bool useInterpreter) where Ts : struct
{
if (array == null)
Assert.Throws<NullReferenceException>(() => CheckGenericWithStructRestrictionArrayArrayLengthExpression(array, useInterpreter));
else
Assert.Throws<IndexOutOfRangeException>(() => CheckGenericWithStructRestrictionArrayArrayLengthExpression(array, useInterpreter));
}
#endregion
#region Regression tests
[Fact]
public static void ArrayLength_MultiDimensionalOf1()
{
foreach (var e in new Expression[] { Expression.Parameter(typeof(int).MakeArrayType(1)), Expression.Constant(new int[2, 2]) })
{
AssertExtensions.Throws<ArgumentException>("array", () => Expression.ArrayLength(e));
}
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DogMinigame : MonoBehaviour
{
public DogGameStoryEvent storyEvent;
public List<AudioClip> barkClips;
public List<AudioClip> scratchClips;
public List<AudioClip> stepClips;
public List<AudioClip> growlClips;
public AudioSource barkAudio;
public AudioSource scratchAudio;
public AudioSource otherAudio;
public float noiseThreshold;
private bool running = false;
private bool isAngry = false;
public float waitUntilStart = 2f;
private float gameTime = 5f;
private float angryTime = 0f;
public float totalGameTime = 5f;
public float totalAngryTime = 3f;
private float keepQuietTime = 0f;
private float timeThatThePlayerIsBeingNoisy = 0f;
private bool isGrowling = false;
private float dogIsNowGrowling = 0f;
private bool eventOcurred = false;
private int timesAngry = 0;
public System.Action GameOver;
private void Start ()
{
Closet.GetInstance().onClosetSound += OnClosetSound;
Closet.GetInstance().onPlayerHidden += OnPlayerHidden;
StartCoroutine("UpdateAudioCapture");
gameTime = totalGameTime;
}
private void Destroy()
{
Closet.GetInstance().onClosetSound -= OnClosetSound;
GameOver();
}
private IEnumerator UpdateAudioCapture ()
{
yield return new WaitForSeconds(waitUntilStart);
running = true;
StartCoroutine("StartScratching");
SoundManager.Instance.heartBeat.heartRateQuickener = 3f;
while(running)
{
// player holds breadth for 5 seconds
if(AudioPlayBack.GetInstance().GetComponent<AudioAnalyze>().GetAvgSound() > noiseThreshold || eventOcurred)
{
eventOcurred = false;
keepQuietTime = 0f;
timeThatThePlayerIsBeingNoisy += Time.deltaTime;
if(timeThatThePlayerIsBeingNoisy >= 3f){
if(!isGrowling)StartCoroutine("StartGrowling");
dogIsNowGrowling += Time.deltaTime;
//if(dogIsNowGrowling > 5f) Detected();
}
if(angryTime>0f){
angryTime = totalAngryTime;
gameTime = totalGameTime;
} else {
if(!isAngry){
OnPlayerHidden();
}
gameTime = totalGameTime;
}
} else{
keepQuietTime += Time.deltaTime;
if(isGrowling){
dogIsNowGrowling += Time.deltaTime;
//if(dogIsNowGrowling > 5f) Detected();
}
timeThatThePlayerIsBeingNoisy = 0f;
if(keepQuietTime > 4f) EndMinigame();
}
yield return null;
}
}
private IEnumerator StartScratching(){
//start scratching
StartCoroutine("ScratchStuff");
//bark every 3s
while(running){
yield return new WaitForSeconds(3f);
if(/*!barkAudio.isPlaying*/true)
{
barkAudio.loop = false;
barkAudio.clip = barkClips[Random.Range(0, barkClips.Count)];
barkAudio.Play();
}
}
}
private IEnumerator ScratchStuff(){
while(running){
if(!otherAudio.isPlaying)
{
scratchAudio.clip = scratchClips[Random.Range(0, scratchClips.Count)];
scratchAudio.loop = true;
scratchAudio.Play();
}
yield return new WaitForSeconds(scratchAudio.clip.length + 0.2f);
}
}
private IEnumerator StartGrowling(){
//stop scratching
scratchAudio.Stop();
StopCoroutine("StartScratching");
StopCoroutine("ScratchStuff");
SoundManager.Instance.heartBeat.heartRateQuickener = 5f;
//start growling
while(running){
if(!otherAudio.isPlaying)
{
otherAudio.clip = growlClips[Random.Range(0, growlClips.Count)];
otherAudio.loop = true;
otherAudio.Play();
}
yield return new WaitForSeconds(otherAudio.clip.length);
}
}
private void Detected(){
StopCoroutine("UpdateAudioCapture");
StopCoroutine("StartScratching");
StopCoroutine("ScratchStuff");
StopCoroutine("StartGrowling");
scratchAudio.Stop();
otherAudio.Stop();
Debug.Log("Now start detection story");
}
private void OnClosetSound(SoundTrigger.Type type, float volume)
{
print ("I AM TOO LOAUD! "+volume);
if(volume < noiseThreshold) return;
//do something
eventOcurred = true;
if(timesAngry==0){
StartCoroutine(GetAngryShort());
timesAngry++;
return;
}
GetAngry();
}
private void OnPlayerHidden()
{
//do something
eventOcurred = true;
}
private void OnPlayerUnhidden()
{
//do something
eventOcurred = true;
}
[ContextMenu("Test Angry")]
private void GetAngry()
{
Debug.Log("doggy gets really angry");
isAngry = true;
angryTime = totalAngryTime;
if(/*!barkAudio.isPlaying*/true)
{
barkAudio.clip = barkClips[Random.Range(0, barkClips.Count)];
barkAudio.loop = true;
barkAudio.Play();
}
if(/*!scratchAudio.isPlaying*/true)
{
scratchAudio.clip = scratchClips[Random.Range(0, scratchClips.Count)];
scratchAudio.loop = true;
scratchAudio.Play();
}
}
[ContextMenu("Test Angry Short")]
private IEnumerator GetAngryShort()
{
if(!isAngry){
Debug.Log("doggy gets angry once");
if(!barkAudio.isPlaying)
{
barkAudio.clip = barkClips[Random.Range(0, barkClips.Count)];
barkAudio.loop = false;
barkAudio.Play();
}
if(!scratchAudio.isPlaying)
{
scratchAudio.clip = scratchClips[Random.Range(0, scratchClips.Count)];
scratchAudio.loop = false;
scratchAudio.Play();
}
timesAngry++;
yield return new WaitForSeconds(2.0f);
}
}
private void CalmDown()
{
if(barkAudio.isPlaying)
barkAudio.Stop();
if(scratchAudio.isPlaying)
scratchAudio.Stop();
isAngry = false;
angryTime = 0f;
Debug.Log ("doggy calms down");
}
private void EndMinigame()
{
running = false;
StopCoroutine("UpdateAudioCapture");
StopCoroutine("StartScratching");
StopCoroutine("ScratchStuff");
StopCoroutine("StartGrowling");
scratchAudio.Stop();
otherAudio.Stop();
Debug.Log("Doggy didn't find you and walks away");
storyEvent.OnDone(storyEvent);
}
#if UNITY_EDITOR
public bool showDebug = true;
private void OnGUI(){
if(!showDebug)return;
GUILayout.Box("Keep Quiet time: " + keepQuietTime);
GUILayout.Box("Being Noisy: " + timeThatThePlayerIsBeingNoisy);
GUILayout.Box("Growling: " + dogIsNowGrowling);
}
#endif
}
| |
using System;
using System.Threading.Tasks;
using NSubstitute;
using NuKeeper.Abstractions.CollaborationModels;
using NuKeeper.Abstractions.CollaborationPlatform;
using NuKeeper.Abstractions.Configuration;
using NuKeeper.Abstractions.Logging;
using NUnit.Framework;
namespace NuKeeper.GitHub.Tests
{
[TestFixture]
public class GitHubForkFinderTests
{
[Test]
public async Task ThrowsWhenNoPushableForkCanBeFound()
{
var fallbackFork = DefaultFork();
var forkFinder = new GitHubForkFinder(Substitute.For<ICollaborationPlatform>(), Substitute.For<INuKeeperLogger>(), ForkMode.PreferFork);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.Null);
}
[Test]
public async Task FallbackForkIsUsedWhenItIsFound()
{
var fallbackFork = DefaultFork();
var fallbackRepoData = RepositoryBuilder.MakeRepository();
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
collaborationPlatform.GetUserRepository(fallbackFork.Owner, fallbackFork.Name)
.Returns(fallbackRepoData);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.PreferFork);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.Not.Null);
Assert.That(fork, Is.EqualTo(fallbackFork));
}
[Test]
public async Task FallbackForkIsNotUsedWhenItIsNotPushable()
{
var fallbackFork = DefaultFork();
var fallbackRepoData = RepositoryBuilder.MakeRepository(true, false);
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
collaborationPlatform.GetUserRepository(fallbackFork.Owner, fallbackFork.Name)
.Returns(fallbackRepoData);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.PreferFork);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.Null);
}
[Test]
public async Task WhenSuitableUserForkIsFoundItIsUsedOverFallback()
{
var fallbackFork = DefaultFork();
var userRepo = RepositoryBuilder.MakeRepository();
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
collaborationPlatform.GetUserRepository(Arg.Any<string>(), Arg.Any<string>())
.Returns(userRepo);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.PreferFork);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.Not.EqualTo(fallbackFork));
AssertForkMatchesRepo(fork, userRepo);
}
[Test]
public async Task WhenSuitableUserForkIsFound_ThatMatchesCloneHtmlUrl_ItIsUsedOverFallback()
{
var fallbackFork = new ForkData(new Uri(RepositoryBuilder.ParentCloneUrl), "testOrg", "someRepo");
var userRepo = RepositoryBuilder.MakeRepository();
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
collaborationPlatform.GetUserRepository(Arg.Any<string>(), Arg.Any<string>())
.Returns(userRepo);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.PreferFork);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.Not.EqualTo(fallbackFork));
AssertForkMatchesRepo(fork, userRepo);
}
[Test]
public async Task WhenSuitableUserForkIsFound_ThatMatchesCloneHtmlUrl_WithRepoUrlVariation()
{
var fallbackFork = new ForkData(new Uri(RepositoryBuilder.ParentCloneBareUrl), "testOrg", "someRepo");
var userRepo = RepositoryBuilder.MakeRepository();
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
collaborationPlatform.GetUserRepository(Arg.Any<string>(), Arg.Any<string>())
.Returns(userRepo);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.PreferFork);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.Not.EqualTo(fallbackFork));
AssertForkMatchesRepo(fork, userRepo);
}
[Test]
public async Task WhenSuitableUserForkIsFound_ThatMatchesCloneHtmlUrl_WithParentRepoUrlVariation()
{
var fallbackFork = new ForkData(new Uri(RepositoryBuilder.ParentCloneUrl), "testOrg", "someRepo");
var userRepo = RepositoryBuilder.MakeRepository(
RepositoryBuilder.ForkCloneUrl,
true, true, "userRepo",
RepositoryBuilder.MakeParentRepo(RepositoryBuilder.ParentCloneBareUrl));
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
collaborationPlatform.GetUserRepository(Arg.Any<string>(), Arg.Any<string>())
.Returns(userRepo);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.PreferFork);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.Not.EqualTo(fallbackFork));
AssertForkMatchesRepo(fork, userRepo);
}
[Test]
public async Task WhenUnsuitableUserForkIsFoundItIsNotUsed()
{
var fallbackFork = NoMatchFork();
var userRepo = RepositoryBuilder.MakeRepository();
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
collaborationPlatform.GetUserRepository(Arg.Any<string>(), Arg.Any<string>())
.Returns(userRepo);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.PreferFork);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.EqualTo(fallbackFork));
}
[Test]
public async Task WhenUserForkIsNotFoundItIsCreated()
{
var fallbackFork = DefaultFork();
var userRepo = RepositoryBuilder.MakeRepository();
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
collaborationPlatform.GetUserRepository(Arg.Any<string>(), Arg.Any<string>())
.Returns((Repository)null);
collaborationPlatform.MakeUserFork(Arg.Any<string>(), Arg.Any<string>())
.Returns(userRepo);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.PreferFork);
var actualFork = await forkFinder.FindPushFork("testUser", fallbackFork);
await collaborationPlatform.Received(1).MakeUserFork(Arg.Any<string>(), Arg.Any<string>());
Assert.That(actualFork, Is.Not.Null);
Assert.That(actualFork, Is.Not.EqualTo(fallbackFork));
}
[Test]
public async Task PreferSingleRepoModeWillNotPreferFork()
{
var fallbackFork = DefaultFork();
var userRepo = RepositoryBuilder.MakeRepository();
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
collaborationPlatform.GetUserRepository(Arg.Any<string>(), Arg.Any<string>())
.Returns(userRepo);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.PreferSingleRepository);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.EqualTo(fallbackFork));
}
[Test]
public async Task PreferSingleRepoModeWillUseForkWhenUpstreamIsUnsuitable()
{
var fallbackFork = DefaultFork();
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
var defaultRepo = RepositoryBuilder.MakeRepository(true, false);
collaborationPlatform.GetUserRepository(fallbackFork.Owner, fallbackFork.Name)
.Returns(defaultRepo);
var userRepo = RepositoryBuilder.MakeRepository();
collaborationPlatform.GetUserRepository("testUser", fallbackFork.Name)
.Returns(userRepo);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.PreferSingleRepository);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.Not.EqualTo(fallbackFork));
AssertForkMatchesRepo(fork, userRepo);
}
[Test]
public async Task SingleRepoOnlyModeWillNotPreferFork()
{
var fallbackFork = DefaultFork();
var userRepo = RepositoryBuilder.MakeRepository();
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
collaborationPlatform.GetUserRepository(Arg.Any<string>(), Arg.Any<string>())
.Returns(userRepo);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.SingleRepositoryOnly);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.EqualTo(fallbackFork));
}
[Test]
public async Task SingleRepoOnlyModeWillNotUseForkWhenUpstreamIsUnsuitable()
{
var fallbackFork = DefaultFork();
var collaborationPlatform = Substitute.For<ICollaborationPlatform>();
var defaultRepo = RepositoryBuilder.MakeRepository(true, false);
collaborationPlatform.GetUserRepository(fallbackFork.Owner, fallbackFork.Name)
.Returns(defaultRepo);
var userRepo = RepositoryBuilder.MakeRepository();
collaborationPlatform.GetUserRepository("testUser", fallbackFork.Name)
.Returns(userRepo);
var forkFinder = new GitHubForkFinder(collaborationPlatform, Substitute.For<INuKeeperLogger>(), ForkMode.SingleRepositoryOnly);
var fork = await forkFinder.FindPushFork("testUser", fallbackFork);
Assert.That(fork, Is.Null);
}
private static ForkData DefaultFork()
{
return new ForkData(new Uri(RepositoryBuilder.ParentCloneUrl), "testOrg", "someRepo");
}
private static ForkData NoMatchFork()
{
return new ForkData(new Uri(RepositoryBuilder.NoMatchUrl), "testOrg", "someRepo");
}
private static void AssertForkMatchesRepo(ForkData fork, Repository repo)
{
Assert.That(fork, Is.Not.Null);
Assert.That(fork.Name, Is.EqualTo(repo.Name));
Assert.That(fork.Owner, Is.EqualTo(repo.Owner.Login));
Assert.That(fork.Uri, Is.EqualTo(repo.CloneUrl));
}
}
}
| |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Routing;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Navigation;
using OrchardCore.Settings;
using OrchardCore.Users.Indexes;
using OrchardCore.Users.Models;
using OrchardCore.Users.ViewModels;
using YesSql;
namespace OrchardCore.Users.Controllers
{
public class AdminController : Controller, IUpdateModel
{
private readonly UserManager<IUser> _userManager;
private readonly ISession _session;
private readonly IAuthorizationService _authorizationService;
private readonly ISiteService _siteService;
private readonly IDisplayManager<User> _userDisplayManager;
private readonly INotifier _notifier;
private readonly dynamic New;
private readonly IHtmlLocalizer TH;
public AdminController(
IDisplayManager<User> userDisplayManager,
IAuthorizationService authorizationService,
ISession session,
UserManager<IUser> userManager,
INotifier notifier,
ISiteService siteService,
IShapeFactory shapeFactory,
IHtmlLocalizer<AdminController> htmlLocalizer
)
{
_userDisplayManager = userDisplayManager;
_authorizationService = authorizationService;
_session = session;
_userManager = userManager;
_notifier = notifier;
_siteService = siteService;
New = shapeFactory;
TH = htmlLocalizer;
}
public async Task<ActionResult> Index(UserIndexOptions options, PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers))
{
return Unauthorized();
}
var siteSettings = await _siteService.GetSiteSettingsAsync();
var pager = new Pager(pagerParameters, siteSettings.PageSize);
// default options
if (options == null)
{
options = new UserIndexOptions();
}
var users = _session.Query<User, UserIndex>();
switch (options.Filter)
{
case UsersFilter.Approved:
//users = users.Where(u => u.RegistrationStatus == UserStatus.Approved);
break;
case UsersFilter.Pending:
//users = users.Where(u => u.RegistrationStatus == UserStatus.Pending);
break;
case UsersFilter.EmailPending:
//users = users.Where(u => u.EmailStatus == UserStatus.Pending);
break;
}
if (!string.IsNullOrWhiteSpace(options.Search))
{
users = users.Where(u => u.NormalizedUserName.Contains(options.Search) || u.NormalizedEmail.Contains(options.Search));
}
switch (options.Order)
{
case UsersOrder.Name:
users = users.OrderBy(u => u.NormalizedUserName);
break;
case UsersOrder.Email:
users = users.OrderBy(u => u.NormalizedEmail);
break;
case UsersOrder.CreatedUtc:
//users = users.OrderBy(u => u.CreatedUtc);
break;
case UsersOrder.LastLoginUtc:
//users = users.OrderBy(u => u.LastLoginUtc);
break;
}
var count = await users.CountAsync();
var results = await users
.Skip(pager.GetStartIndex())
.Take(pager.PageSize)
.ListAsync();
// Maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Filter", options.Filter);
routeData.Values.Add("Options.Search", options.Search);
routeData.Values.Add("Options.Order", options.Order);
var pagerShape = New.Pager(pager).TotalItemCount(count).RouteData(routeData);
var model = new UsersIndexViewModel
{
Users = await Task.WhenAll(
results.Select(async x =>
new UserEntry { Shape = await _userDisplayManager.BuildDisplayAsync(x, this, "SummaryAdmin") })),
Options = options,
Pager = pagerShape
};
return View(model);
}
public async Task<IActionResult> Create()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers))
{
return Unauthorized();
}
var shape = await _userDisplayManager.BuildEditorAsync(new User(), this);
return View(shape);
}
[HttpPost]
[ActionName(nameof(Create))]
public async Task<IActionResult> CreatePost()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers))
{
return Unauthorized();
}
var shape = await _userDisplayManager.UpdateEditorAsync(new User(), this);
if (!ModelState.IsValid)
{
return View(shape);
}
_notifier.Success(TH["User created successfully"]);
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Edit(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers))
{
return Unauthorized();
}
var currentUser = await _userManager.FindByIdAsync(id);
if (!(currentUser is User))
{
return NotFound();
}
var shape = await _userDisplayManager.BuildEditorAsync((User) currentUser, this);
return View(shape);
}
[HttpPost]
[ActionName(nameof(Edit))]
public async Task<IActionResult> EditPost(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers))
{
return Unauthorized();
}
var currentUser = await _userManager.FindByIdAsync(id);
if (currentUser == null)
{
return NotFound();
}
var shape = await _userDisplayManager.UpdateEditorAsync((User) currentUser, this);
if (!ModelState.IsValid)
{
return View(shape);
}
_notifier.Success(TH["User updated successfully"]);
return RedirectToAction(nameof(Index));
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageUsers))
{
return Unauthorized();
}
var currentUser = await _userManager.FindByIdAsync(id);
if (!(currentUser is User))
{
return NotFound();
}
var result = await _userManager.DeleteAsync(currentUser);
if (result.Succeeded)
{
_notifier.Success(TH["User deleted successfully"]);
}
else
{
_session.Cancel();
_notifier.Error(TH["Could not delete the user"]);
foreach (var error in result.Errors)
{
_notifier.Error(TH[error.Description]);
}
}
return RedirectToAction(nameof(Index));
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Activation
{
using System;
using System.Runtime;
using System.ServiceModel.Channels;
using System.Threading;
delegate void ListenerConnectionModeCallback(ListenerConnectionModeReader connectionModeReader);
sealed class ListenerConnectionModeReader : InitialServerConnectionReader
{
Exception readException;
ServerModeDecoder decoder;
byte[] buffer;
int offset;
int size;
ListenerConnectionModeCallback callback;
static WaitCallback readCallback;
byte[] accruedData;
TimeoutHelper receiveTimeoutHelper;
public ListenerConnectionModeReader(IConnection connection, ListenerConnectionModeCallback callback, ConnectionClosedCallback closedCallback)
: base(connection, closedCallback)
{
this.callback = callback;
}
public int BufferOffset
{
get { return offset; }
}
public int BufferSize
{
get { return size; }
}
public long StreamPosition
{
get { return decoder.StreamPosition; }
}
public TimeSpan GetRemainingTimeout()
{
return this.receiveTimeoutHelper.RemainingTime();
}
void Complete(Exception e)
{
// exception will be logged by the caller
readException = e;
Complete();
}
void Complete()
{
callback(this);
}
bool ContinueReading()
{
while (true)
{
if (size == 0)
{
if (readCallback == null)
{
readCallback = new WaitCallback(ReadCallback);
}
// if we already have buffered some data we need
// to accrue it in case we're duping the connection
if (buffer != null)
{
int dataOffset = 0;
if (accruedData == null)
{
accruedData = new byte[offset];
}
else
{
byte[] newAccruedData = new byte[accruedData.Length + offset];
Buffer.BlockCopy(accruedData, 0, newAccruedData, 0, accruedData.Length);
dataOffset = this.accruedData.Length;
accruedData = newAccruedData;
}
Buffer.BlockCopy(buffer, 0, accruedData, dataOffset, offset);
}
if (Connection.BeginRead(0, Connection.AsyncReadBufferSize, GetRemainingTimeout(),
readCallback, this) == AsyncCompletionResult.Queued)
{
return false;
}
GetReadResult();
}
while (true)
{
int bytesDecoded = decoder.Decode(buffer, offset, size);
if (bytesDecoded > 0)
{
offset += bytesDecoded;
size -= bytesDecoded;
}
if (decoder.CurrentState == ServerModeDecoder.State.Done)
{
return true;
}
if (size == 0)
{
break;
}
}
}
}
static void ReadCallback(object state)
{
ListenerConnectionModeReader reader = (ListenerConnectionModeReader)state;
bool completeSelf = false;
Exception completionException = null;
try
{
if (reader.GetReadResult())
{
completeSelf = reader.ContinueReading();
}
}
#pragma warning suppress 56500 // [....], transferring exception to caller
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
completeSelf = true;
completionException = e;
}
if (completeSelf)
{
reader.Complete(completionException);
}
}
bool GetReadResult()
{
offset = 0;
size = Connection.EndRead();
if (size == 0)
{
if (this.decoder.StreamPosition == 0) // client timed out a cached connection
{
base.Close(GetRemainingTimeout());
return false;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException());
}
}
if (buffer == null)
{
buffer = Connection.AsyncReadBuffer;
}
return true;
}
public FramingMode GetConnectionMode()
{
if (readException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(readException);
}
return decoder.Mode;
}
public void StartReading(TimeSpan timeout, Action connectionDequeuedCallback)
{
this.receiveTimeoutHelper = new TimeoutHelper(timeout);
this.decoder = new ServerModeDecoder();
this.ConnectionDequeuedCallback = connectionDequeuedCallback;
bool completeSelf;
try
{
completeSelf = ContinueReading();
}
#pragma warning suppress 56500 // [....], transferring exception to caller
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
// exception will be logged by the caller
this.readException = e;
completeSelf = true;
}
if (completeSelf)
{
Complete();
}
}
public byte[] AccruedData
{
get { return this.accruedData; }
}
}
}
| |
// $Id$
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
using System;
using System.Collections.Generic;
using Org.Apache.Etch.Bindings.Csharp.Msg;
using NUnit.Framework;
using org.apache.etch.tests;
using org.apache.etch.tests.types.Test1;
namespace etch.tests
{
[TestFixture]
public class TestValueFactoryTest1DotCsharp
{
private ValueFactoryTest1 vf = new ValueFactoryTest1("none:");
[TestFixtureSetUp]
public void First()
{
Console.WriteLine();
Console.Write( "TestVF" );
}
[Test]
public void test_E1()
{
// type //
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_E1,
ValueFactoryTest1._mf_A,
ValueFactoryTest1._mf_B,
ValueFactoryTest1._mf_C );
}
[Test]
public void test_E1_export()
{
testEnumExport( E1.A,
ValueFactoryTest1._mt_org_apache_etch_tests_Test1_E1,
ValueFactoryTest1._mf_A );
testEnumExport( E1.B,
ValueFactoryTest1._mt_org_apache_etch_tests_Test1_E1,
ValueFactoryTest1._mf_B );
testEnumExport( E1.C,
ValueFactoryTest1._mt_org_apache_etch_tests_Test1_E1,
ValueFactoryTest1._mf_C );
}
[Test]
public void test_E1_import()
{
testEnumImport( E1.A,
ValueFactoryTest1._mt_org_apache_etch_tests_Test1_E1,
ValueFactoryTest1._mf_A );
testEnumImport( E1.B,
ValueFactoryTest1._mt_org_apache_etch_tests_Test1_E1,
ValueFactoryTest1._mf_B );
testEnumImport( E1.C,
ValueFactoryTest1._mt_org_apache_etch_tests_Test1_E1,
ValueFactoryTest1._mf_C );
}
[Test]
public void test_S1()
{
// type //
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S1,
// fields //
ValueFactoryTest1._mf_x,
ValueFactoryTest1._mf_y,
ValueFactoryTest1._mf_z );
}
[Test]
public void test_S1_export()
{
StructValue sv = vf.ExportCustomValue( new S1( 19, 23, 29 ) );
sv.CheckType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S1 );
Assert.AreEqual( 3, sv.Count );
Assert.AreEqual( 19, sv.Get( ValueFactoryTest1._mf_x ) );
Assert.AreEqual( 23, sv.Get( ValueFactoryTest1._mf_y ) );
Assert.AreEqual( 29, sv.Get( ValueFactoryTest1._mf_z ) );
}
[Test]
public void test_S1_import()
{
StructValue sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S1, vf);
sv.Add( ValueFactoryTest1._mf_x, 101 );
sv.Add( ValueFactoryTest1._mf_y, 103 );
sv.Add( ValueFactoryTest1._mf_z, 107 );
S1 s = ( S1 ) vf.ImportCustomValue( sv );
Assert.AreEqual( 101, s.x );
Assert.AreEqual( 103, s.y );
Assert.AreEqual( 107, s.z );
}
[Test]
public void test_S2()
{
// type //
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S2,
ValueFactoryTest1._mf_a,
ValueFactoryTest1._mf_b,
ValueFactoryTest1._mf_c );
}
[Test]
public void test_S2_export()
{
S1 a = new S1( 21, 22, 23 );
S1 b = new S1( 31, 32, 33 );
E1 c = E1.A;
StructValue sv = vf.ExportCustomValue( new S2( a, b, c ) );
sv.CheckType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S2 );
Assert.AreEqual( 3, sv.Count );
Assert.AreEqual( a, sv.Get( ValueFactoryTest1._mf_a ) );
Assert.AreEqual( b, sv.Get( ValueFactoryTest1._mf_b ) );
Assert.AreEqual( c, sv.Get( ValueFactoryTest1._mf_c ) );
}
[Test]
public void test_S2_import()
{
StructValue sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S2, vf);
sv.Add( ValueFactoryTest1._mf_a, new S1( 21, 22, 23 ) );
sv.Add( ValueFactoryTest1._mf_b, new S1( 31, 32, 33 ) );
sv.Add( ValueFactoryTest1._mf_c, E1.A );
S2 s = ( S2 ) vf.ImportCustomValue( sv );
Assert.AreEqual( 21, s.a.x );
Assert.AreEqual( 22, s.a.y );
Assert.AreEqual( 23, s.a.z );
Assert.AreEqual( 31, s.b.x );
Assert.AreEqual( 32, s.b.y );
Assert.AreEqual( 33, s.b.z );
Assert.AreEqual( E1.A, s.c );
}
[Test]
public void test_S3()
{
// type //
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S3,
// fields //
// ValueFactoryTest1._mf_type1,
ValueFactoryTest1._mf_tipe,
ValueFactoryTest1._mf_x );
}
[Test]
public void test_S3_export()
{
testS3Export("boolean", ConstsTest1.BOOL1);
testS3Export("byte", ConstsTest1.BYTE5);
testS3Export("short", ConstsTest1.SHORT5);
testS3Export("int", ConstsTest1.INT5);
testS3Export("long", ConstsTest1.LONG5);
testS3Export("float", ConstsTest1.FLOAT5);
testS3Export("double", ConstsTest1.DOUBLE5);
testS3Export("string", ConstsTest1.STRING3);
}
[Test]
public void test_S3_import()
{
testS3Import("boolean", ConstsTest1.BOOL1);
testS3Import("byte", ConstsTest1.BYTE5);
testS3Import("short", ConstsTest1.SHORT5);
testS3Import("int", ConstsTest1.INT5);
testS3Import("long", ConstsTest1.LONG5);
testS3Import("float", ConstsTest1.FLOAT5);
testS3Import("double", ConstsTest1.DOUBLE5);
testS3Import("string", ConstsTest1.STRING3);
}
[Test]
public void test_S4()
{
// type //
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S4,
// fields //
ValueFactoryTest1._mf_tipe,
ValueFactoryTest1._mf_x );
}
[Test]
public void test_S4_export()
{
Object[] boolObject = new Object[] {ConstsTest1.BOOL1, ConstsTest1.BOOL2};
Object[] byteObject = new Object[] {ConstsTest1.BYTE1, ConstsTest1.BYTE2, ConstsTest1.BYTE3, ConstsTest1.BYTE4, ConstsTest1.BYTE5};
Object[] shortObject = new Object[] {ConstsTest1.SHORT1, ConstsTest1.SHORT2, ConstsTest1.SHORT3, ConstsTest1.SHORT4, ConstsTest1.SHORT5};
Object[] intObject = new Object[]{ConstsTest1.INT1, ConstsTest1.INT2, ConstsTest1.INT3, ConstsTest1.INT4, ConstsTest1.INT5};
Object[] longObject = new Object[] {ConstsTest1.LONG1, ConstsTest1.LONG2, ConstsTest1.LONG3, ConstsTest1.LONG4, ConstsTest1.LONG5};
Object[] floatObject = new Object[]{ConstsTest1.FLOAT1, ConstsTest1.FLOAT2, ConstsTest1.FLOAT3, ConstsTest1.FLOAT4, ConstsTest1.FLOAT5};
Object[] doubleObject = new Object[] {ConstsTest1.DOUBLE1, ConstsTest1.DOUBLE2, ConstsTest1.DOUBLE3, ConstsTest1.DOUBLE4, ConstsTest1.DOUBLE5};
Object[] stringObject = new Object []{ConstsTest1.STRING1, ConstsTest1.STRING2, ConstsTest1.STRING3, ConstsTest1.STRING4, ConstsTest1.STRING5};
testS4Export("boolean", boolObject);
testS4Export("byte", byteObject);
testS4Export("short", shortObject);
testS4Export("int", intObject);
testS4Export("long", longObject);
testS4Export("float", floatObject);
testS4Export("double", doubleObject);
testS4Export("string", stringObject);
}
[Test]
public void test_S4_import()
{
Object[] boolObject = new Object[] {ConstsTest1.BOOL1, ConstsTest1.BOOL2};
Object[] byteObject = new Object[] {ConstsTest1.BYTE1, ConstsTest1.BYTE2, ConstsTest1.BYTE3, ConstsTest1.BYTE4, ConstsTest1.BYTE5};
Object[] shortObject = new Object[] {ConstsTest1.SHORT1, ConstsTest1.SHORT2, ConstsTest1.SHORT3, ConstsTest1.SHORT4, ConstsTest1.SHORT5};
Object[] intObject = new Object[]{ConstsTest1.INT1, ConstsTest1.INT2, ConstsTest1.INT3, ConstsTest1.INT4, ConstsTest1.INT5};
Object[] longObject = new Object[] {ConstsTest1.LONG1, ConstsTest1.LONG2, ConstsTest1.LONG3, ConstsTest1.LONG4, ConstsTest1.LONG5};
Object[] floatObject = new Object[]{ConstsTest1.FLOAT1, ConstsTest1.FLOAT2, ConstsTest1.FLOAT3, ConstsTest1.FLOAT4, ConstsTest1.FLOAT5};
Object[] doubleObject = new Object[] {ConstsTest1.DOUBLE1, ConstsTest1.DOUBLE2, ConstsTest1.DOUBLE3, ConstsTest1.DOUBLE4, ConstsTest1.DOUBLE5};
Object[] stringObject = new Object []{ConstsTest1.STRING1, ConstsTest1.STRING2, ConstsTest1.STRING3, ConstsTest1.STRING4, ConstsTest1.STRING5};
testS4Import("boolean", boolObject);
testS4Import("byte", byteObject);
testS4Import("short", shortObject);
testS4Import("int", intObject);
testS4Import("long", longObject);
testS4Import("float", floatObject);
testS4Import("double", doubleObject);
testS4Import("string", stringObject);
}
[Test]
public void test_excps()
{
// type //
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp1, ValueFactoryTest1._mf_msg, ValueFactoryTest1._mf_code );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp2 );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp3 );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp4 );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp5, ValueFactoryTest1._mf_msg,ValueFactoryTest1._mf_code, ValueFactoryTest1._mf_x );
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp6, ValueFactoryTest1._mf_msg, ValueFactoryTest1._mf_code, ValueFactoryTest1._mf_x);
// fields //
// checkField( ValueFactoryTest._mf_msg );
// checkField( ValueFactoryTest._mf_code );
// checkField( ValueFactoryTest._mf_x );
}
[Test]
public void test_excps_export()
{
Object[] boolObject = new Object[] { ConstsTest1.BOOL1, ConstsTest1.BOOL2 };
Object[] byteObject = new Object[] { ConstsTest1.BYTE1, ConstsTest1.BYTE2, ConstsTest1.BYTE3, ConstsTest1.BYTE4, ConstsTest1.BYTE5 };
Object[] shortObject = new Object[] { ConstsTest1.SHORT1, ConstsTest1.SHORT2, ConstsTest1.SHORT3, ConstsTest1.SHORT4, ConstsTest1.SHORT5 };
Object[] intObject = new Object[] { ConstsTest1.INT1, ConstsTest1.INT2, ConstsTest1.INT3, ConstsTest1.INT4, ConstsTest1.INT5 };
Object[] longObject = new Object[] { ConstsTest1.LONG1, ConstsTest1.LONG2, ConstsTest1.LONG3, ConstsTest1.LONG4, ConstsTest1.LONG5 };
Object[] floatObject = new Object[] { ConstsTest1.FLOAT1, ConstsTest1.FLOAT2, ConstsTest1.FLOAT3, ConstsTest1.FLOAT4, ConstsTest1.FLOAT5 };
Object[] doubleObject = new Object[] { ConstsTest1.DOUBLE1, ConstsTest1.DOUBLE2, ConstsTest1.DOUBLE3, ConstsTest1.DOUBLE4, ConstsTest1.DOUBLE5 };
Object[] stringObject = new Object[] { ConstsTest1.STRING1, ConstsTest1.STRING2, ConstsTest1.STRING3, ConstsTest1.STRING4, ConstsTest1.STRING5 };
String msg = "Exception";
int code = 500;
StructValue sv = vf.ExportCustomValue( new Excp1( "abc", 23 ) );
sv.CheckType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp1 );
Assert.AreEqual( 2, sv.Count );
Assert.AreEqual( "abc", sv.Get( ValueFactoryTest1._mf_msg ) );
Assert.AreEqual( 23, sv.Get( ValueFactoryTest1._mf_code ) );
sv = vf.ExportCustomValue( new Excp2() );
sv.CheckType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp2 );
Assert.AreEqual( 0, sv.Count );
sv = vf.ExportCustomValue( new Excp3() );
sv.CheckType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp3 );
Assert.AreEqual( 0, sv.Count );
sv = vf.ExportCustomValue( new Excp4() );
sv.CheckType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp4 );
Assert.AreEqual( 0, sv.Count );
// Import exception with object as param
testExcp5Export( msg, code, ConstsTest1.BOOL2 );
testExcp5Export( msg, code, ConstsTest1.BYTE5 );
testExcp5Export( msg, code, ConstsTest1.SHORT5 );
testExcp5Export( msg, code, ConstsTest1.INT5 );
testExcp5Export( msg, code, ConstsTest1.LONG5 );
testExcp5Export( msg, code, ConstsTest1.FLOAT5 );
testExcp5Export( msg, code, ConstsTest1.DOUBLE5 );
testExcp5Export( msg, code, ConstsTest1.STRING3 );
// Import exception with array of object as param
testExcp6Export( msg, code, boolObject );
testExcp6Export( msg, code, byteObject );
testExcp6Export( msg, code, shortObject );
testExcp6Export( msg, code, intObject );
testExcp6Export( msg, code, longObject );
testExcp6Export( msg, code, floatObject );
testExcp6Export( msg, code, doubleObject );
testExcp6Export( msg, code, stringObject );
}
[Test]
public void test_excps_import()
{
Object[] boolObject = new Object[] { ConstsTest1.BOOL1, ConstsTest1.BOOL2 };
Object[] byteObject = new Object[] { ConstsTest1.BYTE1, ConstsTest1.BYTE2, ConstsTest1.BYTE3, ConstsTest1.BYTE4, ConstsTest1.BYTE5 };
Object[] shortObject = new Object[] { ConstsTest1.SHORT1, ConstsTest1.SHORT2, ConstsTest1.SHORT3, ConstsTest1.SHORT4, ConstsTest1.SHORT5 };
Object[] intObject = new Object[] { ConstsTest1.INT1, ConstsTest1.INT2, ConstsTest1.INT3, ConstsTest1.INT4, ConstsTest1.INT5 };
Object[] longObject = new Object[] { ConstsTest1.LONG1, ConstsTest1.LONG2, ConstsTest1.LONG3, ConstsTest1.LONG4, ConstsTest1.LONG5 };
Object[] floatObject = new Object[] { ConstsTest1.FLOAT1, ConstsTest1.FLOAT2, ConstsTest1.FLOAT3, ConstsTest1.FLOAT4, ConstsTest1.FLOAT5 };
Object[] doubleObject = new Object[] { ConstsTest1.DOUBLE1, ConstsTest1.DOUBLE2, ConstsTest1.DOUBLE3, ConstsTest1.DOUBLE4, ConstsTest1.DOUBLE5 };
Object[] stringObject = new Object[] { ConstsTest1.STRING1, ConstsTest1.STRING2, ConstsTest1.STRING3, ConstsTest1.STRING4, ConstsTest1.STRING5 };
String msg = "Exception";
int code = 500;
StructValue sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp1, vf);
sv.Add( ValueFactoryTest1._mf_msg, "def" );
sv.Add( ValueFactoryTest1._mf_code, 29 );
Excp1 e1 = ( Excp1 ) vf.ImportCustomValue( sv );
Assert.AreEqual( "def", e1.msg );
Assert.AreEqual( 29, e1.code );
e1 = null;
sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp2, vf);
Excp2 e2 = ( Excp2 ) vf.ImportCustomValue( sv );
Assert.IsNotNull( e2 );
e2 = null;
sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp3, vf);
Excp3 e3 = ( Excp3 ) vf.ImportCustomValue( sv );
Assert.IsNotNull( e3 );
e3 = null;
sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp4, vf);
Excp4 e4 = ( Excp4 ) vf.ImportCustomValue( sv );
Assert.IsNotNull( e4 );
e4 = null;
// Import exception with object as param
testExcp5Import( msg, code, ConstsTest1.BOOL2 );
testExcp5Import( msg, code, ConstsTest1.BYTE5 );
testExcp5Import( msg, code, ConstsTest1.SHORT5 );
testExcp5Import( msg, code, ConstsTest1.INT5 );
testExcp5Import( msg, code, ConstsTest1.LONG5 );
testExcp5Import( msg, code, ConstsTest1.FLOAT5 );
testExcp5Import( msg, code, ConstsTest1.DOUBLE5 );
testExcp5Import( msg, code, ConstsTest1.STRING3 );
// Import exception with array of object as param
testExcp6Import( msg, code, boolObject );
testExcp6Import( msg, code, byteObject );
testExcp6Import( msg, code, shortObject );
testExcp6Import( msg, code, intObject );
testExcp6Import( msg, code, longObject );
testExcp6Import( msg, code, floatObject );
testExcp6Import( msg, code, doubleObject );
testExcp6Import( msg, code, stringObject );
}
[Test]
public void test_method_nothing()
{
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_nothing, ValueFactoryTest1._mf__messageId);
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_nothing,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_incr()
{
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_incr, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_x);
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_incr, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_sub()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_sub, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_x, ValueFactoryTest1._mf_y );
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_sub, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo, ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_sum()
{
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_sum, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_x);
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_sum, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_trans()
{
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_trans, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_e,
ValueFactoryTest1._mf_x);
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_trans, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_dist()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_dist,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a,
ValueFactoryTest1._mf_b );
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_dist, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_fill()
{
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_fill, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_n, ValueFactoryTest1._mf_x );
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_fill, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_fillObject()
{
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_fillObject, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_n, ValueFactoryTest1._mf_o );
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_fillObject, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_blow()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_blow , ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_msg,
ValueFactoryTest1._mf_code );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_blow, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_beets()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_beets, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_e );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_beets, ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_throwExcp5()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_throwExcp5,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_msg,
ValueFactoryTest1._mf_code,
ValueFactoryTest1._mf_value);
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_throwExcp5,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_throwExcp6()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_throwExcp5,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_msg,
ValueFactoryTest1._mf_code,
ValueFactoryTest1._mf_value);
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_throwExcp6,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_boolean()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_boolean,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a);
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_boolean,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_boolean_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_boolean_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a);
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_boolean_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_byte()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_byte,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a);
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_byte,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_byte_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_byte_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a);
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_byte_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_short()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_short,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a);
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_short,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_short_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_short_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a);
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_short_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_int()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_int,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_int,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_int_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_int_array ,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_int_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_long()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_long,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_long,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_long_array()
{
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_long_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a);
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_long_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_float()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_float,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_float,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_float_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_float_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_float_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_double()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_double,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_double,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_double_array()
{
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_double_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a);
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_double_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_string()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_string,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_string,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_string_array()
{
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_string_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a);
checkType(ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_string_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result);
}
[Test]
public void test_method_p_E1()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_E1,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_E1,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_E1_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_E1_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_E1_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_S1()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_S1,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_S1,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_S1_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_S1_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_S1_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_S2()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_S2,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_S2,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_S2_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_S2_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_S2_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_Blob()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_Blob,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_Blob,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_Blob_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_Blob_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_Blob_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_object()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_object,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_object,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_object_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_object_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_object_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_object_struct()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_object_struct,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_object_struct,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
[Test]
public void test_method_p_object_struct_array()
{
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_p_object_struct_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf_a );
checkType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1__result_p_object_struct_array,
ValueFactoryTest1._mf__messageId,
ValueFactoryTest1._mf__inReplyTo,
ValueFactoryTest1._mf_result );
}
/////////////////////
// UTILITY METHODS //
/////////////////////
private void checkType( XType type, params Field[] fields )
{
Assert.IsNotNull( type );
Assert.AreSame( typeof(XType), type.GetType() );
Assert.AreSame( type, vf.GetType( type.Id ) );
List<Field> tfields = type.GetFields();
if (fields != null)
{
Assert.AreEqual( fields.Length, tfields.Count );
//for (Field f: fields)
for (int i = 0; i < fields.Length;i++ )
{
Assert.IsNotNull(type.GetValidator(fields[i]));
Assert.AreSame(fields[i], type.GetField(fields[i].Id));
Assert.AreSame(fields[i], type.GetField(fields[i].Name));
}
}
else
{
Assert.AreEqual( 0, tfields.Count );
}
}
private void testEnumExport( E1 e, XType t, Field f )
{
StructValue sv = vf.ExportCustomValue( e );
sv.CheckType( t );
Assert.AreEqual( 1, sv.Count );
Assert.IsTrue( (Boolean) sv.Get( f ) );
}
private void testEnumImport( E1 e, XType t, Field f )
{
StructValue sv = new StructValue(t, vf);
sv.Add( f, true );
E1 a = (E1) vf.ImportCustomValue( sv );
Assert.AreEqual( e, a );
}
private void testS3Export( String s, Object value )
{
StructValue sv = vf.ExportCustomValue( new S3( s, value ) );
sv.CheckType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S3 );
Assert.AreEqual( 2, sv.Count );
Assert.AreEqual( s, sv[ ValueFactoryTest1._mf_tipe ] );
Assert.AreEqual( value, sv[ ValueFactoryTest1._mf_x ] );
}
private void testS3Import( String s, Object value )
{
StructValue sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S3, vf);
sv.Add(ValueFactoryTest1._mf_tipe, s);
sv.Add( ValueFactoryTest1._mf_x, value );
S3 myS3 = ( S3 ) vf.ImportCustomValue( sv );
Assert.AreEqual( s, myS3.tipe );
Assert.AreEqual( value, myS3.x );
}
private void testS4Export( String s, Object[] value )
{
StructValue sv = vf.ExportCustomValue( new S4( s, value ) );
sv.CheckType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S4 );
Assert.AreEqual( 2, sv.Count );
Assert.AreEqual(s, sv[ValueFactoryTest1._mf_tipe]);
Assert.AreEqual( value, sv[ ValueFactoryTest1._mf_x ] );
}
private void testS4Import( String s, Object[] value )
{
StructValue sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_S4, vf);
sv.Add(ValueFactoryTest1._mf_tipe, s);
sv.Add( ValueFactoryTest1._mf_x, value );
S4 myS4 = ( S4 ) vf.ImportCustomValue( sv );
Assert.AreEqual( s, myS4.tipe );
Assert.AreEqual( value, myS4.x );
}
private void testExcp5Export( String msg, int code, Object value )
{
StructValue sv = vf.ExportCustomValue( new Excp5( msg, code, value ) );
sv.CheckType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp5 );
Assert.AreEqual( 3, sv.Count );
Assert.AreEqual( msg, sv[ValueFactoryTest1._mf_msg] );
Assert.AreEqual( code, sv[ ValueFactoryTest1._mf_code] );
Assert.AreEqual( value, sv[ ValueFactoryTest1._mf_x ] );
}
private void testExcp5Import( String msg, int code, Object value )
{
StructValue sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp5, vf);
sv.Add( ValueFactoryTest1._mf_msg, msg );
sv.Add( ValueFactoryTest1._mf_code, code );
sv.Add( ValueFactoryTest1._mf_x, value );
Excp5 e = ( Excp5 ) vf.ImportCustomValue( sv );
Assert.AreEqual( msg, e.msg );
Assert.AreEqual( code, e.code );
Assert.AreEqual( value, e.x );
}
private void testExcp6Export( String msg, int code, Object[] value )
{
StructValue sv = vf.ExportCustomValue( new Excp6( msg, code, value ) );
sv.CheckType( ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp6 );
Assert.AreEqual( 3, sv.Count );
Assert.AreEqual( msg, sv[ ValueFactoryTest1._mf_msg ] );
Assert.AreEqual( code, sv[ ValueFactoryTest1._mf_code] );
Assert.AreEqual( value, sv[ ValueFactoryTest1._mf_x ] );
}
private void testExcp6Import( String msg, int code, Object[] value )
{
StructValue sv = new StructValue(ValueFactoryTest1._mt_org_apache_etch_tests_Test1_Excp6, vf);
sv.Add( ValueFactoryTest1._mf_msg, msg );
sv.Add( ValueFactoryTest1._mf_code, code );
sv.Add( ValueFactoryTest1._mf_x, value );
Excp6 e = ( Excp6 ) vf.ImportCustomValue( sv );
Assert.AreEqual( msg, e.msg );
Assert.AreEqual( code, e.code );
Assert.AreEqual( value, e.x );
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Automation.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Automation;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Software update configuration machine run model.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class SoftwareUpdateConfigurationMachineRun
{
/// <summary>
/// Initializes a new instance of the
/// SoftwareUpdateConfigurationMachineRun class.
/// </summary>
public SoftwareUpdateConfigurationMachineRun()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// SoftwareUpdateConfigurationMachineRun class.
/// </summary>
/// <param name="name">Name of the software update configuration
/// machine run</param>
/// <param name="id">Resource Id of the software update configuration
/// machine run</param>
/// <param name="targetComputer">name of the updated computer</param>
/// <param name="targetComputerType">type of the updated
/// computer.</param>
/// <param name="softwareUpdateConfiguration">software update
/// configuration triggered this run</param>
/// <param name="status">Status of the software update configuration
/// machine run.</param>
/// <param name="osType">Operating system target of the software update
/// configuration triggered this run</param>
/// <param name="correlationId">correlation id of the software update
/// configuration machine run</param>
/// <param name="sourceComputerId">source computer id of the software
/// update configuration machine run</param>
/// <param name="startTime">Start time of the software update
/// configuration machine run.</param>
/// <param name="endTime">End time of the software update configuration
/// machine run.</param>
/// <param name="configuredDuration">configured duration for the
/// software update configuration run.</param>
/// <param name="job">Job associated with the software update
/// configuration machine run</param>
/// <param name="creationTime">Creation time of theresource, which only
/// appears in the response.</param>
/// <param name="createdBy">createdBy property, which only appears in
/// the response.</param>
/// <param name="lastModifiedTime">Last time resource was modified,
/// which only appears in the response.</param>
/// <param name="lastModifiedBy">lastModifiedBy property, which only
/// appears in the response.</param>
public SoftwareUpdateConfigurationMachineRun(string name = default(string), string id = default(string), string targetComputer = default(string), string targetComputerType = default(string), UpdateConfigurationNavigation softwareUpdateConfiguration = default(UpdateConfigurationNavigation), string status = default(string), string osType = default(string), System.Guid? correlationId = default(System.Guid?), System.Guid? sourceComputerId = default(System.Guid?), System.DateTime? startTime = default(System.DateTime?), System.DateTime? endTime = default(System.DateTime?), string configuredDuration = default(string), JobNavigation job = default(JobNavigation), System.DateTime? creationTime = default(System.DateTime?), string createdBy = default(string), System.DateTime? lastModifiedTime = default(System.DateTime?), string lastModifiedBy = default(string))
{
Name = name;
Id = id;
TargetComputer = targetComputer;
TargetComputerType = targetComputerType;
SoftwareUpdateConfiguration = softwareUpdateConfiguration;
Status = status;
OsType = osType;
CorrelationId = correlationId;
SourceComputerId = sourceComputerId;
StartTime = startTime;
EndTime = endTime;
ConfiguredDuration = configuredDuration;
Job = job;
CreationTime = creationTime;
CreatedBy = createdBy;
LastModifiedTime = lastModifiedTime;
LastModifiedBy = lastModifiedBy;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets name of the software update configuration machine run
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; private set; }
/// <summary>
/// Gets resource Id of the software update configuration machine run
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; private set; }
/// <summary>
/// Gets name of the updated computer
/// </summary>
[JsonProperty(PropertyName = "properties.targetComputer")]
public string TargetComputer { get; private set; }
/// <summary>
/// Gets type of the updated computer.
/// </summary>
[JsonProperty(PropertyName = "properties.targetComputerType")]
public string TargetComputerType { get; private set; }
/// <summary>
/// Gets or sets software update configuration triggered this run
/// </summary>
[JsonProperty(PropertyName = "properties.softwareUpdateConfiguration")]
public UpdateConfigurationNavigation SoftwareUpdateConfiguration { get; set; }
/// <summary>
/// Gets status of the software update configuration machine run.
/// </summary>
[JsonProperty(PropertyName = "properties.status")]
public string Status { get; private set; }
/// <summary>
/// Gets operating system target of the software update configuration
/// triggered this run
/// </summary>
[JsonProperty(PropertyName = "properties.osType")]
public string OsType { get; private set; }
/// <summary>
/// Gets correlation id of the software update configuration machine
/// run
/// </summary>
[JsonProperty(PropertyName = "properties.correlationId")]
public System.Guid? CorrelationId { get; private set; }
/// <summary>
/// Gets source computer id of the software update configuration
/// machine run
/// </summary>
[JsonProperty(PropertyName = "properties.sourceComputerId")]
public System.Guid? SourceComputerId { get; private set; }
/// <summary>
/// Gets start time of the software update configuration machine run.
/// </summary>
[JsonProperty(PropertyName = "properties.startTime")]
public System.DateTime? StartTime { get; private set; }
/// <summary>
/// Gets end time of the software update configuration machine run.
/// </summary>
[JsonProperty(PropertyName = "properties.endTime")]
public System.DateTime? EndTime { get; private set; }
/// <summary>
/// Gets configured duration for the software update configuration run.
/// </summary>
[JsonProperty(PropertyName = "properties.configuredDuration")]
public string ConfiguredDuration { get; private set; }
/// <summary>
/// Gets or sets job associated with the software update configuration
/// machine run
/// </summary>
[JsonProperty(PropertyName = "properties.job")]
public JobNavigation Job { get; set; }
/// <summary>
/// Gets creation time of theresource, which only appears in the
/// response.
/// </summary>
[JsonProperty(PropertyName = "properties.creationTime")]
public System.DateTime? CreationTime { get; private set; }
/// <summary>
/// Gets createdBy property, which only appears in the response.
/// </summary>
[JsonProperty(PropertyName = "properties.createdBy")]
public string CreatedBy { get; private set; }
/// <summary>
/// Gets last time resource was modified, which only appears in the
/// response.
/// </summary>
[JsonProperty(PropertyName = "properties.lastModifiedTime")]
public System.DateTime? LastModifiedTime { get; private set; }
/// <summary>
/// Gets lastModifiedBy property, which only appears in the response.
/// </summary>
[JsonProperty(PropertyName = "properties.lastModifiedBy")]
public string LastModifiedBy { get; private set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Security;
using System.Security.Principal;
using System.Threading;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using Microsoft.Win32.SafeHandles;
namespace System.Net.Security
{
//
// The class maintains the state of the authentication process and the security context.
// It encapsulates security context and does the real work in authentication and
// user data encryption with NEGO SSPI package.
//
internal static partial class NegotiateStreamPal
{
// value should match the Windows sspicli NTE_FAIL value
// defined in winerror.h
private const int NTE_FAIL = unchecked((int)0x80090020);
internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext)
{
throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
}
internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext)
{
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
return negoContext.IsNtlmUsed ? NegotiationInfoClass.NTLM : NegotiationInfoClass.Kerberos;
}
static byte[] GssWrap(
SafeGssContextHandle context,
bool encrypt,
byte[] buffer,
int offset,
int count)
{
Debug.Assert((buffer != null) && (buffer.Length > 0), "Invalid input buffer passed to Encrypt");
Debug.Assert((offset >= 0) && (offset < buffer.Length), "Invalid input offset passed to Encrypt");
Debug.Assert((count >= 0) && (count <= (buffer.Length - offset)), "Invalid input count passed to Encrypt");
Interop.NetSecurityNative.GssBuffer encryptedBuffer = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status minorStatus;
Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.WrapBuffer(out minorStatus, context, encrypt, buffer, offset, count, ref encryptedBuffer);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return encryptedBuffer.ToByteArray();
}
finally
{
encryptedBuffer.Dispose();
}
}
private static int GssUnwrap(
SafeGssContextHandle context,
byte[] buffer,
int offset,
int count)
{
Debug.Assert((buffer != null) && (buffer.Length > 0), "Invalid input buffer passed to Decrypt");
Debug.Assert((offset >= 0) && (offset <= buffer.Length), "Invalid input offset passed to Decrypt");
Debug.Assert((count >= 0) && (count <= (buffer.Length - offset)), "Invalid input count passed to Decrypt");
Interop.NetSecurityNative.GssBuffer decryptedBuffer = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status minorStatus;
Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.UnwrapBuffer(out minorStatus, context, buffer, offset, count, ref decryptedBuffer);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return decryptedBuffer.Copy(buffer, offset);
}
finally
{
decryptedBuffer.Dispose();
}
}
private static bool GssInitSecurityContext(
ref SafeGssContextHandle context,
SafeGssCredHandle credential,
bool isNtlm,
ChannelBinding channelBinding,
bool isNtlmFallback,
SafeGssNameHandle targetNameKerberos,
SafeGssNameHandle targetNameNtlm,
Interop.NetSecurityNative.GssFlags inFlags,
byte[] buffer,
out byte[] outputBuffer,
out uint outFlags,
out bool isNtlmUsed)
{
// If a TLS channel binding token (cbt) is available then get the pointer
// to the application specific data.
IntPtr cbtAppData = IntPtr.Zero;
int cbtAppDataSize = 0;
if (channelBinding != null)
{
int appDataOffset = Marshal.SizeOf<SecChannelBindings>();
Debug.Assert(appDataOffset < channelBinding.Size);
cbtAppData = channelBinding.DangerousGetHandle() + appDataOffset;
cbtAppDataSize = channelBinding.Size - appDataOffset;
}
outputBuffer = null;
outFlags = 0;
// EstablishSecurityContext is called multiple times in a session.
// In each call, we need to pass the context handle from the previous call.
// For the first call, the context handle will be null.
if (context == null)
{
context = new SafeGssContextHandle();
}
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
Interop.NetSecurityNative.Status status;
try
{
Interop.NetSecurityNative.Status minorStatus;
status = Interop.NetSecurityNative.InitSecContext(out minorStatus,
credential,
ref context,
isNtlm,
cbtAppData,
cbtAppDataSize,
isNtlmFallback,
targetNameKerberos,
targetNameNtlm,
(uint)inFlags,
buffer,
(buffer == null) ? 0 : buffer.Length,
ref token,
out outFlags,
out isNtlmUsed);
if ((status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) &&
(status != Interop.NetSecurityNative.Status.GSS_S_CONTINUE_NEEDED))
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
outputBuffer = token.ToByteArray();
}
finally
{
token.Dispose();
}
return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE;
}
private static SecurityStatusPal EstablishSecurityContext(
SafeFreeNegoCredentials credential,
ref SafeDeleteContext context,
ChannelBinding channelBinding,
string targetName,
ContextFlagsPal inFlags,
byte[] incomingBlob,
ref byte[] resultBuffer,
ref ContextFlagsPal outFlags)
{
bool isNtlmOnly = credential.IsNtlmOnly;
bool initialContext = false;
if (context == null)
{
if (NetEventSource.IsEnabled)
{
string protocol = isNtlmOnly ? "NTLM" : "SPNEGO";
NetEventSource.Info(null, $"requested protocol = {protocol}, target = {targetName}");
}
initialContext = true;
context = new SafeDeleteNegoContext(credential, targetName);
}
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)context;
try
{
Interop.NetSecurityNative.GssFlags inputFlags =
ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(inFlags, isServer: false);
uint outputFlags;
bool isNtlmUsed;
SafeGssContextHandle contextHandle = negoContext.GssContext;
bool done = GssInitSecurityContext(
ref contextHandle,
credential.GssCredential,
isNtlmOnly,
channelBinding,
negoContext.IsNtlmFallback,
negoContext.TargetNameKerberos,
negoContext.TargetNameNtlm,
inputFlags,
incomingBlob,
out resultBuffer,
out outputFlags,
out isNtlmUsed);
if (initialContext)
{
if (NetEventSource.IsEnabled)
{
string protocol = isNtlmOnly ? "NTLM" : isNtlmUsed ? "SPNEGO-NTLM" : "SPNEGO-Kerberos";
NetEventSource.Info(null, $"actual protocol = {protocol}");
}
// Remember if SPNEGO did a fallback from Kerberos to NTLM while generating the initial context.
if (!isNtlmOnly && isNtlmUsed)
{
negoContext.IsNtlmFallback = true;
}
// Populate protocol used for authentication
negoContext.SetAuthenticationPackage(isNtlmUsed);
}
Debug.Assert(resultBuffer != null, "Unexpected null buffer returned by GssApi");
outFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop(
(Interop.NetSecurityNative.GssFlags)outputFlags, isServer: false);
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
// Save the inner context handle for further calls to NetSecurity
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
if (null == negoContext.GssContext)
{
negoContext.SetGssContext(contextHandle);
}
SecurityStatusPalErrorCode errorCode = done ?
(negoContext.IsNtlmUsed && resultBuffer.Length > 0 ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.CompleteNeeded) :
SecurityStatusPalErrorCode.ContinueNeeded;
return new SecurityStatusPal(errorCode);
}
catch (Exception ex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex);
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
internal static SecurityStatusPal InitializeSecurityContext(
ref SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext securityContext,
string spn,
ContextFlagsPal requestedContextFlags,
byte[] incomingBlob,
ChannelBinding channelBinding,
ref byte[] resultBlob,
ref ContextFlagsPal contextFlags)
{
SafeFreeNegoCredentials negoCredentialsHandle = (SafeFreeNegoCredentials)credentialsHandle;
if (negoCredentialsHandle.IsDefault && string.IsNullOrEmpty(spn))
{
throw new PlatformNotSupportedException(SR.net_nego_not_supported_empty_target_with_defaultcreds);
}
SecurityStatusPal status = EstablishSecurityContext(
negoCredentialsHandle,
ref securityContext,
channelBinding,
spn,
requestedContextFlags,
incomingBlob,
ref resultBlob,
ref contextFlags);
// Confidentiality flag should not be set if not requested
if (status.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded)
{
ContextFlagsPal mask = ContextFlagsPal.Confidentiality;
if ((requestedContextFlags & mask) != (contextFlags & mask))
{
throw new PlatformNotSupportedException(SR.net_nego_protection_level_not_supported);
}
}
return status;
}
internal static SecurityStatusPal AcceptSecurityContext(
SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext securityContext,
ContextFlagsPal requestedContextFlags,
byte[] incomingBlob,
ChannelBinding channelBinding,
ref byte[] resultBlob,
ref ContextFlagsPal contextFlags)
{
throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
}
internal static Win32Exception CreateExceptionFromError(SecurityStatusPal statusCode)
{
return new Win32Exception(NTE_FAIL, (statusCode.Exception != null) ? statusCode.Exception.Message : statusCode.ErrorCode.ToString());
}
internal static int QueryMaxTokenSize(string package)
{
// This value is not used on Unix
return 0;
}
internal static SafeFreeCredentials AcquireDefaultCredential(string package, bool isServer)
{
return AcquireCredentialsHandle(package, isServer, new NetworkCredential(string.Empty, string.Empty, string.Empty));
}
internal static SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential)
{
if (isServer)
{
throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
}
bool isEmptyCredential = string.IsNullOrWhiteSpace(credential.UserName) ||
string.IsNullOrWhiteSpace(credential.Password);
bool ntlmOnly = string.Equals(package, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase);
if (ntlmOnly && isEmptyCredential)
{
// NTLM authentication is not possible with default credentials which are no-op
throw new PlatformNotSupportedException(SR.net_ntlm_not_possible_default_cred);
}
try
{
return isEmptyCredential ?
new SafeFreeNegoCredentials(false, string.Empty, string.Empty, string.Empty) :
new SafeFreeNegoCredentials(ntlmOnly, credential.UserName, credential.Password, credential.Domain);
}
catch(Exception ex)
{
throw new Win32Exception(NTE_FAIL, ex.Message);
}
}
internal static SecurityStatusPal CompleteAuthToken(
ref SafeDeleteContext securityContext,
byte[] incomingBlob)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
internal static int Encrypt(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
ref byte[] output,
uint sequenceNumber)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext) securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, isConfidential, buffer, offset, count);
// Create space for prefixing with the length
const int prefixLength = 4;
output = new byte[tempOutput.Length + prefixLength];
Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length);
int resultSize = tempOutput.Length;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
internal static int Decrypt(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
out int newOffset,
uint sequenceNumber)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
NetEventSource.Fail(securityContext, "Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
NetEventSource.Fail(securityContext, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
newOffset = offset;
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer, offset, count);
}
internal static int VerifySignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
NetEventSource.Fail(securityContext, "Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
NetEventSource.Fail(securityContext, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer, offset, count);
}
internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext)securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, false, buffer, offset, count);
// Create space for prefixing with the length
const int prefixLength = 4;
output = new byte[tempOutput.Length + prefixLength];
Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length);
int resultSize = tempOutput.Length;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pokemon_delta_emerald
{
public class Pokemon
{
//information about the pokemon
public int pokemonID;
public int xp;
public int level;
public int currentHP;
public string nature = "Serious";
public string[] moves = new string[4];
int[] evs = new int[6];
double[] natureMultiplier = new double[6] { 1, 1, 1, 1, 1, 1 }; //still need to add this to stat calculation
public int[] stats = new int[6];
Random rand = new Random();
//write to text files
System.IO.StreamWriter file;
System.IO.StreamReader read;
string address = "";
string filename = "";
DateTime nowDateTime;
//create wild / trainer's Pokemon
public Pokemon(int num, int exp, bool trainer, bool wild)
{
//only trained Pokemon have EVs
if (wild == false)
{
if (trainer == true)
{
randomEV();
}
randomNature();
}
pokemonID = num;
xp = exp;
level = Convert.ToInt32(Math.Ceiling(Math.Pow(xp, (1.00 / 3.00))));
getMoves();
calculateStats();
currentHP = stats[0];
}
//create the player's Pokemon
public Pokemon(string handler)
{
filename = handler;
}
//generate random EVs for the enemy trainer's Pokemon
private void randomEV()
{
int i = 0;
int maxEV = Convert.ToInt32(Math.Ceiling(Math.Pow(xp, (1.00 / 3.00))) * 2.5);
int currentEV = 0;
while (currentEV < maxEV)
{
evs[i] += rand.Next(maxEV / 2);
if (evs[i] > maxEV - currentEV)
{
evs[i] = maxEV - currentEV;
}
currentEV += evs[i];
i++;
if (i > 5)
{
i = 0;
}
}
}
//generate the Pokemon's nature
private void randomNature()
{
int num = rand.Next(25);
if (num == 0)
{
nature = "Hardy";
}
else if (num == 1)
{
nature = "Lonely";
}
else if (num == 2)
{
nature = "Brave";
}
else if (num == 3)
{
nature = "Adamant";
}
else if (num == 4)
{
nature = "Naughty";
}
else if (num == 5)
{
nature = "Bold";
}
else if (num == 6)
{
nature = "Docile";
}
else if (num == 7)
{
nature = "Relaxed";
}
else if (num == 8)
{
nature = "Impish";
}
else if (num == 9)
{
nature = "Lax";
}
else if (num == 10)
{
nature = "Timid";
}
else if (num == 11)
{
nature = "Hasty";
}
else if (num == 12)
{
nature = "Serious";
}
else if (num == 13)
{
nature = "Jolly";
}
else if (num == 14)
{
nature = "Naive";
}
else if (num == 15)
{
nature = "Modest";
}
else if (num == 16)
{
nature = "Mild";
}
else if (num == 17)
{
nature = "Quiet";
}
else if (num == 18)
{
nature = "Bashful";
}
else if (num == 19)
{
nature = "Rash";
}
else if (num == 20)
{
nature = "Calm";
}
else if (num == 21)
{
nature = "Gentle";
}
else if (num == 22)
{
nature = "Sassy";
}
else if (num == 23)
{
nature = "Careful";
}
else if (num == 24)
{
nature = "Quirky";
}
}
//generate the Pokemon's moves
private void getMoves()
{
int i = 0; //count the moves
int j = 0; //count the slot the move goes in
while (i < 20 && Global.pkmnMovesLvl[pokemonID, i] != 0 && Global.pkmnMovesLvl[pokemonID, i] <= level)
{
moves[j] = Global.pokemonMoves[pokemonID, i];
if (j == 4)
{
j = 0;
}
j++;
i++;
}
}
//returns the slot of a random move
public int randomMove()
{
string move = null;
int value = 0;
while (move == null)
{
value = rand.Next(4);
move = moves[value];
}
return value;
}
//generates the pokemon's stats
private void calculateStats()
{
//HP
stats[0] = 10 + Convert.ToInt32(((2 * Global.hp[pokemonID]) + (evs[0] / 4) + 100) * level / 100.00);
//Attack
stats[1] = 5 + Convert.ToInt32((2 * Global.attack[pokemonID] + (evs[1] / 4)) / 100.00 * level);
//Defense
stats[2] = 5 + Convert.ToInt32((2 * Global.attack[pokemonID] + (evs[1] / 4)) / 100.00 * level);
//Sp. Attack
stats[3] = 5 + Convert.ToInt32((2 * Global.attack[pokemonID] + (evs[1] / 4)) / 100.00 * level);
//Sp. Defense
stats[4] = 5 + Convert.ToInt32((2 * Global.attack[pokemonID] + (evs[1] / 4)) / 100.00 * level);
//Speed
stats[5] = 5 + Convert.ToInt32((2 * Global.attack[pokemonID] + (evs[1] / 4)) / 100.00 * level);
}
//save pokemon to a text file
public string savePokemon()
{
//check if the pokemon has been saved before
if (filename == null)
{
//create the filename
nowDateTime = DateTime.Now;
filename = nowDateTime.Year.ToString();
filename += nowDateTime.Month.ToString();
filename += nowDateTime.Day.ToString();
filename += nowDateTime.Hour.ToString();
filename += nowDateTime.Minute.ToString();
filename += nowDateTime.Second.ToString();
}
//prepare text writing variables
address = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
file = new System.IO.StreamWriter(address + filename + ".txt");
file.WriteLine(pokemonID);
file.WriteLine(nature);
for (int i = 0; i < evs.Length; i++)
{
file.WriteLine(evs[i]);
}
for (int i = 0; i < moves.Length; i++)
{
file.WriteLine(moves[i]);
}
file.Close();
return filename;
}
}
}
| |
using System;
using System.Collections;
using Server;
using Server.Network;
using Server.Targeting;
using System.Collections.Generic;
namespace Server.Items
{
public class CrystalRechargeInfo
{
public static readonly CrystalRechargeInfo[] Table = new CrystalRechargeInfo[]
{
new CrystalRechargeInfo( typeof( Citrine ), 500 ),
new CrystalRechargeInfo( typeof( Amber ), 500 ),
new CrystalRechargeInfo( typeof( Tourmaline ), 750 ),
new CrystalRechargeInfo( typeof( Emerald ), 1000 ),
new CrystalRechargeInfo( typeof( Sapphire ), 1000 ),
new CrystalRechargeInfo( typeof( Amethyst ), 1000 ),
new CrystalRechargeInfo( typeof( StarSapphire ), 1250 ),
new CrystalRechargeInfo( typeof( Diamond ), 2000 )
};
public static CrystalRechargeInfo Get( Type type )
{
foreach ( CrystalRechargeInfo info in Table )
{
if ( info.Type == type )
return info;
}
return null;
}
private Type m_Type;
private int m_Amount;
public Type Type{ get{ return m_Type; } }
public int Amount{ get{ return m_Amount; } }
private CrystalRechargeInfo( Type type, int amount )
{
m_Type = type;
m_Amount = amount;
}
}
public class BroadcastCrystal : Item
{
public static readonly int MaxCharges = 2000;
public override int LabelNumber{ get{ return 1060740; } } // communication crystal
private int m_Charges;
private List<ReceiverCrystal> m_Receivers;
[CommandProperty( AccessLevel.GameMaster )]
public bool Active
{
get{ return this.ItemID == 0x1ECD; }
set
{
this.ItemID = value ? 0x1ECD : 0x1ED0;
InvalidateProperties();
}
}
[CommandProperty( AccessLevel.GameMaster )]
public int Charges
{
get{ return m_Charges; }
set
{
m_Charges = value;
InvalidateProperties();
}
}
public List<ReceiverCrystal> Receivers
{
get{ return m_Receivers; }
}
[Constructable]
public BroadcastCrystal() : this( 2000 )
{
}
[Constructable]
public BroadcastCrystal( int charges ) : base( 0x1ED0 )
{
Light = LightType.Circle150;
m_Charges = charges;
m_Receivers = new List<ReceiverCrystal>();
}
public BroadcastCrystal( Serial serial ) : base( serial )
{
}
public override void GetProperties( ObjectPropertyList list )
{
base.GetProperties( list );
list.Add( this.Active ? 1060742 : 1060743 ); // active / inactive
list.Add( 1060745 ); // broadcast
list.Add( 1060741, this.Charges.ToString() ); // charges: ~1_val~
if ( Receivers.Count > 0 )
list.Add( 1060746, Receivers.Count.ToString() ); // links: ~1_val~
}
public override void OnSingleClick(Mobile from)
{
base.OnSingleClick( from );
LabelTo( from, this.Active ? 1060742 : 1060743 ); // active / inactive
LabelTo( from, 1060745 ); // broadcast
LabelTo( from, 1060741, this.Charges.ToString() ); // charges: ~1_val~
if ( Receivers.Count > 0 )
LabelTo( from, 1060746, Receivers.Count.ToString() ); // links: ~1_val~
}
public override bool HandlesOnSpeech
{
get{ return Active && Receivers.Count > 0 && ( RootParent == null || RootParent is Mobile ); }
}
public override void OnSpeech( SpeechEventArgs e )
{
if ( !Active || Receivers.Count == 0 || ( RootParent != null && !(RootParent is Mobile) ) )
return;
if ( e.Type == MessageType.Emote )
return;
Mobile from = e.Mobile;
string speech = e.Speech;
foreach ( ReceiverCrystal receiver in new List<ReceiverCrystal>( Receivers ) )
{
if ( receiver.Deleted )
{
Receivers.Remove( receiver );
}
else if ( Charges > 0 )
{
receiver.TransmitMessage( from, speech );
Charges--;
}
else
{
this.Active = false;
break;
}
}
}
public override void OnDoubleClick( Mobile from )
{
if ( !from.InRange( GetWorldLocation(), 2 ) )
{
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that.
return;
}
from.Target = new InternalTarget( this );
}
private class InternalTarget : Target
{
private BroadcastCrystal m_Crystal;
public InternalTarget( BroadcastCrystal crystal ) : base( 2, false, TargetFlags.None )
{
m_Crystal = crystal;
}
protected override void OnTarget( Mobile from, object targeted )
{
if ( !m_Crystal.IsAccessibleTo( from ) )
return;
if ( from.Map != m_Crystal.Map || !from.InRange( m_Crystal.GetWorldLocation(), 2 ) )
{
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that.
return;
}
if ( targeted == m_Crystal )
{
if ( m_Crystal.Active )
{
m_Crystal.Active = false;
from.SendLocalizedMessage( 500672 ); // You turn the crystal off.
}
else
{
if ( m_Crystal.Charges > 0 )
{
m_Crystal.Active = true;
from.SendLocalizedMessage( 500673 ); // You turn the crystal on.
}
else
{
from.SendLocalizedMessage( 500676 ); // This crystal is out of charges.
}
}
}
else if ( targeted is ReceiverCrystal )
{
ReceiverCrystal receiver = (ReceiverCrystal) targeted;
if ( m_Crystal.Receivers.Count >= 10 )
{
from.SendLocalizedMessage( 1010042 ); // This broadcast crystal is already linked to 10 receivers.
}
else if ( receiver.Sender == m_Crystal )
{
from.SendLocalizedMessage( 500674 ); // This crystal is already linked with that crystal.
}
else if ( receiver.Sender != null )
{
from.SendLocalizedMessage( 1010043 ); // That receiver crystal is already linked to another broadcast crystal.
}
else
{
receiver.Sender = m_Crystal;
from.SendLocalizedMessage( 500675 ); // That crystal has been linked to this crystal.
}
}
else if ( targeted == from )
{
foreach( ReceiverCrystal receiver in new List<ReceiverCrystal>( m_Crystal.Receivers ) )
{
receiver.Sender = null;
}
from.SendLocalizedMessage( 1010046 ); // You unlink the broadcast crystal from all of its receivers.
}
else
{
Item targItem = targeted as Item;
if ( targItem != null && targItem.VerifyMove( from ) )
{
CrystalRechargeInfo info = CrystalRechargeInfo.Get( targItem.GetType() );
if ( info != null )
{
if ( m_Crystal.Charges >= MaxCharges )
{
from.SendLocalizedMessage( 500678 ); // This crystal is already fully charged.
}
else
{
targItem.Consume();
if ( m_Crystal.Charges + info.Amount >= MaxCharges )
{
m_Crystal.Charges = MaxCharges;
from.SendLocalizedMessage( 500679 ); // You completely recharge the crystal.
}
else
{
m_Crystal.Charges += info.Amount;
from.SendLocalizedMessage( 500680 ); // You recharge the crystal.
}
}
return;
}
}
from.SendLocalizedMessage( 500681 ); // You cannot use this crystal on that.
}
}
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
writer.WriteEncodedInt( m_Charges );
writer.WriteItemList<ReceiverCrystal>( m_Receivers );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
m_Charges = reader.ReadEncodedInt();
m_Receivers = reader.ReadStrongItemList<ReceiverCrystal>();
}
}
public class ReceiverCrystal : Item
{
public override int LabelNumber{ get{ return 1060740; } } // communication crystal
private BroadcastCrystal m_Sender;
[CommandProperty( AccessLevel.GameMaster )]
public bool Active
{
get{ return this.ItemID == 0x1ED1; }
set
{
this.ItemID = value ? 0x1ED1 : 0x1ED0;
InvalidateProperties();
}
}
[CommandProperty( AccessLevel.GameMaster )]
public BroadcastCrystal Sender
{
get{ return m_Sender; }
set
{
if ( m_Sender != null )
{
m_Sender.Receivers.Remove( this );
m_Sender.InvalidateProperties();
}
m_Sender = value;
if ( value != null )
{
value.Receivers.Add( this );
value.InvalidateProperties();
}
}
}
[Constructable]
public ReceiverCrystal() : base( 0x1ED0 )
{
Light = LightType.Circle150;
}
public ReceiverCrystal( Serial serial ) : base( serial )
{
}
public override void GetProperties( ObjectPropertyList list )
{
base.GetProperties( list );
list.Add( this.Active ? 1060742 : 1060743 ); // active / inactive
list.Add( 1060744 ); // receiver
}
public override void OnSingleClick( Mobile from )
{
base.OnSingleClick( from );
LabelTo( from, this.Active ? 1060742 : 1060743 ); // active / inactive
LabelTo( from, 1060744 ); // receiver
}
public void TransmitMessage( Mobile from, string message )
{
if ( !this.Active )
return;
string text = String.Format( "{0} says {1}", from.Name, message );
if ( this.RootParent is Mobile )
{
((Mobile)this.RootParent).SendMessage( 0x2B2, "Crystal: " + text );
}
else if ( this.RootParent is Item )
{
((Item)this.RootParent).PublicOverheadMessage( MessageType.Regular, 0x2B2, false, "Crystal: " + text );
}
else
{
PublicOverheadMessage( MessageType.Regular, 0x2B2, false, text );
}
}
public override void OnDoubleClick( Mobile from )
{
if ( !from.InRange( GetWorldLocation(), 2 ) )
{
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that.
return;
}
from.Target = new InternalTarget( this );
}
private class InternalTarget : Target
{
private ReceiverCrystal m_Crystal;
public InternalTarget( ReceiverCrystal crystal ) : base( -1, false, TargetFlags.None )
{
m_Crystal = crystal;
}
protected override void OnTarget( Mobile from, object targeted )
{
if ( !m_Crystal.IsAccessibleTo( from ) )
return;
if ( from.Map != m_Crystal.Map || !from.InRange( m_Crystal.GetWorldLocation(), 2 ) )
{
from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that.
return;
}
if ( targeted == m_Crystal )
{
if ( m_Crystal.Active )
{
m_Crystal.Active = false;
from.SendLocalizedMessage( 500672 ); // You turn the crystal off.
}
else
{
m_Crystal.Active = true;
from.SendLocalizedMessage( 500673 ); // You turn the crystal on.
}
}
else if ( targeted == from )
{
if ( m_Crystal.Sender != null )
{
m_Crystal.Sender = null;
from.SendLocalizedMessage( 1010044 ); // You unlink the receiver crystal.
}
else
{
from.SendLocalizedMessage( 1010045 ); // That receiver crystal is not linked.
}
}
else
{
Item targItem = targeted as Item;
if ( targItem != null && targItem.VerifyMove( from ) )
{
CrystalRechargeInfo info = CrystalRechargeInfo.Get( targItem.GetType() );
if ( info != null )
{
from.SendLocalizedMessage( 500677 ); // This crystal cannot be recharged.
return;
}
}
from.SendLocalizedMessage( 1010045 ); // That receiver crystal is not linked.
}
}
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
writer.WriteItem<BroadcastCrystal>( m_Sender );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
m_Sender = reader.ReadItem<BroadcastCrystal>();
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
<<<<<<< HEAD
using Microsoft.CodeAnalysis.Editor.Implementation.Structure;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
=======
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.Editor.Implementation.Structure;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.FindUsages;
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal partial class VisualStudioSymbolNavigationService : ForegroundThreadAffinitizedObject, ISymbolNavigationService
{
private readonly IServiceProvider _serviceProvider;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactory;
private readonly ITextEditorFactoryService _textEditorFactoryService;
private readonly ITextDocumentFactoryService _textDocumentFactoryService;
private readonly IMetadataAsSourceFileService _metadataAsSourceFileService;
private readonly VisualStudio14StructureTaggerProvider _outliningTaggerProvider;
public VisualStudioSymbolNavigationService(
SVsServiceProvider serviceProvider,
VisualStudio14StructureTaggerProvider outliningTaggerProvider)
{
_serviceProvider = serviceProvider;
_outliningTaggerProvider = outliningTaggerProvider;
var componentModel = _serviceProvider.GetService<SComponentModel, IComponentModel>();
_editorAdaptersFactory = componentModel.GetService<IVsEditorAdaptersFactoryService>();
_textEditorFactoryService = componentModel.GetService<ITextEditorFactoryService>();
_textDocumentFactoryService = componentModel.GetService<ITextDocumentFactoryService>();
_metadataAsSourceFileService = componentModel.GetService<IMetadataAsSourceFileService>();
}
public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet options, CancellationToken cancellationToken)
{
if (project == null || symbol == null)
{
return false;
}
options = options ?? project.Solution.Workspace.Options;
symbol = symbol.OriginalDefinition;
// Prefer visible source locations if possible.
var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource);
var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
var sourceLocation = visibleSourceLocations.FirstOrDefault() ?? sourceLocations.FirstOrDefault();
if (sourceLocation != null)
{
var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
if (targetDocument != null)
{
var editorWorkspace = targetDocument.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
return navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options);
}
}
// We don't have a source document, so show the Metadata as Source view in a preview tab.
var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();
if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
{
return false;
}
// Should we prefer navigating to the Object Browser over metadata-as-source?
if (options.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language))
{
var libraryService = project.LanguageServices.GetService<ILibraryService>();
if (libraryService == null)
{
return false;
}
var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation);
if (navInfo == null)
{
navInfo = libraryService.NavInfoFactory.CreateForProject(project);
}
if (navInfo != null)
{
var navigationTool = _serviceProvider.GetService<SVsObjBrowser, IVsNavigationTool>();
return navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK;
}
// Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen.
}
// Generate new source or retrieve existing source for the symbol in question
var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, cancellationToken).WaitAndGetResult(cancellationToken);
var vsRunningDocumentTable4 = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable4>();
var fileAlreadyOpen = vsRunningDocumentTable4.IsMonikerValid(result.FilePath);
var openDocumentService = _serviceProvider.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>();
openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out var localServiceProvider, out var hierarchy, out var itemId, out var windowFrame);
var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);
var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie);
var textBuffer = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer);
if (!fileAlreadyOpen)
{
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
}
windowFrame.Show();
var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault();
if (openedDocument != null)
{
var editorWorkspace = openedDocument.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
return navigationService.TryNavigateToSpan(
workspace: editorWorkspace,
documentId: openedDocument.Id,
textSpan: result.IdentifierLocation.SourceSpan,
options: options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true));
}
return true;
}
public bool TrySymbolNavigationNotify(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
return TryNotifyForSpecificSymbol(symbol, solution, cancellationToken);
}
private bool TryNotifyForSpecificSymbol(
ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
AssertIsForeground();
<<<<<<< HEAD
if (!TryGetNavigationAPIRequiredArguments(
symbol, solution, cancellationToken,
out var hierarchy, out var itemID, out var navigationNotify, out var rqname))
=======
var definitionItem = symbol.ToNonClassifiedDefinitionItem(solution, includeHiddenLocations: true);
definitionItem.Properties.TryGetValue(DefinitionItem.RQNameKey1, out var rqName);
if (!TryGetNavigationAPIRequiredArguments(
definitionItem, rqName, solution, cancellationToken,
out var hierarchy, out var itemID, out var navigationNotify))
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
{
return false;
}
int returnCode = navigationNotify.OnBeforeNavigateToSymbol(
hierarchy,
itemID,
<<<<<<< HEAD
rqname,
out var navigationHandled);
if (returnCode == VSConstants.S_OK && navigationHandled == 1)
{
return true;
}
=======
rqName,
out var navigationHandled);
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
return returnCode == VSConstants.S_OK && navigationHandled == 1;
}
public bool WouldNavigateToSymbol(
<<<<<<< HEAD
ISymbol symbol, Solution solution, CancellationToken cancellationToken,
out string filePath, out int lineNumber, out int charOffset)
{
if (WouldNotifyToSpecificSymbol(symbol, solution, cancellationToken, out filePath, out lineNumber, out charOffset))
{
return true;
}
// If the symbol being considered is a constructor and no third parties choose to
// navigate to the constructor, then try the constructor's containing type.
if (symbol.IsConstructor() && WouldNotifyToSpecificSymbol(
symbol.ContainingType, solution, cancellationToken, out filePath, out lineNumber, out charOffset))
=======
DefinitionItem definitionItem, Solution solution, CancellationToken cancellationToken,
out string filePath, out int lineNumber, out int charOffset)
{
definitionItem.Properties.TryGetValue(DefinitionItem.RQNameKey1, out var rqName1);
definitionItem.Properties.TryGetValue(DefinitionItem.RQNameKey2, out var rqName2);
if (WouldNotifyToSpecificSymbol(definitionItem, rqName1, solution, cancellationToken, out filePath, out lineNumber, out charOffset) ||
WouldNotifyToSpecificSymbol(definitionItem, rqName2, solution, cancellationToken, out filePath, out lineNumber, out charOffset))
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
{
return true;
}
filePath = null;
lineNumber = 0;
charOffset = 0;
return false;
}
public bool WouldNotifyToSpecificSymbol(
<<<<<<< HEAD
ISymbol symbol, Solution solution, CancellationToken cancellationToken,
=======
DefinitionItem definitionItem, string rqName, Solution solution, CancellationToken cancellationToken,
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
out string filePath, out int lineNumber, out int charOffset)
{
AssertIsForeground();
filePath = null;
lineNumber = 0;
charOffset = 0;
<<<<<<< HEAD
if (!TryGetNavigationAPIRequiredArguments(
symbol, solution, cancellationToken,
out var hierarchy, out var itemID, out var navigationNotify, out var rqname))
=======
if (rqName == null)
{
return false;
}
if (!TryGetNavigationAPIRequiredArguments(
definitionItem, rqName, solution, cancellationToken,
out var hierarchy, out var itemID, out var navigationNotify))
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
{
return false;
}
var navigateToTextSpan = new Microsoft.VisualStudio.TextManager.Interop.TextSpan[1];
int queryNavigateStatusCode = navigationNotify.QueryNavigateToSymbol(
hierarchy,
itemID,
<<<<<<< HEAD
rqname,
=======
rqName,
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
out var navigateToHierarchy,
out var navigateToItem,
navigateToTextSpan,
out var wouldNavigate);
if (queryNavigateStatusCode == VSConstants.S_OK && wouldNavigate == 1)
{
navigateToHierarchy.GetCanonicalName(navigateToItem, out filePath);
lineNumber = navigateToTextSpan[0].iStartLine;
charOffset = navigateToTextSpan[0].iStartIndex;
return true;
}
return false;
}
private bool TryGetNavigationAPIRequiredArguments(
DefinitionItem definitionItem,
string rqName,
Solution solution,
CancellationToken cancellationToken,
out IVsHierarchy hierarchy,
out uint itemID,
out IVsSymbolicNavigationNotify navigationNotify)
{
AssertIsForeground();
hierarchy = null;
navigationNotify = null;
itemID = (uint)VSConstants.VSITEMID.Nil;
if (rqName == null)
{
return false;
}
var sourceLocations = definitionItem.SourceSpans;
if (!sourceLocations.Any())
{
return false;
}
var documents = sourceLocations.SelectAsArray(loc => loc.Document);
// We can only pass one itemid to IVsSymbolicNavigationNotify, so prefer itemids from
// documents we consider to be "generated" to give external language services the best
// chance of participating.
<<<<<<< HEAD
var generatedDocuments = documents.Where(d => d.IsGeneratedCode(cancellationToken));
=======
var generatedDocuments = documents.WhereAsArray(d => d.IsGeneratedCode(cancellationToken));
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
var documentToUse = generatedDocuments.FirstOrDefault() ?? documents.First();
if (!TryGetVsHierarchyAndItemId(documentToUse, out hierarchy, out itemID))
{
return false;
}
navigationNotify = hierarchy as IVsSymbolicNavigationNotify;
if (navigationNotify == null)
{
return false;
}
return true;
}
private bool TryGetVsHierarchyAndItemId(Document document, out IVsHierarchy hierarchy, out uint itemID)
{
AssertIsForeground();
var visualStudioWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
if (visualStudioWorkspace != null)
{
var hostProject = visualStudioWorkspace.GetHostProject(document.Project.Id);
hierarchy = hostProject.Hierarchy;
itemID = hostProject.GetDocumentOrAdditionalDocument(document.Id).GetItemId();
return true;
}
hierarchy = null;
itemID = (uint)VSConstants.VSITEMID.Nil;
return false;
}
private IVsRunningDocumentTable GetRunningDocumentTable()
{
var runningDocumentTable = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable>();
Debug.Assert(runningDocumentTable != null);
return runningDocumentTable;
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Animation;
using Avalonia.Controls;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Avalonia.Data;
using Xunit;
using Avalonia.Animation.Easings;
using System.Threading;
using System.Reactive.Linq;
namespace Avalonia.Animation.UnitTests
{
public class AnimationIterationTests
{
[Fact]
public void Check_KeyTime_Correctly_Converted_To_Cue()
{
var keyframe1 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 100d),
},
KeyTime = TimeSpan.FromSeconds(0.5)
};
var keyframe2 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 0d),
},
KeyTime = TimeSpan.FromSeconds(0)
};
var animation = new Animation()
{
Duration = TimeSpan.FromSeconds(1),
Children =
{
keyframe2,
keyframe1
}
};
var border = new Border()
{
Height = 100d,
Width = 100d
};
var clock = new TestClock();
var animationRun = animation.RunAsync(border, clock);
clock.Step(TimeSpan.Zero);
Assert.Equal(border.Width, 0d);
clock.Step(TimeSpan.FromSeconds(1));
Assert.Equal(border.Width, 100d);
}
[Fact]
public void Check_Initial_Inter_and_Trailing_Delay_Values()
{
var keyframe1 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 200d),
},
Cue = new Cue(1d)
};
var keyframe2 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 100d),
},
Cue = new Cue(0d)
};
var animation = new Animation()
{
Duration = TimeSpan.FromSeconds(3),
Delay = TimeSpan.FromSeconds(3),
DelayBetweenIterations = TimeSpan.FromSeconds(3),
IterationCount = new IterationCount(2),
Children =
{
keyframe2,
keyframe1
}
};
var border = new Border()
{
Height = 100d,
Width = 100d
};
var clock = new TestClock();
var animationRun = animation.RunAsync(border, clock);
clock.Step(TimeSpan.Zero);
// Initial Delay.
clock.Step(TimeSpan.FromSeconds(1));
Assert.Equal(border.Width, 0d);
clock.Step(TimeSpan.FromSeconds(6));
// First Inter-Iteration delay.
clock.Step(TimeSpan.FromSeconds(8));
Assert.Equal(border.Width, 200d);
// Trailing Delay should be non-existent.
clock.Step(TimeSpan.FromSeconds(14));
Assert.True(animationRun.Status == TaskStatus.RanToCompletion);
Assert.Equal(border.Width, 100d);
}
[Fact]
public void Check_FillModes_Start_and_End_Values_if_Retained()
{
var keyframe1 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 0d),
},
Cue = new Cue(0.0d)
};
var keyframe2 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 300d),
},
Cue = new Cue(1.0d)
};
var animation = new Animation()
{
Duration = TimeSpan.FromSeconds(0.05d),
Delay = TimeSpan.FromSeconds(0.05d),
Easing = new SineEaseInOut(),
FillMode = FillMode.Both,
Children =
{
keyframe1,
keyframe2
}
};
var border = new Border()
{
Height = 100d,
Width = 100d,
};
var clock = new TestClock();
var animationRun = animation.RunAsync(border, clock);
clock.Step(TimeSpan.FromSeconds(0d));
Assert.Equal(border.Width, 0d);
clock.Step(TimeSpan.FromSeconds(0.050d));
Assert.Equal(border.Width, 0d);
clock.Step(TimeSpan.FromSeconds(0.100d));
Assert.Equal(border.Width, 300d);
}
[Fact(Skip = "See #6111")]
public void Dispose_Subscription_Should_Stop_Animation()
{
var keyframe1 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 200d),
},
Cue = new Cue(1d)
};
var keyframe2 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 100d),
},
Cue = new Cue(0d)
};
var animation = new Animation()
{
Duration = TimeSpan.FromSeconds(10),
Delay = TimeSpan.FromSeconds(0),
DelayBetweenIterations = TimeSpan.FromSeconds(0),
IterationCount = new IterationCount(1),
Children =
{
keyframe2,
keyframe1
}
};
var border = new Border()
{
Height = 100d,
Width = 50d
};
var propertyChangedCount = 0;
var animationCompletedCount = 0;
border.PropertyChanged += (sender, e) =>
{
if (e.Property == Control.WidthProperty)
{
propertyChangedCount++;
}
};
var clock = new TestClock();
var disposable = animation.Apply(border, clock, Observable.Return(true), () => animationCompletedCount++);
Assert.Equal(0, propertyChangedCount);
clock.Step(TimeSpan.FromSeconds(0));
Assert.Equal(0, animationCompletedCount);
Assert.Equal(1, propertyChangedCount);
disposable.Dispose();
// Clock ticks should be ignored after Dispose
clock.Step(TimeSpan.FromSeconds(5));
clock.Step(TimeSpan.FromSeconds(6));
clock.Step(TimeSpan.FromSeconds(7));
// On animation disposing (cancellation) on completed is not invoked (is it expected?)
Assert.Equal(0, animationCompletedCount);
// Initial property changed before cancellation + animation value removal.
Assert.Equal(2, propertyChangedCount);
}
[Fact]
public void Do_Not_Run_Cancelled_Animation()
{
var keyframe1 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 200d),
},
Cue = new Cue(1d)
};
var keyframe2 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 100d),
},
Cue = new Cue(0d)
};
var animation = new Animation()
{
Duration = TimeSpan.FromSeconds(10),
Delay = TimeSpan.FromSeconds(0),
DelayBetweenIterations = TimeSpan.FromSeconds(0),
IterationCount = new IterationCount(1),
Children =
{
keyframe2,
keyframe1
}
};
var border = new Border()
{
Height = 100d,
Width = 100d
};
var propertyChangedCount = 0;
border.PropertyChanged += (sender, e) =>
{
if (e.Property == Control.WidthProperty)
{
propertyChangedCount++;
}
};
var clock = new TestClock();
var cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.Cancel();
var animationRun = animation.RunAsync(border, clock, cancellationTokenSource.Token);
clock.Step(TimeSpan.FromSeconds(10));
Assert.Equal(0, propertyChangedCount);
Assert.True(animationRun.IsCompleted);
}
[Fact(Skip = "See #6111")]
public void Cancellation_Should_Stop_Animation()
{
var keyframe1 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 200d),
},
Cue = new Cue(1d)
};
var keyframe2 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 100d),
},
Cue = new Cue(0d)
};
var animation = new Animation()
{
Duration = TimeSpan.FromSeconds(10),
Delay = TimeSpan.FromSeconds(0),
DelayBetweenIterations = TimeSpan.FromSeconds(0),
IterationCount = new IterationCount(1),
Children =
{
keyframe2,
keyframe1
}
};
var border = new Border()
{
Height = 100d,
Width = 50d
};
var propertyChangedCount = 0;
border.PropertyChanged += (sender, e) =>
{
if (e.Property == Control.WidthProperty)
{
propertyChangedCount++;
}
};
var clock = new TestClock();
var cancellationTokenSource = new CancellationTokenSource();
var animationRun = animation.RunAsync(border, clock, cancellationTokenSource.Token);
Assert.Equal(0, propertyChangedCount);
clock.Step(TimeSpan.FromSeconds(0));
Assert.False(animationRun.IsCompleted);
Assert.Equal(1, propertyChangedCount);
cancellationTokenSource.Cancel();
clock.Step(TimeSpan.FromSeconds(1));
clock.Step(TimeSpan.FromSeconds(2));
clock.Step(TimeSpan.FromSeconds(3));
//Assert.Equal(2, propertyChangedCount);
animationRun.Wait();
clock.Step(TimeSpan.FromSeconds(6));
Assert.True(animationRun.IsCompleted);
Assert.Equal(2, propertyChangedCount);
}
[Fact]
public void Cancellation_Of_Completed_Animation_Does_Not_Fail()
{
var keyframe1 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 200d),
},
Cue = new Cue(1d)
};
var keyframe2 = new KeyFrame()
{
Setters =
{
new Setter(Border.WidthProperty, 100d),
},
Cue = new Cue(0d)
};
var animation = new Animation()
{
Duration = TimeSpan.FromSeconds(10),
Delay = TimeSpan.FromSeconds(0),
DelayBetweenIterations = TimeSpan.FromSeconds(0),
IterationCount = new IterationCount(1),
Children =
{
keyframe2,
keyframe1
}
};
var border = new Border()
{
Height = 100d,
Width = 50d
};
var propertyChangedCount = 0;
border.PropertyChanged += (sender, e) =>
{
if (e.Property == Control.WidthProperty)
{
propertyChangedCount++;
}
};
var clock = new TestClock();
var cancellationTokenSource = new CancellationTokenSource();
var animationRun = animation.RunAsync(border, clock, cancellationTokenSource.Token);
Assert.Equal(0, propertyChangedCount);
clock.Step(TimeSpan.FromSeconds(0));
Assert.False(animationRun.IsCompleted);
Assert.Equal(1, propertyChangedCount);
clock.Step(TimeSpan.FromSeconds(10));
Assert.True(animationRun.IsCompleted);
Assert.Equal(2, propertyChangedCount);
cancellationTokenSource.Cancel();
animationRun.Wait();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.Serialization;
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>
/// OrderedDictionary offers IDictionary syntax with ordering. Objects
/// added or inserted in an IOrderedDictionary must have both a key and an index, and
/// can be retrieved by either.
/// OrderedDictionary is used by the ParameterCollection because MSAccess relies on ordering of
/// parameters, while almost all other DBs do not. DataKeyArray also uses it so
/// DataKeys can be retrieved by either their name or their index.
///
/// OrderedDictionary implements IDeserializationCallback because it needs to have the
/// contained ArrayList and Hashtable deserialized before it tries to get its count and objects.
/// </para>
/// </devdoc>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class OrderedDictionary : IOrderedDictionary, ISerializable, IDeserializationCallback
{
private ArrayList _objectsArray;
private Hashtable _objectsTable;
private int _initialCapacity;
private IEqualityComparer _comparer;
private bool _readOnly;
private Object _syncRoot;
private SerializationInfo _siInfo; //A temporary variable which we need during deserialization.
private const string KeyComparerName = "KeyComparer"; // Do not rename (binary serialization)
private const string ArrayListName = "ArrayList"; // Do not rename (binary serialization)
private const string ReadOnlyName = "ReadOnly"; // Do not rename (binary serialization)
private const string InitCapacityName = "InitialCapacity"; // Do not rename (binary serialization)
public OrderedDictionary() : this(0)
{
}
public OrderedDictionary(int capacity) : this(capacity, null)
{
}
public OrderedDictionary(IEqualityComparer comparer) : this(0, comparer)
{
}
public OrderedDictionary(int capacity, IEqualityComparer comparer)
{
_initialCapacity = capacity;
_comparer = comparer;
}
private OrderedDictionary(OrderedDictionary dictionary)
{
Debug.Assert(dictionary != null);
_readOnly = true;
_objectsArray = dictionary._objectsArray;
_objectsTable = dictionary._objectsTable;
_comparer = dictionary._comparer;
_initialCapacity = dictionary._initialCapacity;
}
protected OrderedDictionary(SerializationInfo info, StreamingContext context)
{
// We can't do anything with the keys and values until the entire graph has been deserialized
// and getting Counts and objects won't fail. For the time being, we'll just cache this.
// The graph is not valid until OnDeserialization has been called.
_siInfo = info;
}
/// <devdoc>
/// Gets the size of the table.
/// </devdoc>
public int Count
{
get
{
return objectsArray.Count;
}
}
/// <devdoc>
/// Indicates that the collection can grow.
/// </devdoc>
bool IDictionary.IsFixedSize
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that the collection is not read-only
/// </devdoc>
public bool IsReadOnly
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that this class is not synchronized
/// </devdoc>
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
/// <devdoc>
/// Gets the collection of keys in the table in order.
/// </devdoc>
public ICollection Keys
{
get
{
return new OrderedDictionaryKeyValueCollection(objectsArray, true);
}
}
private ArrayList objectsArray
{
get
{
if (_objectsArray == null)
{
_objectsArray = new ArrayList(_initialCapacity);
}
return _objectsArray;
}
}
private Hashtable objectsTable
{
get
{
if (_objectsTable == null)
{
_objectsTable = new Hashtable(_initialCapacity, _comparer);
}
return _objectsTable;
}
}
/// <devdoc>
/// The SyncRoot object. Not used because IsSynchronized is false
/// </devdoc>
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
/// <devdoc>
/// Gets or sets the object at the specified index
/// </devdoc>
public object this[int index]
{
get
{
return ((DictionaryEntry)objectsArray[index]).Value;
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index < 0 || index >= objectsArray.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
object key = ((DictionaryEntry)objectsArray[index]).Key;
objectsArray[index] = new DictionaryEntry(key, value);
objectsTable[key] = value;
}
}
/// <devdoc>
/// Gets or sets the object with the specified key
/// </devdoc>
public object this[object key]
{
get
{
return objectsTable[key];
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (objectsTable.Contains(key))
{
objectsTable[key] = value;
objectsArray[IndexOfKey(key)] = new DictionaryEntry(key, value);
}
else
{
Add(key, value);
}
}
}
/// <devdoc>
/// Returns an arrayList of the values in the table
/// </devdoc>
public ICollection Values
{
get
{
return new OrderedDictionaryKeyValueCollection(objectsArray, false);
}
}
/// <devdoc>
/// Adds a new entry to the table with the lowest-available index.
/// </devdoc>
public void Add(object key, object value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
objectsTable.Add(key, value);
objectsArray.Add(new DictionaryEntry(key, value));
}
/// <devdoc>
/// Clears all elements in the table.
/// </devdoc>
public void Clear()
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
objectsTable.Clear();
objectsArray.Clear();
}
/// <devdoc>
/// Returns a readonly OrderedDictionary for the given OrderedDictionary.
/// </devdoc>
public OrderedDictionary AsReadOnly()
{
return new OrderedDictionary(this);
}
/// <devdoc>
/// Returns true if the key exists in the table, false otherwise.
/// </devdoc>
public bool Contains(object key)
{
return objectsTable.Contains(key);
}
/// <devdoc>
/// Copies the table to an array. This will not preserve order.
/// </devdoc>
public void CopyTo(Array array, int index)
{
objectsTable.CopyTo(array, index);
}
private int IndexOfKey(object key)
{
for (int i = 0; i < objectsArray.Count; i++)
{
object o = ((DictionaryEntry)objectsArray[i]).Key;
if (_comparer != null)
{
if (_comparer.Equals(o, key))
{
return i;
}
}
else
{
if (o.Equals(key))
{
return i;
}
}
}
return -1;
}
/// <devdoc>
/// Inserts a new object at the given index with the given key.
/// </devdoc>
public void Insert(int index, object key, object value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index > Count || index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
objectsTable.Add(key, value);
objectsArray.Insert(index, new DictionaryEntry(key, value));
}
/// <devdoc>
/// Removes the entry at the given index.
/// </devdoc>
public void RemoveAt(int index)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index >= Count || index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
object key = ((DictionaryEntry)objectsArray[index]).Key;
objectsArray.RemoveAt(index);
objectsTable.Remove(key);
}
/// <devdoc>
/// Removes the entry with the given key.
/// </devdoc>
public void Remove(object key)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
int index = IndexOfKey(key);
if (index < 0)
{
return;
}
objectsTable.Remove(key);
objectsArray.RemoveAt(index);
}
#region IDictionary implementation
public virtual IDictionaryEnumerator GetEnumerator()
{
return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region ISerializable implementation
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
info.AddValue(KeyComparerName, _comparer, typeof(IEqualityComparer));
info.AddValue(ReadOnlyName, _readOnly);
info.AddValue(InitCapacityName, _initialCapacity);
object[] serArray = new object[Count];
_objectsArray.CopyTo(serArray);
info.AddValue(ArrayListName, serArray);
}
#endregion
#region IDeserializationCallback implementation
void IDeserializationCallback.OnDeserialization(object sender) {
OnDeserialization(sender);
}
protected virtual void OnDeserialization(object sender)
{
if (_siInfo == null)
{
throw new SerializationException(SR.Serialization_InvalidOnDeser);
}
_comparer = (IEqualityComparer)_siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer));
_readOnly = _siInfo.GetBoolean(ReadOnlyName);
_initialCapacity = _siInfo.GetInt32(InitCapacityName);
object[] serArray = (object[])_siInfo.GetValue(ArrayListName, typeof(object[]));
if (serArray != null)
{
foreach (object o in serArray)
{
DictionaryEntry entry;
try
{
// DictionaryEntry is a value type, so it can only be casted.
entry = (DictionaryEntry)o;
}
catch
{
throw new SerializationException(SR.OrderedDictionary_SerializationMismatch);
}
objectsArray.Add(entry);
objectsTable.Add(entry.Key, entry.Value);
}
}
}
#endregion
/// <devdoc>
/// OrderedDictionaryEnumerator works just like any other IDictionaryEnumerator, but it retrieves DictionaryEntries
/// in the order by index.
/// </devdoc>
private class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
private int _objectReturnType;
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictionaryEntry = 3;
private IEnumerator _arrayEnumerator;
internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType)
{
_arrayEnumerator = array.GetEnumerator();
_objectReturnType = objectReturnType;
}
/// <devdoc>
/// Retrieves the current DictionaryEntry. This is the same as Entry, but not strongly-typed.
/// </devdoc>
public object Current
{
get
{
if (_objectReturnType == Keys)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
if (_objectReturnType == Values)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
return Entry;
}
}
/// <devdoc>
/// Retrieves the current DictionaryEntry
/// </devdoc>
public DictionaryEntry Entry
{
get
{
return new DictionaryEntry(((DictionaryEntry)_arrayEnumerator.Current).Key, ((DictionaryEntry)_arrayEnumerator.Current).Value);
}
}
/// <devdoc>
/// Retrieves the key of the current DictionaryEntry
/// </devdoc>
public object Key
{
get
{
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
}
/// <devdoc>
/// Retrieves the value of the current DictionaryEntry
/// </devdoc>
public object Value
{
get
{
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
}
/// <devdoc>
/// Moves the enumerator pointer to the next member
/// </devdoc>
public bool MoveNext()
{
return _arrayEnumerator.MoveNext();
}
/// <devdoc>
/// Resets the enumerator pointer to the beginning.
/// </devdoc>
public void Reset()
{
_arrayEnumerator.Reset();
}
}
/// <devdoc>
/// OrderedDictionaryKeyValueCollection implements a collection for the Values and Keys properties
/// that is "live"- it will reflect changes to the OrderedDictionary on the collection made after the getter
/// was called.
/// </devdoc>
private class OrderedDictionaryKeyValueCollection : ICollection
{
private ArrayList _objects;
private bool _isKeys;
public OrderedDictionaryKeyValueCollection(ArrayList array, bool isKeys)
{
_objects = array;
_isKeys = isKeys;
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
foreach (object o in _objects)
{
array.SetValue(_isKeys ? ((DictionaryEntry)o).Key : ((DictionaryEntry)o).Value, index);
index++;
}
}
int ICollection.Count
{
get
{
return _objects.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return _objects.SyncRoot;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new OrderedDictionaryEnumerator(_objects, _isKeys == true ? OrderedDictionaryEnumerator.Keys : OrderedDictionaryEnumerator.Values);
}
}
}
}
| |
// --------------------------------------------------
// 3DS Theme Editor - FlagsViewModel.cs
// --------------------------------------------------
using ThemeEditor.Common.Themes;
using ThemeEditor.WPF.Localization;
using ThemeEditor.WPF.Localization.Enums;
namespace ThemeEditor.WPF.Themes
{
public class FlagsViewModel : ViewModelBase
{
[Order("Theme_Flags_Arrow_Button_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Arrow_Button_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Arrow_Button_Color_Desc", typeof(ThemeResources))]
public bool ArrowButtonColor
{
get { return Model.ArrowButtonColor; }
set
{
var oldValue = Model.ArrowButtonColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.ArrowButtonColor = newValue;
RaiseViewModelChanged(nameof(ArrowButtonColor), oldValue, value);
}
}
[Order("Theme_Flags_Arrow_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Arrow_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Arrow_Color_Desc", typeof(ThemeResources))]
public bool ArrowColor
{
get { return Model.ArrowColor; }
set
{
var oldValue = Model.ArrowColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.ArrowColor = newValue;
RaiseViewModelChanged(nameof(ArrowColor), oldValue, value);
}
}
[Order("Theme_Flags_Background_Music_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Background_Music", typeof(ThemeResources))]
[Description("Theme_Flags_Background_Music_Desc", typeof(ThemeResources))]
public bool BackgroundMusic
{
get { return Model.BackgroundMusic; }
set
{
var oldValue = Model.BackgroundMusic;
var newValue = value;
if (oldValue == newValue)
return;
Model.BackgroundMusic = newValue;
RaiseViewModelChanged(nameof(BackgroundMusic), oldValue, value);
}
}
[Order("Theme_Flags_Bottom_Background_Inner_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Bottom_Background_Inner_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Bottom_Background_Inner_Color_Desc", typeof(ThemeResources))]
public bool BottomBackgroundInnerColor
{
get { return Model.BottomBackgroundInnerColor; }
set
{
var oldValue = Model.BottomBackgroundInnerColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.BottomBackgroundInnerColor = newValue;
RaiseViewModelChanged(nameof(BottomBackgroundInnerColor), oldValue, value);
}
}
[Order("Theme_Flags_Bottom_Background_Outer_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Bottom_Background_Outer_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Bottom_Background_Outer_Color_Desc", typeof(ThemeResources))]
public bool BottomBackgroundOuterColor
{
get { return Model.BottomBackgroundOuterColor; }
set
{
var oldValue = Model.BottomBackgroundOuterColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.BottomBackgroundOuterColor = newValue;
RaiseViewModelChanged(nameof(BottomBackgroundOuterColor), oldValue, value);
}
}
[Order("Theme_Flags_Bottom_Corner_Button_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Bottom_Corner_Button_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Bottom_Corner_Button_Color_Desc", typeof(ThemeResources))]
public bool BottomCornerButtonColor
{
get { return Model.BottomCornerButtonColor; }
set
{
var oldValue = Model.BottomCornerButtonColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.BottomCornerButtonColor = newValue;
RaiseViewModelChanged(nameof(BottomCornerButtonColor), oldValue, value);
}
}
[Order("Theme_Flags_Bottom_Draw_Type_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Bottom_Draw_Type", typeof(ThemeResources))]
[Description("Theme_Flags_Bottom_Draw_Type_Desc", typeof(ThemeResources))]
public BottomDrawType BottomDrawType
{
get { return (BottomDrawType) (uint) Model.BottomDrawType; }
set
{
var oldValue = (uint) Model.BottomDrawType;
var newValue = (uint) value;
if (oldValue == newValue)
return;
Model.BottomDrawType = (Common.Themes.Enums.BottomDrawType) newValue;
RaiseViewModelChanged(nameof(BottomDrawType), oldValue, value);
}
}
[Order("Theme_Flags_Bottom_Frame_Type_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Bottom_Frame_Type", typeof(ThemeResources))]
[Description("Theme_Flags_Bottom_Frame_Type_Desc", typeof(ThemeResources))]
public BottomFrameType BottomFrameType
{
get { return (BottomFrameType) (uint) Model.BottomFrameType; }
set
{
var oldValue = (uint) Model.BottomFrameType;
var newValue = (uint) value;
if (oldValue == newValue)
return;
Model.BottomFrameType = (Common.Themes.Enums.BottomFrameType) newValue;
RaiseViewModelChanged(nameof(BottomFrameType), oldValue, value);
}
}
[Order("Theme_Flags_Cursor_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Cursor_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Cursor_Color_Desc", typeof(ThemeResources))]
public bool CursorColor
{
get { return Model.CursorColor; }
set
{
var oldValue = Model.CursorColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.CursorColor = newValue;
RaiseViewModelChanged(nameof(CursorColor), oldValue, value);
}
}
[Order("Theme_Flags_Demo_Text_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Demo_Text_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Demo_Text_Color_Desc", typeof(ThemeResources))]
public bool DemoTextColor
{
get { return Model.DemoTextColor; }
set
{
var oldValue = Model.DemoTextColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.DemoTextColor = newValue;
RaiseViewModelChanged(nameof(DemoTextColor), oldValue, value);
}
}
[Order("Theme_Flags_File_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_File_Color", typeof(ThemeResources))]
[Description("Theme_Flags_File_Color_Desc", typeof(ThemeResources))]
public bool FileColor
{
get { return Model.FileColor; }
set
{
var oldValue = Model.FileColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.FileColor = newValue;
RaiseViewModelChanged(nameof(FileColor), oldValue, value);
}
}
[Order("Theme_Flags_File_Texture_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_File_Texture", typeof(ThemeResources))]
[Description("Theme_Flags_File_Texture_Desc", typeof(ThemeResources))]
public bool FileTexture
{
get { return Model.FileTexture; }
set
{
var oldValue = Model.FileTexture;
var newValue = value;
if (oldValue == newValue)
return;
Model.FileTexture = newValue;
RaiseViewModelChanged(nameof(FileTexture), oldValue, value);
}
}
[Order("Theme_Flags_Folder_Arrow_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Folder_Arrow_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Folder_Arrow_Color_Desc", typeof(ThemeResources))]
public bool FolderArrowColor
{
get { return Model.FolderArrowColor; }
set
{
var oldValue = Model.FolderArrowColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.FolderArrowColor = newValue;
RaiseViewModelChanged(nameof(FolderArrowColor), oldValue, value);
}
}
[Order("Theme_Flags_Folder_Background_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Folder_Background_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Folder_Background_Color_Desc", typeof(ThemeResources))]
public bool FolderBackgroundColor
{
get { return Model.FolderBackgroundColor; }
set
{
var oldValue = Model.FolderBackgroundColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.FolderBackgroundColor = newValue;
RaiseViewModelChanged(nameof(FolderBackgroundColor), oldValue, value);
}
}
[Order("Theme_Flags_Folder_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Folder_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Folder_Color_Desc", typeof(ThemeResources))]
public bool FolderColor
{
get { return Model.FolderColor; }
set
{
var oldValue = Model.FolderColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.FolderColor = newValue;
RaiseViewModelChanged(nameof(FolderColor), oldValue, value);
}
}
[Order("Theme_Flags_Folder_Texture_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Folder_Texture", typeof(ThemeResources))]
[Description("Theme_Flags_Folder_Texture_Desc", typeof(ThemeResources))]
public bool FolderTexture
{
get { return Model.FolderTexture; }
set
{
var oldValue = Model.FolderTexture;
var newValue = value;
if (oldValue == newValue)
return;
Model.FolderTexture = newValue;
RaiseViewModelChanged(nameof(FolderTexture), oldValue, value);
}
}
[Order("Theme_Flags_Game_Text_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Game_Text_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Game_Text_Color_Desc", typeof(ThemeResources))]
public GameTextDrawType GameTextDrawType
{
get { return (GameTextDrawType) (uint) Model.GameTextDrawType; }
set
{
var oldValue = (uint) Model.GameTextDrawType;
var newValue = (uint) value;
if (oldValue == newValue)
return;
Model.GameTextDrawType = (Common.Themes.Enums.GameTextDrawType) newValue;
RaiseViewModelChanged(nameof(GameTextDrawType), oldValue, value);
}
}
private new Flags Model => (Flags) base.Model;
[Order("Theme_Flags_Open_Close_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Open_Close_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Open_Close_Color_Desc", typeof(ThemeResources))]
public bool OpenCloseColor
{
get { return Model.OpenCloseColor; }
set
{
var oldValue = Model.OpenCloseColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.OpenCloseColor = newValue;
RaiseViewModelChanged(nameof(OpenCloseColor), oldValue, value);
}
}
[Order("Theme_Flags_Sound_Effect_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Sound_Effect", typeof(ThemeResources))]
[Description("Theme_Flags_Sound_Effect_Desc", typeof(ThemeResources))]
public bool SoundEffect
{
get { return Model.SoundEffect; }
set
{
var oldValue = Model.SoundEffect;
var newValue = value;
if (oldValue == newValue)
return;
Model.SoundEffect = newValue;
RaiseViewModelChanged(nameof(SoundEffect), oldValue, value);
}
}
[Order("Theme_Flags_Top_Background_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Top_Background_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Top_Background_Color_Desc", typeof(ThemeResources))]
public bool TopBackgroundColor
{
get
{
var enb = (uint) Model.TopDrawType == (uint) TopDrawType.SolidColor
|| (uint) Model.TopDrawType == (uint) TopDrawType.SolidColorTexture;
return enb;
}
}
[Order("Theme_Flags_Top_Corner_Button_Color_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Top_Corner_Button_Color", typeof(ThemeResources))]
[Description("Theme_Flags_Top_Corner_Button_Color_Desc", typeof(ThemeResources))]
public bool TopCornerButtonColor
{
get { return Model.TopCornerButtonColor; }
set
{
var oldValue = Model.TopCornerButtonColor;
var newValue = value;
if (oldValue == newValue)
return;
Model.TopCornerButtonColor = newValue;
RaiseViewModelChanged(nameof(TopCornerButtonColor), oldValue, value);
}
}
[Order("Theme_Flags_Top_Draw_Type_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Top_Draw_Type", typeof(ThemeResources))]
[Description("Theme_Flags_Top_Draw_Type_Desc", typeof(ThemeResources))]
public TopDrawType TopDrawType
{
get { return (TopDrawType) (uint) Model.TopDrawType; }
set
{
var oldBgc = TopBackgroundColor;
var oldValue = (uint) Model.TopDrawType;
var newValue = (uint) value;
if (oldValue == newValue)
return;
Model.TopDrawType = (Common.Themes.Enums.TopDrawType) newValue;
RaiseViewModelChanged(nameof(TopDrawType), oldValue, value);
RaiseViewModelChanged(nameof(TopBackgroundColor), oldBgc, TopBackgroundColor);
}
}
[Order("Theme_Flags_Top_Frame_Type_Order", typeof(ThemeResources))]
[DisplayName("Theme_Flags_Top_Frame_Type", typeof(ThemeResources))]
[Description("Theme_Flags_Top_Frame_Type_Desc", typeof(ThemeResources))]
public TopFrameType TopFrameType
{
get { return (TopFrameType) (int) Model.TopFrameType; }
set
{
var oldValue = (uint) Model.TopFrameType;
var newValue = (uint) value;
if (oldValue == newValue)
return;
Model.TopFrameType = (Common.Themes.Enums.TopFrameType) newValue;
RaiseViewModelChanged(nameof(TopFrameType), oldValue, value);
}
}
public FlagsViewModel(Flags model, string tag) : base(model, tag) {}
}
}
| |
/*
* Copyright (c) 2006-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse.StructuredData;
namespace OpenMetaverse
{
[Serializable]
public partial class Primitive : IEquatable<Primitive>
{
// Used for packing and unpacking parameters
protected const float CUT_QUANTA = 0.00002f;
protected const float SCALE_QUANTA = 0.01f;
protected const float SHEAR_QUANTA = 0.01f;
protected const float TAPER_QUANTA = 0.01f;
protected const float REV_QUANTA = 0.015f;
protected const float HOLLOW_QUANTA = 0.00002f;
#region Subclasses
/// <summary>
/// Parameters used to construct a visual representation of a primitive
/// </summary>
[Serializable]
public struct ConstructionData
{
private const byte PROFILE_MASK = 0x0F;
private const byte HOLE_MASK = 0xF0;
/// <summary></summary>
public byte profileCurve;
/// <summary></summary>
public PathCurve PathCurve;
/// <summary></summary>
public float PathEnd;
/// <summary></summary>
public float PathRadiusOffset;
/// <summary></summary>
public float PathSkew;
/// <summary></summary>
public float PathScaleX;
/// <summary></summary>
public float PathScaleY;
/// <summary></summary>
public float PathShearX;
/// <summary></summary>
public float PathShearY;
/// <summary></summary>
public float PathTaperX;
/// <summary></summary>
public float PathTaperY;
/// <summary></summary>
public float PathBegin;
/// <summary></summary>
public float PathTwist;
/// <summary></summary>
public float PathTwistBegin;
/// <summary></summary>
public float PathRevolutions;
/// <summary></summary>
public float ProfileBegin;
/// <summary></summary>
public float ProfileEnd;
/// <summary></summary>
public float ProfileHollow;
/// <summary></summary>
public Material Material;
/// <summary></summary>
public byte State;
/// <summary></summary>
public PCode PCode;
#region Properties
/// <summary>Attachment point to an avatar</summary>
public AttachmentPoint AttachmentPoint
{
get { return (AttachmentPoint)Utils.SwapWords(State); }
set { State = (byte)Utils.SwapWords((byte)value); }
}
/// <summary></summary>
public ProfileCurve ProfileCurve
{
get { return (ProfileCurve)(profileCurve & PROFILE_MASK); }
set
{
profileCurve &= HOLE_MASK;
profileCurve |= (byte)value;
}
}
/// <summary></summary>
public HoleType ProfileHole
{
get { return (HoleType)(profileCurve & HOLE_MASK); }
set
{
profileCurve &= PROFILE_MASK;
profileCurve |= (byte)value;
}
}
/// <summary></summary>
public Vector2 PathBeginScale
{
get
{
Vector2 begin = new Vector2(1f, 1f);
if (PathScaleX > 1f)
begin.X = 2f - PathScaleX;
if (PathScaleY > 1f)
begin.Y = 2f - PathScaleY;
return begin;
}
}
/// <summary></summary>
public Vector2 PathEndScale
{
get
{
Vector2 end = new Vector2(1f, 1f);
if (PathScaleX < 1f)
end.X = PathScaleX;
if (PathScaleY < 1f)
end.Y = PathScaleY;
return end;
}
}
#endregion Properties
/// <summary>
/// Calculdates hash code for prim construction data
/// </summary>
/// <returns>The has</returns>
public override int GetHashCode()
{
return profileCurve.GetHashCode()
^ PathCurve.GetHashCode()
^ PathEnd.GetHashCode()
^ PathRadiusOffset.GetHashCode()
^ PathSkew.GetHashCode()
^ PathScaleX.GetHashCode()
^ PathScaleY.GetHashCode()
^ PathShearX.GetHashCode()
^ PathShearY.GetHashCode()
^ PathTaperX.GetHashCode()
^ PathTaperY.GetHashCode()
^ PathBegin.GetHashCode()
^ PathTwist.GetHashCode()
^ PathTwistBegin.GetHashCode()
^ PathRevolutions.GetHashCode()
^ ProfileBegin.GetHashCode()
^ ProfileEnd.GetHashCode()
^ ProfileHollow.GetHashCode()
^ Material.GetHashCode()
^ State.GetHashCode()
^ PCode.GetHashCode();
}
}
/// <summary>
/// Information on the flexible properties of a primitive
/// </summary>
public class FlexibleData
{
/// <summary></summary>
public int Softness;
/// <summary></summary>
public float Gravity;
/// <summary></summary>
public float Drag;
/// <summary></summary>
public float Wind;
/// <summary></summary>
public float Tension;
/// <summary></summary>
public Vector3 Force;
/// <summary>
/// Default constructor
/// </summary>
public FlexibleData()
{
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="pos"></param>
public FlexibleData(byte[] data, int pos)
{
if (data.Length >= 5)
{
Softness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7);
Tension = (float)(data[pos++] & 0x7F) / 10.0f;
Drag = (float)(data[pos++] & 0x7F) / 10.0f;
Gravity = (float)(data[pos++] / 10.0f) - 10.0f;
Wind = (float)data[pos++] / 10.0f;
Force = new Vector3(data, pos);
}
else
{
Softness = 0;
Tension = 0.0f;
Drag = 0.0f;
Gravity = 0.0f;
Wind = 0.0f;
Force = Vector3.Zero;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public byte[] GetBytes()
{
byte[] data = new byte[16];
int i = 0;
// Softness is packed in the upper bits of tension and drag
data[i] = (byte)((Softness & 2) << 6);
data[i + 1] = (byte)((Softness & 1) << 7);
data[i++] |= (byte)((byte)(Tension * 10.01f) & 0x7F);
data[i++] |= (byte)((byte)(Drag * 10.01f) & 0x7F);
data[i++] = (byte)((Gravity + 10.0f) * 10.01f);
data[i++] = (byte)(Wind * 10.01f);
Force.GetBytes().CopyTo(data, i);
return data;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public OSD GetOSD()
{
OSDMap map = new OSDMap();
map["simulate_lod"] = OSD.FromInteger(Softness);
map["gravity"] = OSD.FromReal(Gravity);
map["air_friction"] = OSD.FromReal(Drag);
map["wind_sensitivity"] = OSD.FromReal(Wind);
map["tension"] = OSD.FromReal(Tension);
map["user_force"] = OSD.FromVector3(Force);
return map;
}
public static FlexibleData FromOSD(OSD osd)
{
FlexibleData flex = new FlexibleData();
if (osd.Type == OSDType.Map)
{
OSDMap map = (OSDMap)osd;
flex.Softness = map["simulate_lod"].AsInteger();
flex.Gravity = (float)map["gravity"].AsReal();
flex.Drag = (float)map["air_friction"].AsReal();
flex.Wind = (float)map["wind_sensitivity"].AsReal();
flex.Tension = (float)map["tension"].AsReal();
flex.Force = ((OSDArray)map["user_force"]).AsVector3();
}
return flex;
}
public override int GetHashCode()
{
return
Softness.GetHashCode() ^
Gravity.GetHashCode() ^
Drag.GetHashCode() ^
Wind.GetHashCode() ^
Tension.GetHashCode() ^
Force.GetHashCode();
}
}
/// <summary>
/// Information on the light properties of a primitive
/// </summary>
public class LightData
{
/// <summary></summary>
public Color4 Color;
/// <summary></summary>
public float Intensity;
/// <summary></summary>
public float Radius;
/// <summary></summary>
public float Cutoff;
/// <summary></summary>
public float Falloff;
/// <summary>
/// Default constructor
/// </summary>
public LightData()
{
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="pos"></param>
public LightData(byte[] data, int pos)
{
if (data.Length - pos >= 16)
{
Color = new Color4(data, pos, false);
Radius = Utils.BytesToFloat(data, pos + 4);
Cutoff = Utils.BytesToFloat(data, pos + 8);
Falloff = Utils.BytesToFloat(data, pos + 12);
// Alpha in color is actually intensity
Intensity = Color.A;
Color.A = 1f;
}
else
{
Color = Color4.Black;
Radius = 0f;
Cutoff = 0f;
Falloff = 0f;
Intensity = 0f;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public byte[] GetBytes()
{
byte[] data = new byte[16];
// Alpha channel in color is intensity
Color4 tmpColor = Color;
tmpColor.A = Intensity;
tmpColor.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(Radius).CopyTo(data, 4);
Utils.FloatToBytes(Cutoff).CopyTo(data, 8);
Utils.FloatToBytes(Falloff).CopyTo(data, 12);
return data;
}
public OSD GetOSD()
{
OSDMap map = new OSDMap();
map["color"] = OSD.FromColor4(Color);
map["intensity"] = OSD.FromReal(Intensity);
map["radius"] = OSD.FromReal(Radius);
map["cutoff"] = OSD.FromReal(Cutoff);
map["falloff"] = OSD.FromReal(Falloff);
return map;
}
public static LightData FromOSD(OSD osd)
{
LightData light = new LightData();
if (osd.Type == OSDType.Map)
{
OSDMap map = (OSDMap)osd;
light.Color = ((OSDArray)map["color"]).AsColor4();
light.Intensity = (float)map["intensity"].AsReal();
light.Radius = (float)map["radius"].AsReal();
light.Cutoff = (float)map["cutoff"].AsReal();
light.Falloff = (float)map["falloff"].AsReal();
}
return light;
}
public override int GetHashCode()
{
return
Color.GetHashCode() ^
Intensity.GetHashCode() ^
Radius.GetHashCode() ^
Cutoff.GetHashCode() ^
Falloff.GetHashCode();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return String.Format("Color: {0} Intensity: {1} Radius: {2} Cutoff: {3} Falloff: {4}",
Color, Intensity, Radius, Cutoff, Falloff);
}
}
/// <summary>
/// Information on the sculpt properties of a sculpted primitive
/// </summary>
public class SculptData
{
public UUID SculptTexture;
private byte type;
public SculptType Type
{
get { return (SculptType)(type & 7); }
set { type = (byte)value; }
}
/// <summary>
/// Render inside out (inverts the normals).
/// </summary>
public bool Invert
{
get { return ((type & (byte)SculptType.Invert) != 0); }
}
/// <summary>
/// Render an X axis mirror of the sculpty.
/// </summary>
public bool Mirror
{
get { return ((type & (byte)SculptType.Mirror) != 0); }
}
/// <summary>
/// Default constructor
/// </summary>
public SculptData()
{
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="pos"></param>
public SculptData(byte[] data, int pos)
{
if (data.Length >= 17)
{
SculptTexture = new UUID(data, pos);
type = data[pos + 16];
}
else
{
SculptTexture = UUID.Zero;
type = (byte)SculptType.None;
}
}
public byte[] GetBytes()
{
byte[] data = new byte[17];
SculptTexture.GetBytes().CopyTo(data, 0);
data[16] = type;
return data;
}
public OSD GetOSD()
{
OSDMap map = new OSDMap();
map["texture"] = OSD.FromUUID(SculptTexture);
map["type"] = OSD.FromInteger(type);
return map;
}
public static SculptData FromOSD(OSD osd)
{
SculptData sculpt = new SculptData();
if (osd.Type == OSDType.Map)
{
OSDMap map = (OSDMap)osd;
sculpt.SculptTexture = map["texture"].AsUUID();
sculpt.type = (byte)map["type"].AsInteger();
}
return sculpt;
}
public override int GetHashCode()
{
return SculptTexture.GetHashCode() ^ type.GetHashCode();
}
}
/// <summary>
/// Extended properties to describe an object
/// </summary>
[Serializable]
public class ObjectProperties
{
/// <summary></summary>
public UUID ObjectID;
/// <summary></summary>
public UUID CreatorID;
/// <summary></summary>
public UUID OwnerID;
/// <summary></summary>
public UUID GroupID;
/// <summary></summary>
public DateTime CreationDate;
/// <summary></summary>
public Permissions Permissions;
/// <summary></summary>
public int OwnershipCost;
/// <summary></summary>
public SaleType SaleType;
/// <summary></summary>
public int SalePrice;
/// <summary></summary>
public byte AggregatePerms;
/// <summary></summary>
public byte AggregatePermTextures;
/// <summary></summary>
public byte AggregatePermTexturesOwner;
/// <summary></summary>
public ObjectCategory Category;
/// <summary></summary>
public short InventorySerial;
/// <summary></summary>
public UUID ItemID;
/// <summary></summary>
public UUID FolderID;
/// <summary></summary>
public UUID FromTaskID;
/// <summary></summary>
public UUID LastOwnerID;
/// <summary></summary>
public string Name;
/// <summary></summary>
public string Description;
/// <summary></summary>
public string TouchName;
/// <summary></summary>
public string SitName;
/// <summary></summary>
public UUID[] TextureIDs;
/// <summary>
/// Default constructor
/// </summary>
public ObjectProperties()
{
Name = String.Empty;
Description = String.Empty;
TouchName = String.Empty;
SitName = String.Empty;
}
/// <summary>
/// Set the properties that are set in an ObjectPropertiesFamily packet
/// </summary>
/// <param name="props"><seealso cref="ObjectProperties"/> that has
/// been partially filled by an ObjectPropertiesFamily packet</param>
public void SetFamilyProperties(ObjectProperties props)
{
ObjectID = props.ObjectID;
OwnerID = props.OwnerID;
GroupID = props.GroupID;
Permissions = props.Permissions;
OwnershipCost = props.OwnershipCost;
SaleType = props.SaleType;
SalePrice = props.SalePrice;
Category = props.Category;
LastOwnerID = props.LastOwnerID;
Name = props.Name;
Description = props.Description;
}
public void SetFamilyProperties(Primitive props)
{
if (UUID.Zero != props.ID) ObjectID = props.ID;
if (UUID.Zero != props.OwnerID) OwnerID = props.OwnerID;
if (UUID.Zero != props.GroupID) GroupID = props.GroupID;
}
public byte[] GetTextureIDBytes()
{
if (TextureIDs == null || TextureIDs.Length == 0)
return Utils.EmptyBytes;
byte[] bytes = new byte[16 * TextureIDs.Length];
for (int i = 0; i < TextureIDs.Length; i++)
TextureIDs[i].ToBytes(bytes, 16 * i);
return bytes;
}
public void ApplyProperties(Primitive primitive)
{
if (UUID.Zero != OwnerID) primitive.OwnerID = OwnerID;
if (UUID.Zero != GroupID) primitive.GroupID = GroupID;
if (UUID.Zero != ObjectID) primitive.ID = ObjectID;
SetFamilyProperties(primitive);
}
}
/// <summary>
/// Describes physics attributes of the prim
/// </summary>
public class PhysicsProperties
{
/// <summary>Primitive's local ID</summary>
public uint LocalID;
/// <summary>Density (1000 for normal density)</summary>
public float Density;
/// <summary>Friction</summary>
public float Friction;
/// <summary>Gravity multiplier (1 for normal gravity) </summary>
public float GravityMultiplier;
/// <summary>Type of physics representation of this primitive in the simulator</summary>
public PhysicsShapeType PhysicsShapeType;
/// <summary>Restitution</summary>
public float Restitution;
/// <summary>
/// Creates PhysicsProperties from OSD
/// </summary>
/// <param name="osd">OSDMap with incoming data</param>
/// <returns>Deserialized PhysicsProperties object</returns>
public static PhysicsProperties FromOSD(OSD osd)
{
PhysicsProperties ret = new PhysicsProperties();
if (osd is OSDMap)
{
OSDMap map = (OSDMap)osd;
ret.LocalID = map["LocalID"];
ret.Density = map["Density"];
ret.Friction = map["Friction"];
ret.GravityMultiplier = map["GravityMultiplier"];
ret.Restitution = map["Restitution"];
ret.PhysicsShapeType = (PhysicsShapeType)map["PhysicsShapeType"].AsInteger();
}
return ret;
}
/// <summary>
/// Serializes PhysicsProperties to OSD
/// </summary>
/// <returns>OSDMap with serialized PhysicsProperties data</returns>
public OSD GetOSD()
{
OSDMap map = new OSDMap(6);
map["LocalID"] = LocalID;
map["Density"] = Density;
map["Friction"] = Friction;
map["GravityMultiplier"] = GravityMultiplier;
map["Restitution"] = Restitution;
map["PhysicsShapeType"] = (int)PhysicsShapeType;
return map;
}
}
#endregion Subclasses
#region Public Members
/// <summary></summary>
public UUID ID;
/// <summary></summary>
public UUID GroupID;
/// <summary></summary>
public uint LocalID;
/// <summary></summary>
public uint ParentID;
/// <summary></summary>
public ulong RegionHandle;
/// <summary></summary>
public PrimFlags Flags;
/// <summary>Foliage type for this primitive. Only applicable if this
/// primitive is foliage</summary>
public Tree TreeSpecies;
/// <summary>Unknown</summary>
public byte[] ScratchPad;
/// <summary></summary>
public Vector3 Position;
/// <summary></summary>
public Vector3 Scale;
/// <summary></summary>
public Quaternion Rotation = Quaternion.Identity;
/// <summary></summary>
public Vector3 Velocity;
/// <summary></summary>
public Vector3 AngularVelocity;
/// <summary></summary>
public Vector3 Acceleration;
/// <summary></summary>
public Vector4 CollisionPlane;
/// <summary></summary>
public FlexibleData Flexible;
/// <summary></summary>
public LightData Light;
/// <summary></summary>
public SculptData Sculpt;
/// <summary></summary>
public ClickAction ClickAction;
/// <summary></summary>
public UUID Sound;
/// <summary>Identifies the owner if audio or a particle system is
/// active</summary>
public UUID OwnerID;
/// <summary></summary>
public SoundFlags SoundFlags;
/// <summary></summary>
public float SoundGain;
/// <summary></summary>
public float SoundRadius;
/// <summary></summary>
public string Text;
/// <summary></summary>
public Color4 TextColor;
/// <summary></summary>
public string MediaURL;
/// <summary></summary>
public JointType Joint;
/// <summary></summary>
public Vector3 JointPivot;
/// <summary></summary>
public Vector3 JointAxisOrAnchor;
/// <summary></summary>
public NameValue[] NameValues;
/// <summary></summary>
public ConstructionData PrimData;
/// <summary></summary>
public ObjectProperties Properties;
/// <summary>Objects physics engine propertis</summary>
public PhysicsProperties PhysicsProps;
/// <summary>Extra data about primitive</summary>
public object Tag;
/// <summary>Indicates if prim is attached to an avatar</summary>
public bool IsAttachment;
/// <summary>Number of clients referencing this prim</summary>
public int ActiveClients = 0;
#endregion Public Members
#region Properties
/// <summary>Uses basic heuristics to estimate the primitive shape</summary>
public PrimType Type
{
get
{
if (Sculpt != null && Sculpt.Type != SculptType.None && Sculpt.SculptTexture != UUID.Zero)
{
if (Sculpt.Type == SculptType.Mesh)
return PrimType.Mesh;
else
return PrimType.Sculpt;
}
bool linearPath = (PrimData.PathCurve == PathCurve.Line || PrimData.PathCurve == PathCurve.Flexible);
float scaleY = PrimData.PathScaleY;
if (linearPath)
{
switch (PrimData.ProfileCurve)
{
case ProfileCurve.Circle:
return PrimType.Cylinder;
case ProfileCurve.Square:
return PrimType.Box;
case ProfileCurve.IsoTriangle:
case ProfileCurve.EqualTriangle:
case ProfileCurve.RightTriangle:
return PrimType.Prism;
case ProfileCurve.HalfCircle:
default:
return PrimType.Unknown;
}
}
else
{
switch (PrimData.PathCurve)
{
case PathCurve.Flexible:
return PrimType.Unknown;
case PathCurve.Circle:
switch (PrimData.ProfileCurve)
{
case ProfileCurve.Circle:
if (scaleY > 0.75f)
return PrimType.Sphere;
else
return PrimType.Torus;
case ProfileCurve.HalfCircle:
return PrimType.Sphere;
case ProfileCurve.EqualTriangle:
return PrimType.Ring;
case ProfileCurve.Square:
if (scaleY <= 0.75f)
return PrimType.Tube;
else
return PrimType.Unknown;
default:
return PrimType.Unknown;
}
case PathCurve.Circle2:
if (PrimData.ProfileCurve == ProfileCurve.Circle)
return PrimType.Sphere;
else
return PrimType.Unknown;
default:
return PrimType.Unknown;
}
}
}
}
#endregion Properties
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public Primitive()
{
// Default a few null property values to String.Empty
Text = String.Empty;
MediaURL = String.Empty;
}
public Primitive(Primitive prim)
{
ID = prim.ID;
GroupID = prim.GroupID;
LocalID = prim.LocalID;
ParentID = prim.ParentID;
RegionHandle = prim.RegionHandle;
Flags = prim.Flags;
TreeSpecies = prim.TreeSpecies;
if (prim.ScratchPad != null)
{
ScratchPad = new byte[prim.ScratchPad.Length];
Buffer.BlockCopy(prim.ScratchPad, 0, ScratchPad, 0, ScratchPad.Length);
}
else
ScratchPad = Utils.EmptyBytes;
Position = prim.Position;
Scale = prim.Scale;
Rotation = prim.Rotation;
Velocity = prim.Velocity;
AngularVelocity = prim.AngularVelocity;
Acceleration = prim.Acceleration;
CollisionPlane = prim.CollisionPlane;
Flexible = prim.Flexible;
Light = prim.Light;
Sculpt = prim.Sculpt;
ClickAction = prim.ClickAction;
Sound = prim.Sound;
OwnerID = prim.OwnerID;
SoundFlags = prim.SoundFlags;
SoundGain = prim.SoundGain;
SoundRadius = prim.SoundRadius;
Text = prim.Text;
TextColor = prim.TextColor;
MediaURL = prim.MediaURL;
Joint = prim.Joint;
JointPivot = prim.JointPivot;
JointAxisOrAnchor = prim.JointAxisOrAnchor;
if (prim.NameValues != null)
{
if (NameValues == null || NameValues.Length != prim.NameValues.Length)
NameValues = new NameValue[prim.NameValues.Length];
Array.Copy(prim.NameValues, NameValues, prim.NameValues.Length);
}
else
NameValues = null;
PrimData = prim.PrimData;
Properties = prim.Properties;
// FIXME: Get a real copy constructor for TextureEntry instead of serializing to bytes and back
if (prim.Textures != null)
{
byte[] textureBytes = prim.Textures.GetBytes();
Textures = new TextureEntry(textureBytes, 0, textureBytes.Length);
}
else
{
Textures = null;
}
TextureAnim = prim.TextureAnim;
if (!Equals(prim.ParticleSys, default(ParticleSystem))) ParticleSys = (ParticleSystem)prim.ParticleSys.Clone();
}
public Primitive Clone()
{
var p = new Primitive(this);
return p;
}
#endregion Constructors
#region Public Methods
public virtual OSD GetOSDL()
{
OSDMap path = new OSDMap(14);
path["begin"] = OSD.FromReal(PrimData.PathBegin);
path["curve"] = OSD.FromInteger((int)PrimData.PathCurve);
path["end"] = OSD.FromReal(PrimData.PathEnd);
path["radius_offset"] = OSD.FromReal(PrimData.PathRadiusOffset);
path["revolutions"] = OSD.FromReal(PrimData.PathRevolutions);
path["scale_x"] = OSD.FromReal(PrimData.PathScaleX);
path["scale_y"] = OSD.FromReal(PrimData.PathScaleY);
path["shear_x"] = OSD.FromReal(PrimData.PathShearX);
path["shear_y"] = OSD.FromReal(PrimData.PathShearY);
path["skew"] = OSD.FromReal(PrimData.PathSkew);
path["taper_x"] = OSD.FromReal(PrimData.PathTaperX);
path["taper_y"] = OSD.FromReal(PrimData.PathTaperY);
path["twist"] = OSD.FromReal(PrimData.PathTwist);
path["twist_begin"] = OSD.FromReal(PrimData.PathTwistBegin);
OSDMap profile = new OSDMap(4);
profile["begin"] = OSD.FromReal(PrimData.ProfileBegin);
profile["curve"] = OSD.FromInteger((int)PrimData.ProfileCurve);
profile["hole"] = OSD.FromInteger((int)PrimData.ProfileHole);
profile["end"] = OSD.FromReal(PrimData.ProfileEnd);
profile["hollow"] = OSD.FromReal(PrimData.ProfileHollow);
OSDMap volume = new OSDMap(2);
volume["path"] = path;
volume["profile"] = profile;
OSDMap prim = new OSDMap(20);
if (Properties != null)
{
prim["name"] = OSD.FromString(Properties.Name);
prim["description"] = OSD.FromString(Properties.Description);
}
else
{
prim["name"] = OSD.FromString("Object");
prim["description"] = OSD.FromString(String.Empty);
}
prim["phantom"] = OSD.FromBoolean(((Flags & PrimFlags.Phantom) != 0));
prim["physical"] = OSD.FromBoolean(((Flags & PrimFlags.Physics) != 0));
prim["position"] = OSD.FromVector3(Position);
prim["rotation"] = OSD.FromQuaternion(Rotation);
prim["scale"] = OSD.FromVector3(Scale);
prim["pcode"] = OSD.FromInteger((int)PrimData.PCode);
prim["material"] = OSD.FromInteger((int)PrimData.Material);
prim["shadows"] = OSD.FromBoolean(((Flags & PrimFlags.CastShadows) != 0));
prim["state"] = OSD.FromInteger(PrimData.State);
prim["id"] = OSD.FromUUID(ID);
prim["localid"] = OSD.FromUInteger(LocalID);
prim["parentid"] = OSD.FromUInteger(ParentID);
prim["volume"] = volume;
if (Textures != null)
prim["textures"] = Textures.GetOSD();
if (Light != null)
prim["light"] = Light.GetOSD();
if (Flexible != null)
prim["flex"] = Flexible.GetOSD();
if (Sculpt != null)
prim["sculpt"] = Sculpt.GetOSD();
return prim;
}
public static bool prefixFP = true;
public virtual OSD GetOSD()
{
if (Properties != null) Properties.ApplyProperties(this);
OSDMap path = new OSDMap(14);
path["begin"] = OSD.FromReal(PrimData.PathBegin);
path["curve"] = OSD.FromInteger((int)PrimData.PathCurve);
path["end"] = OSD.FromReal(PrimData.PathEnd);
path["radius_offset"] = OSD.FromReal(PrimData.PathRadiusOffset);
path["revolutions"] = OSD.FromReal(PrimData.PathRevolutions);
path["scale_x"] = OSD.FromReal(PrimData.PathScaleX);
path["scale_y"] = OSD.FromReal(PrimData.PathScaleY);
path["shear_x"] = OSD.FromReal(PrimData.PathShearX);
path["shear_y"] = OSD.FromReal(PrimData.PathShearY);
path["skew"] = OSD.FromReal(PrimData.PathSkew);
path["taper_x"] = OSD.FromReal(PrimData.PathTaperX);
path["taper_y"] = OSD.FromReal(PrimData.PathTaperY);
path["twist"] = OSD.FromReal(PrimData.PathTwist);
path["twist_begin"] = OSD.FromReal(PrimData.PathTwistBegin);
OSDMap profile = new OSDMap(4);
profile["begin"] = OSD.FromReal(PrimData.ProfileBegin);
profile["curve"] = OSD.FromInteger((int)PrimData.ProfileCurve);
profile["hole"] = OSD.FromInteger((int)PrimData.ProfileHole);
profile["end"] = OSD.FromReal(PrimData.ProfileEnd);
profile["hollow"] = OSD.FromReal(PrimData.ProfileHollow);
OSDMap volume = new OSDMap(2);
volume["path"] = path;
volume["profile"] = profile;
OSDMap prim = new OSDMap(20);
if (Properties != null)
{
prim["name"] = OSD.FromString(Properties.Name);
prim["description"] = OSD.FromString(Properties.Description);
}
else
{
prim["name"] = OSD.FromString("Object");
prim["description"] = OSD.FromString(String.Empty);
}
prim["phantom"] = OSD.FromBoolean(((Flags & PrimFlags.Phantom) != 0));
prim["physical"] = OSD.FromBoolean(((Flags & PrimFlags.Physics) != 0));
prim["position"] = OSD.FromVector3(Position);
prim["rotation"] = OSD.FromQuaternion(Rotation);
prim["scale"] = OSD.FromVector3(Scale);
prim["pcode"] = OSD.FromInteger((int)PrimData.PCode);
prim["material"] = OSD.FromInteger((int)PrimData.Material);
prim["shadows"] = OSD.FromBoolean(((Flags & PrimFlags.CastShadows) != 0));
prim["state"] = OSD.FromInteger(PrimData.State);
prim["id"] = OSD.FromUUID(ID);
prim["localid"] = OSD.FromUInteger(LocalID);
prim["parentid"] = OSD.FromUInteger(ParentID);
prim["volume"] = volume;
if (Textures != null)
{
prim["textures"] = Textures.GetOSD();
prim["hadTextures"] = true;
}
if (Light != null)
prim["light"] = Light.GetOSD();
if (Flexible != null)
prim["flex"] = Flexible.GetOSD();
if (Sculpt != null)
prim["sculpt"] = Sculpt.GetOSD();
if (PhysicsProps != null)
prim["PhysicsProps"] = PhysicsProps.GetOSD();
var map = Serialize(prim);
if (!Equals(ParticleSys, default(ParticleSystem))) map["particalSysBytes"] = OSD.FromBinary(ParticleSys.GetBytes());
map["extraParamBytes"] = OSD.FromBinary(GetExtraParamsBytes());
if (Properties != null)
{
map["TextureIDs"] = OSD.FromArray(Properties.TextureIDs, new HashSet<object>(), prefixFP);
}
map["PrimFlags"] = (uint)Flags;
map["TreeSpecies"] = (byte)TreeSpecies;
if (NameValues != null)
{
string nvs = NameValue.NameValuesToString(NameValues);
map["NameValues"] = nvs;
}
if (Textures != null)
{
var data1 = Textures.GetBytes();
map["TexturesBytesLen"] = data1.Length;
map["TexturesBytes"] = OSD.FromBinary(data1);
}
return map;
}
public OSDMap Serialize(OSDMap map)
{
map = map ?? new OSDMap();
Properties = Properties ?? new ObjectProperties();
Properties.ApplyProperties(this);
OSD.AddObjectOSD(this, map, GetType(), true);
map["assetprimoid"] = OSD.FromBoolean(true);
map["id"] = OSD.FromUUID(ID);
//@TODO map["attachment_position"] = OSD.FromVector3(AttachmentPosition);
//@TODO map["attachment_rotation"] = OSD.FromQuaternion(AttachmentRotation);
//@TODO map["before_attachment_rotation"] = OSD.FromQuaternion(BeforeAttachmentRotation);
map["name"] = OSD.FromString(Properties.Name);
map["description"] = OSD.FromString(Properties.Description);
map["perms_base"] = OSD.FromInteger((uint)Properties.Permissions.BaseMask);
map["perms_owner"] = OSD.FromInteger((uint)Properties.Permissions.OwnerMask);
map["perms_group"] = OSD.FromInteger((uint)Properties.Permissions.GroupMask);
map["perms_everyone"] = OSD.FromInteger((uint)Properties.Permissions.EveryoneMask);
map["perms_next_owner"] = OSD.FromInteger((uint)Properties.Permissions.NextOwnerMask);
map["creator_identity"] = OSD.FromUUID(Properties.CreatorID);
map["owner_identity"] = OSD.FromUUID(OwnerID);
map["last_owner_identity"] = OSD.FromUUID(Properties.LastOwnerID);
map["group_identity"] = OSD.FromUUID(GroupID);
map["folder_id"] = OSD.FromUUID(Properties.FolderID);
map["region_handle"] = OSD.FromULong(RegionHandle);
map["click_action"] = OSD.FromInteger((byte)ClickAction);
map["last_attachment_point"] = OSD.FromInteger((byte)PrimData.AttachmentPoint);
//@TODO map["link_number"] = OSD.FromInteger(LinkNumber);
map["local_id"] = OSD.FromInteger(LocalID);
map["parent_id"] = OSD.FromInteger(ParentID);
map["position"] = OSD.FromVector3(Position);
map["rotation"] = OSD.FromQuaternion(Rotation);
map["velocity"] = OSD.FromVector3(Velocity);
map["angular_velocity"] = OSD.FromVector3(AngularVelocity);
map["acceleration"] = OSD.FromVector3(Acceleration);
map["collisionplane"] = OSD.FromVector4(CollisionPlane);
map["scale"] = OSD.FromVector3(Scale);
//@TODO map["sit_offset"] = OSD.FromVector3(SitOffset);
//@TODO map["sit_rotation"] = OSD.FromQuaternion(PrimData.SitRotation);
//@TODO map["camera_eye_offset"] = OSD.FromVector3(CameraEyeOffset);
//@TODO map["camera_at_offset"] = OSD.FromVector3(CameraAtOffset);
map["state"] = OSD.FromInteger((int)PrimData.State);
map["prim_code"] = OSD.FromInteger((int)PrimData.PCode);
map["material"] = OSD.FromInteger((int)PrimData.Material);
//@TODO map["pass_touches"] = OSD.FromBoolean(PassTouches);
map["sound_id"] = OSD.FromUUID(Sound);
map["sound_gain"] = OSD.FromReal(SoundGain);
map["sound_radius"] = OSD.FromReal(SoundRadius);
map["sound_flags"] = OSD.FromInteger((int)SoundFlags);
map["text_color"] = OSD.FromColor4(TextColor);
map["text"] = OSD.FromString(Text);
map["sit_name"] = OSD.FromString(Properties.SitName);
map["touch_name"] = OSD.FromString(Properties.TouchName);
//@TODO map["selected"] = OSD.FromBoolean(Selected);
//@TODO map["selector_id"] = OSD.FromUUID(SelectorID);
map["use_physics"] = OSD.FromBoolean(((Flags & PrimFlags.Physics) != 0));
map["phantom"] = OSD.FromBoolean(((Flags & PrimFlags.Phantom) != 0));
//@TODO map["remote_script_access_pin"] = OSD.FromInteger(RemoteScriptAccessPIN);
//@TODO map["volume_detect"] = OSD.FromBoolean(VolumeDetect);
map["die_at_edge"] = OSD.FromBoolean(((Flags & PrimFlags.DieAtEdge) != 0));
map["return_at_edge"] = OSD.FromBoolean(((Flags & PrimFlags.ReturnAtEdge) != 0));
map["temporary"] = OSD.FromBoolean(((Flags & PrimFlags.Temporary) != 0));
map["temporary_on_rez"] = OSD.FromBoolean(((Flags & PrimFlags.TemporaryOnRez) != 0));
map["sandbox"] = OSD.FromBoolean(((Flags & PrimFlags.Sandbox) != 0));
map["creation_date"] = OSD.FromDate(Properties. CreationDate);
//@TODO map["rez_date"] = OSD.FromDate(RezDate);
map["sale_price"] = OSD.FromInteger(Properties.SalePrice);
map["sale_type"] = OSD.FromInteger((int)Properties.SaleType);
if (Flexible != null)
map["flexible"] = Flexible.GetOSD();
if (Light != null)
map["light"] = Light.GetOSD();
if (Sculpt != null)
map["sculpt"] = Sculpt.GetOSD();
if (!Equals(ParticleSys, default(ParticleSystem)))
map["particles"] = ParticleSys.GetOSD();
//PrimData @todo if (Shape != null) map["shape"] = Shape.Serialize();
if (Textures != null)
map["textures"] = Textures.GetOSD();
//@todo if (Inventory != null) map["inventory"] = Inventory.Serialize();
return map;
}
public void Deserialize(OSDMap map)
{
Properties = Properties ?? new ObjectProperties();
OSD.SetObjectOSD(this, map);
if (!map["assetprimoid"].AsBoolean()) return;
ID = map["id"].AsUUID();
//@TODO AttachmentPosition = map["attachment_position"].AsVector3();
//@TODO AttachmentRotation = map["attachment_rotation"].AsQuaternion();
//@TODO BeforeAttachmentRotation = map["before_attachment_rotation"].AsQuaternion();
Properties = Properties ?? new ObjectProperties();
Properties.Name = map["name"].AsString();
Properties.Description = map["description"].AsString();
var PermsBase = (uint)map["perms_base"].AsInteger();
var PermsOwner = (uint)map["perms_owner"].AsInteger();
var PermsGroup = (uint)map["perms_group"].AsInteger();
var PermsEveryone = (uint)map["perms_everyone"].AsInteger();
var PermsNextOwner = (uint)map["perms_next_owner"].AsInteger();
Properties.Permissions = new Permissions(PermsBase, PermsEveryone, PermsGroup, PermsNextOwner, PermsOwner);
Properties.CreatorID = map["creator_identity"].AsUUID();
OwnerID = map["owner_identity"].AsUUID();
Properties.LastOwnerID = map["last_owner_identity"].AsUUID();
GroupID = map["group_identity"].AsUUID();
Properties.FolderID = map["folder_id"].AsUUID();
RegionHandle = map["region_handle"].AsULong();
ClickAction =(ClickAction) map["click_action"].AsInteger();
PrimData.AttachmentPoint = (AttachmentPoint) map["last_attachment_point"].AsInteger();
//@TODO LinkNumber = map["link_number"].AsInteger();
LocalID = (uint)map["local_id"].AsInteger();
ParentID = (uint)map["parent_id"].AsInteger();
Position = map["position"].AsVector3();
Rotation = map["rotation"].AsQuaternion();
Velocity = map["velocity"].AsVector3();
AngularVelocity = map["angular_velocity"].AsVector3();
Acceleration = map["acceleration"].AsVector3();
CollisionPlane = map["collisionplane"].AsVector4();
Scale = map["scale"].AsVector3();
//@TODO SitOffset = map["sit_offset"].AsVector3();
//@TODO SitRotation = map["sit_rotation"].AsQuaternion();
//@TODO CameraEyeOffset = map["camera_eye_offset"].AsVector3();
//@TODO CameraAtOffset = map["camera_at_offset"].AsVector3();
PrimData.State = (byte) map["state"].AsInteger();
PrimData.PCode = (PCode)map["prim_code"].AsInteger();
PrimData.Material = (Material) map["material"].AsInteger();
//@TODO PassTouches = map["pass_touches"].AsBoolean();
Sound = map["sound_id"].AsUUID();
SoundGain = (float)map["sound_gain"].AsReal();
SoundRadius = (float)map["sound_radius"].AsReal();
SoundFlags =(SoundFlags) map["sound_flags"].AsInteger();
TextColor = map["text_color"].AsColor4();
Text = map["text"].AsString();
Properties.SitName = map["sit_name"].AsString();
Properties.TouchName = map["touch_name"].AsString();
//@TODO Selected = map["selected"].AsBoolean();
//@TODO SelectorID = map["selector_id"].AsUUID();
var UsePhysics = map["use_physics"].AsBoolean();
var Phantom = map["phantom"].AsBoolean();
//@TODO RemoteScriptAccessPIN = map["remote_script_access_pin"].AsInteger();
//@TODO VolumeDetect = map["volume_detect"].AsBoolean();
var DieAtEdge = map["die_at_edge"].AsBoolean();
var ReturnAtEdge = map["return_at_edge"].AsBoolean();
var Temporary = map["temporary"].AsBoolean();
var TemporaryOnRez = map["temporary_on_rez"].AsBoolean();
var Sandbox = map["sandbox"].AsBoolean();
Properties.CreationDate = map["creation_date"].AsDate();
//@TODO RezDate = map["rez_date"].AsDate();
Properties.SalePrice = map["sale_price"].AsInteger();
Properties.SaleType = (SaleType)map["sale_type"].AsInteger();
}
public static Primitive FromOSDL(OSD osd)
{
Primitive prim = new Primitive();
Primitive.ConstructionData data = new ConstructionData();
OSDMap map = (OSDMap)osd;
OSDMap volume = (OSDMap)map["volume"];
OSDMap path = (OSDMap)volume["path"];
OSDMap profile = (OSDMap)volume["profile"];
#region Path/Profile
data.profileCurve = (byte)0;
data.Material = (Material)map["material"].AsInteger();
data.PCode = (PCode)map["pcode"].AsInteger();
data.State = (byte)map["state"].AsInteger();
data.PathBegin = (float)path["begin"].AsReal();
data.PathCurve = (PathCurve)path["curve"].AsInteger();
data.PathEnd = (float)path["end"].AsReal();
data.PathRadiusOffset = (float)path["radius_offset"].AsReal();
data.PathRevolutions = (float)path["revolutions"].AsReal();
data.PathScaleX = (float)path["scale_x"].AsReal();
data.PathScaleY = (float)path["scale_y"].AsReal();
data.PathShearX = (float)path["shear_x"].AsReal();
data.PathShearY = (float)path["shear_y"].AsReal();
data.PathSkew = (float)path["skew"].AsReal();
data.PathTaperX = (float)path["taper_x"].AsReal();
data.PathTaperY = (float)path["taper_y"].AsReal();
data.PathTwist = (float)path["twist"].AsReal();
data.PathTwistBegin = (float)path["twist_begin"].AsReal();
data.ProfileBegin = (float)profile["begin"].AsReal();
data.ProfileEnd = (float)profile["end"].AsReal();
data.ProfileHollow = (float)profile["hollow"].AsReal();
data.ProfileCurve = (ProfileCurve) profile["curve"].AsInteger();
data.ProfileHole = (HoleType) profile["hole"].AsInteger();
#endregion Path/Profile
prim.PrimData = data;
if (map["phantom"].AsBoolean())
prim.Flags |= PrimFlags.Phantom;
if (map["physical"].AsBoolean())
prim.Flags |= PrimFlags.Physics;
if (map["shadows"].AsBoolean())
prim.Flags |= PrimFlags.CastShadows;
prim.ID = map["id"].AsUUID();
prim.LocalID = map["localid"].AsUInteger();
prim.ParentID = map["parentid"].AsUInteger();
prim.Position = ((OSDArray)map["position"]).AsVector3();
prim.Rotation = ((OSDArray)map["rotation"]).AsQuaternion();
prim.Scale = ((OSDArray)map["scale"]).AsVector3();
if (map["flex"])
prim.Flexible = FlexibleData.FromOSD(map["flex"]);
if (map["light"])
prim.Light = LightData.FromOSD(map["light"]);
if (map["sculpt"])
prim.Sculpt = SculptData.FromOSD(map["sculpt"]);
prim.Textures = TextureEntry.FromOSD(map["textures"]);
prim.Properties = new ObjectProperties();
if (!string.IsNullOrEmpty(map["name"].AsString()))
{
prim.Properties.Name = map["name"].AsString();
}
if (!string.IsNullOrEmpty(map["description"].AsString()))
{
prim.Properties.Description = map["description"].AsString();
}
return prim;
}
public static Primitive FromOSD(OSD osd)
{
Primitive prim = new Primitive();
prim.Deserialize(osd as OSDMap);
Primitive.ConstructionData data = new ConstructionData();
OSDMap map = (OSDMap)osd;
OSDMap volume = (OSDMap)map["volume"];
OSDMap path = (OSDMap)volume["path"];
OSDMap profile = (OSDMap)volume["profile"];
#region Path/Profile
data.profileCurve = (byte)0;
data.Material = (Material)map["material"].AsInteger();
data.PCode = (PCode)map["pcode"].AsInteger();
data.State = (byte)map["state"].AsInteger();
data.PathBegin = (float)path["begin"].AsReal();
data.PathCurve = (PathCurve)path["curve"].AsInteger();
data.PathEnd = (float)path["end"].AsReal();
data.PathRadiusOffset = (float)path["radius_offset"].AsReal();
data.PathRevolutions = (float)path["revolutions"].AsReal();
data.PathScaleX = (float)path["scale_x"].AsReal();
data.PathScaleY = (float)path["scale_y"].AsReal();
data.PathShearX = (float)path["shear_x"].AsReal();
data.PathShearY = (float)path["shear_y"].AsReal();
data.PathSkew = (float)path["skew"].AsReal();
data.PathTaperX = (float)path["taper_x"].AsReal();
data.PathTaperY = (float)path["taper_y"].AsReal();
data.PathTwist = (float)path["twist"].AsReal();
data.PathTwistBegin = (float)path["twist_begin"].AsReal();
data.ProfileBegin = (float)profile["begin"].AsReal();
data.ProfileEnd = (float)profile["end"].AsReal();
data.ProfileHollow = (float)profile["hollow"].AsReal();
data.ProfileCurve = (ProfileCurve)profile["curve"].AsInteger();
data.ProfileHole = (HoleType)profile["hole"].AsInteger();
#endregion Path/Profile
prim.PrimData = data;
if (map["phantom"].AsBoolean())
prim.Flags |= PrimFlags.Phantom;
if (map["physical"].AsBoolean())
prim.Flags |= PrimFlags.Physics;
if (map["shadows"].AsBoolean())
prim.Flags |= PrimFlags.CastShadows;
if (map["temporary"].AsBoolean())
prim.Flags |= PrimFlags.Temporary;
if (map["temporary_on_rez"].AsBoolean())
prim.Flags |= PrimFlags.TemporaryOnRez;
if (map["die_at_edge"].AsBoolean())
prim.Flags |= PrimFlags.DieAtEdge;
if (map["return_at_edge"].AsBoolean())
prim.Flags |= PrimFlags.ReturnAtEdge;
if (map["sandbox"].AsBoolean())
prim.Flags |= PrimFlags.Sandbox;
prim.ID = map["id"].AsUUID();
prim.LocalID = map["localid"].AsUInteger();
prim.ParentID = map["parentid"].AsUInteger();
prim.Position = ((OSDArray)map["position"]).AsVector3();
prim.Rotation = ((OSDArray)map["rotation"]).AsQuaternion();
prim.Scale = ((OSDArray)map["scale"]).AsVector3();
bool boolosd = map["flex"].AsBoolean();
if (boolosd)
prim.Flexible = FlexibleData.FromOSD(map["flex"]);
if (map["light"])
prim.Light = LightData.FromOSD(map["light"]);
if (map["sculpt"])
prim.Sculpt = SculptData.FromOSD(map["sculpt"]);
if (map["hadTextures"]) prim.Textures = TextureEntry.FromOSD(map["textures"]);
prim.Properties = prim.Properties ?? new ObjectProperties();
if (!string.IsNullOrEmpty(map["name"].AsString()))
{
prim.Properties.Name = map["name"].AsString();
}
if (!string.IsNullOrEmpty(map["description"].AsString()))
{
prim.Properties.Description = map["description"].AsString();
}
if (map["extraParamBytes"]) prim.SetExtraParamsFromBytes(map["extraParamBytes"].AsBinary(), 0);
if (map["particalSysBytes"].AsBoolean())
{
prim.ParticleSys = new ParticleSystem(map["particalSysBytes"].AsBinary(), 0);
}
else
{
throw new NotImplementedException("particalSysBytes");
}
if (map["TexturesBytesLen"].AsBoolean())
{
int len = map["TexturesBytesLen"].AsInteger();
byte[] data1 = map["TexturesBytes"].AsBinary();
if (prim.Textures == null)
{
prim.Textures = new TextureEntry(data1, 0, len);
}
else
{
prim.Textures.FromBytes(data1, 0, len);
}
}
else
{
// throw new NotImplementedException("TexturesBytesLen");
}
if (map["PhysicsProps"]) prim.PhysicsProps = PhysicsProperties.FromOSD(map["PhysicsProps"]);
if (map["properties"])
{
// OSD.SetObjectOSD(prim.Properties, (OSDMap)map["properties"]);
}
if (map["TextureIDs"])
{
prim.Properties.TextureIDs = (UUID[])OSD.ToObject(typeof(UUID[]), map["TextureIDs"]);
}
if (map["PrimFlags"])
{
prim.Flags = (PrimFlags)map["PrimFlags"].AsUInteger();
}
if (map["NameValues"])
{
prim.NameValues = NameValue.ParseNameValues(map["NameValues"]);
}
prim.Properties.ApplyProperties(prim);
if (!map["flex"])
prim.Flexible = null;
if (!map["light"])
prim.Light = null;
if (!map["sculpt"])
prim.Sculpt = null;
if (!map["hadTextures"])
prim.Textures = null;
if (!map["PhysicsProps"])
prim.PhysicsProps = null;
prim.TreeSpecies = (Tree)(byte)map["TreeSpecies"].AsInteger();
return prim;
}
public int SetExtraParamsFromBytes(byte[] data, int pos)
{
int i = pos;
int totalLength = 1;
if (data.Length == 0 || pos >= data.Length)
return 0;
byte extraParamCount = data[i++];
for (int k = 0; k < extraParamCount; k++)
{
ExtraParamType type = (ExtraParamType)Utils.BytesToUInt16(data, i);
i += 2;
uint paramLength = Utils.BytesToUInt(data, i);
i += 4;
if (type == ExtraParamType.Flexible)
Flexible = new FlexibleData(data, i);
else if (type == ExtraParamType.Light)
Light = new LightData(data, i);
else if (type == ExtraParamType.Sculpt || type == ExtraParamType.Mesh)
Sculpt = new SculptData(data, i);
i += (int)paramLength;
totalLength += (int)paramLength + 6;
}
return totalLength;
}
public byte[] GetExtraParamsBytes()
{
byte[] flexible = null;
byte[] light = null;
byte[] sculpt = null;
byte[] buffer = null;
int size = 1;
int pos = 0;
byte count = 0;
if (Flexible != null)
{
flexible = Flexible.GetBytes();
size += flexible.Length + 6;
++count;
}
if (Light != null)
{
light = Light.GetBytes();
size += light.Length + 6;
++count;
}
if (Sculpt != null)
{
sculpt = Sculpt.GetBytes();
size += sculpt.Length + 6;
++count;
}
buffer = new byte[size];
buffer[0] = count;
++pos;
if (flexible != null)
{
Buffer.BlockCopy(Utils.UInt16ToBytes((ushort)ExtraParamType.Flexible), 0, buffer, pos, 2);
pos += 2;
Buffer.BlockCopy(Utils.UIntToBytes((uint)flexible.Length), 0, buffer, pos, 4);
pos += 4;
Buffer.BlockCopy(flexible, 0, buffer, pos, flexible.Length);
pos += flexible.Length;
}
if (light != null)
{
Buffer.BlockCopy(Utils.UInt16ToBytes((ushort)ExtraParamType.Light), 0, buffer, pos, 2);
pos += 2;
Buffer.BlockCopy(Utils.UIntToBytes((uint)light.Length), 0, buffer, pos, 4);
pos += 4;
Buffer.BlockCopy(light, 0, buffer, pos, light.Length);
pos += light.Length;
}
if (sculpt != null)
{
if (Sculpt.Type == SculptType.Mesh)
{
Buffer.BlockCopy(Utils.UInt16ToBytes((ushort)ExtraParamType.Mesh), 0, buffer, pos, 2);
}
else
{
Buffer.BlockCopy(Utils.UInt16ToBytes((ushort)ExtraParamType.Sculpt), 0, buffer, pos, 2);
}
pos += 2;
Buffer.BlockCopy(Utils.UIntToBytes((uint)sculpt.Length), 0, buffer, pos, 4);
pos += 4;
Buffer.BlockCopy(sculpt, 0, buffer, pos, sculpt.Length);
pos += sculpt.Length;
}
return buffer;
}
#endregion Public Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Primitive) ? this == (Primitive)obj : false;
}
public bool Equals(Primitive other)
{
return this == other;
}
public override string ToString()
{
switch (PrimData.PCode)
{
case PCode.Prim:
return String.Format("{0} ({1})", Type, ID);
default:
return String.Format("{0} ({1})", PrimData.PCode, ID);
}
}
public override int GetHashCode()
{
// Some people have been complaining that prims hashcode changes as their data changes
if (Settings.PRIMS_KEEP_HASHCODES) return LocalID.GetHashCode();
return
Position.GetHashCode() ^
Velocity.GetHashCode() ^
Acceleration.GetHashCode() ^
Rotation.GetHashCode() ^
AngularVelocity.GetHashCode() ^
ClickAction.GetHashCode() ^
(Flexible != null ? Flexible.GetHashCode() : 0) ^
(Light != null ? Light.GetHashCode() : 0) ^
(Sculpt != null ? Sculpt.GetHashCode() : 0) ^
Flags.GetHashCode() ^
PrimData.Material.GetHashCode() ^
MediaURL.GetHashCode() ^
//TODO: NameValues?
(Properties != null ? Properties.OwnerID.GetHashCode() : 0) ^
ParentID.GetHashCode() ^
PrimData.PathBegin.GetHashCode() ^
PrimData.PathCurve.GetHashCode() ^
PrimData.PathEnd.GetHashCode() ^
PrimData.PathRadiusOffset.GetHashCode() ^
PrimData.PathRevolutions.GetHashCode() ^
PrimData.PathScaleX.GetHashCode() ^
PrimData.PathScaleY.GetHashCode() ^
PrimData.PathShearX.GetHashCode() ^
PrimData.PathShearY.GetHashCode() ^
PrimData.PathSkew.GetHashCode() ^
PrimData.PathTaperX.GetHashCode() ^
PrimData.PathTaperY.GetHashCode() ^
PrimData.PathTwist.GetHashCode() ^
PrimData.PathTwistBegin.GetHashCode() ^
PrimData.PCode.GetHashCode() ^
PrimData.ProfileBegin.GetHashCode() ^
PrimData.ProfileCurve.GetHashCode() ^
PrimData.ProfileEnd.GetHashCode() ^
PrimData.ProfileHollow.GetHashCode() ^
ParticleSys.GetHashCode() ^
TextColor.GetHashCode() ^
TextureAnim.GetHashCode() ^
(Textures != null ? Textures.GetHashCode() : 0) ^
SoundRadius.GetHashCode() ^
Scale.GetHashCode() ^
Sound.GetHashCode() ^
PrimData.State.GetHashCode() ^
Text.GetHashCode() ^
TreeSpecies.GetHashCode();
}
#endregion Overrides
#region Operators
public static bool operator ==(Primitive lhs, Primitive rhs)
{
if ((Object)lhs == null || (Object)rhs == null)
{
return (Object)rhs == (Object)lhs;
}
return (lhs.ID == rhs.ID);
}
public static bool operator !=(Primitive lhs, Primitive rhs)
{
if ((Object)lhs == null || (Object)rhs == null)
{
return (Object)rhs != (Object)lhs;
}
return !(lhs.ID == rhs.ID);
}
#endregion Operators
#region Parameter Packing Methods
public static ushort PackBeginCut(float beginCut)
{
return (ushort)Math.Round(beginCut / CUT_QUANTA);
}
public static ushort PackEndCut(float endCut)
{
return (ushort)(50000 - (ushort)Math.Round(endCut / CUT_QUANTA));
}
public static byte PackPathScale(float pathScale)
{
return (byte)(200 - (byte)Math.Round(pathScale / SCALE_QUANTA));
}
public static sbyte PackPathShear(float pathShear)
{
return (sbyte)Math.Round(pathShear / SHEAR_QUANTA);
}
/// <summary>
/// Packs PathTwist, PathTwistBegin, PathRadiusOffset, and PathSkew
/// parameters in to signed eight bit values
/// </summary>
/// <param name="pathTwist">Floating point parameter to pack</param>
/// <returns>Signed eight bit value containing the packed parameter</returns>
public static sbyte PackPathTwist(float pathTwist)
{
return (sbyte)Math.Round(pathTwist / SCALE_QUANTA);
}
public static sbyte PackPathTaper(float pathTaper)
{
return (sbyte)Math.Round(pathTaper / TAPER_QUANTA);
}
public static byte PackPathRevolutions(float pathRevolutions)
{
return (byte)Math.Round((pathRevolutions - 1f) / REV_QUANTA);
}
public static ushort PackProfileHollow(float profileHollow)
{
return (ushort)Math.Round(profileHollow / HOLLOW_QUANTA);
}
#endregion Parameter Packing Methods
#region Parameter Unpacking Methods
public static float UnpackBeginCut(ushort beginCut)
{
return (float)beginCut * CUT_QUANTA;
}
public static float UnpackEndCut(ushort endCut)
{
return (float)(50000 - endCut) * CUT_QUANTA;
}
public static float UnpackPathScale(byte pathScale)
{
return (float)(200 - pathScale) * SCALE_QUANTA;
}
public static float UnpackPathShear(sbyte pathShear)
{
return (float)pathShear * SHEAR_QUANTA;
}
/// <summary>
/// Unpacks PathTwist, PathTwistBegin, PathRadiusOffset, and PathSkew
/// parameters from signed eight bit integers to floating point values
/// </summary>
/// <param name="pathTwist">Signed eight bit value to unpack</param>
/// <returns>Unpacked floating point value</returns>
public static float UnpackPathTwist(sbyte pathTwist)
{
return (float)pathTwist * SCALE_QUANTA;
}
public static float UnpackPathTaper(sbyte pathTaper)
{
return (float)pathTaper * TAPER_QUANTA;
}
public static float UnpackPathRevolutions(byte pathRevolutions)
{
return (float)pathRevolutions * REV_QUANTA + 1f;
}
public static float UnpackProfileHollow(ushort profileHollow)
{
return (float)profileHollow * HOLLOW_QUANTA;
}
#endregion Parameter Unpacking Methods
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Sql;
using Microsoft.Azure.Management.Sql.Models;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class FailoverGroupOperationsExtensions
{
/// <summary>
/// Begins creating a new Azure SQL Database Failover Group or updating
/// an existing Azure SQL Database Failover Group. To determine the
/// status of the operation call GetFailoverGroupOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating an
/// Failover Group.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupCreateOrUpdateResponse BeginCreateOrUpdate(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins creating a new Azure SQL Database Failover Group or updating
/// an existing Azure SQL Database Failover Group. To determine the
/// status of the operation call GetFailoverGroupOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating an
/// Failover Group.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupCreateOrUpdateParameters parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Begins deleting an existing Azure SQL Database Failover Group .To
/// determine the status of the operation call
/// GetFailoverGroupDeleteOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Database Failover Group belongs
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group.
/// </param>
/// <returns>
/// Response for long running Azure SQL Database Failover Group delete
/// operations.
/// </returns>
public static FailoverGroupDeleteResponse BeginDelete(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).BeginDeleteAsync(resourceGroupName, serverName, failoverGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins deleting an existing Azure SQL Database Failover Group .To
/// determine the status of the operation call
/// GetFailoverGroupDeleteOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server to which the Azure SQL
/// Database Failover Group belongs
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group.
/// </param>
/// <returns>
/// Response for long running Azure SQL Database Failover Group delete
/// operations.
/// </returns>
public static Task<FailoverGroupDeleteResponse> BeginDeleteAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.BeginDeleteAsync(resourceGroupName, serverName, failoverGroupName, CancellationToken.None);
}
/// <summary>
/// Begins the failover operation without data loss for the Azure SQL
/// Database Failover Group with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// failovered.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupFailoverResponse BeginFailover(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).BeginFailoverAsync(resourceGroupName, serverName, failoverGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins the failover operation without data loss for the Azure SQL
/// Database Failover Group with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// failovered.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupFailoverResponse> BeginFailoverAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.BeginFailoverAsync(resourceGroupName, serverName, failoverGroupName, CancellationToken.None);
}
/// <summary>
/// Begins the force failover operation without data loss for the Azure
/// SQL Database Failover Group with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// failovered.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupForceFailoverResponse BeginForceFailoverAllowDataLoss(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).BeginForceFailoverAllowDataLossAsync(resourceGroupName, serverName, failoverGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins the force failover operation without data loss for the Azure
/// SQL Database Failover Group with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// failovered.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupForceFailoverResponse> BeginForceFailoverAllowDataLossAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.BeginForceFailoverAllowDataLossAsync(resourceGroupName, serverName, failoverGroupName, CancellationToken.None);
}
/// <summary>
/// Begins adding databases to an existing Azure SQL Database Failover
/// Group. To determine the status of the operation call
/// GetFailoverGroupOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// updated.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating an
/// Failover Group.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupPatchUpdateResponse BeginPatchUpdate(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupPatchUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).BeginPatchUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Begins adding databases to an existing Azure SQL Database Failover
/// Group. To determine the status of the operation call
/// GetFailoverGroupOperationStatus.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// updated.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating an
/// Failover Group.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupPatchUpdateResponse> BeginPatchUpdateAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupPatchUpdateParameters parameters)
{
return operations.BeginPatchUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Creates a new Azure SQL Database Failover Group or updates an
/// existing Azure SQL Database Failover Group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// operated on (updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating an Azure
/// Sql Databaser Failover Group.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupCreateOrUpdateResponse CreateOrUpdate(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).CreateOrUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure SQL Database Failover Group or updates an
/// existing Azure SQL Database Failover Group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// operated on (updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating an Azure
/// Sql Databaser Failover Group.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupCreateOrUpdateResponse> CreateOrUpdateAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes the Azure SQL Database Failover Group with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// deleted.
/// </param>
/// <returns>
/// Response for long running Azure SQL Database Failover Group delete
/// operations.
/// </returns>
public static FailoverGroupDeleteResponse Delete(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).DeleteAsync(resourceGroupName, serverName, failoverGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the Azure SQL Database Failover Group with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// deleted.
/// </param>
/// <returns>
/// Response for long running Azure SQL Database Failover Group delete
/// operations.
/// </returns>
public static Task<FailoverGroupDeleteResponse> DeleteAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.DeleteAsync(resourceGroupName, serverName, failoverGroupName, CancellationToken.None);
}
/// <summary>
/// Issue the failover operation without data loss for the Azure SQL
/// Database Failover Group with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// failovered.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupFailoverResponse Failover(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).FailoverAsync(resourceGroupName, serverName, failoverGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Issue the failover operation without data loss for the Azure SQL
/// Database Failover Group with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// failovered.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupFailoverResponse> FailoverAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.FailoverAsync(resourceGroupName, serverName, failoverGroupName, CancellationToken.None);
}
/// <summary>
/// Issue the forced failover operation with data loss for the Azure
/// SQL Database Failover Group with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// force failovered.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupForceFailoverResponse ForceFailoverAllowDataLoss(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).ForceFailoverAllowDataLossAsync(resourceGroupName, serverName, failoverGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Issue the forced failover operation with data loss for the Azure
/// SQL Database Failover Group with the given name.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// force failovered.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupForceFailoverResponse> ForceFailoverAllowDataLossAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.ForceFailoverAllowDataLossAsync(resourceGroupName, serverName, failoverGroupName, CancellationToken.None);
}
/// <summary>
/// Returns information about an Azure SQL Database Failover Group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group belongs.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// retrieved.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Failover Group request.
/// </returns>
public static FailoverGroupGetResponse Get(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).GetAsync(resourceGroupName, serverName, failoverGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about an Azure SQL Database Failover Group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group belongs.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// retrieved.
/// </param>
/// <returns>
/// Represents the response to a Get Azure Sql Failover Group request.
/// </returns>
public static Task<FailoverGroupGetResponse> GetAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName)
{
return operations.GetAsync(resourceGroupName, serverName, failoverGroupName, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure SQL Database Failover Group delete
/// operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure SQL Database Failover Group delete
/// operations.
/// </returns>
public static FailoverGroupDeleteResponse GetDeleteOperationStatus(this IFailoverGroupOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).GetDeleteOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure SQL Database Failover Group delete
/// operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure SQL Database Failover Group delete
/// operations.
/// </returns>
public static Task<FailoverGroupDeleteResponse> GetDeleteOperationStatusAsync(this IFailoverGroupOperations operations, string operationStatusLink)
{
return operations.GetDeleteOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure Sql Database Failover Group Failover
/// operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupFailoverResponse GetFailoverGroupFailoverOperationStatus(this IFailoverGroupOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).GetFailoverGroupFailoverOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure Sql Database Failover Group Failover
/// operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupFailoverResponse> GetFailoverGroupFailoverOperationStatusAsync(this IFailoverGroupOperations operations, string operationStatusLink)
{
return operations.GetFailoverGroupFailoverOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure Sql Database Failover Group create or
/// update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupCreateOrUpdateResponse GetFailoverGroupOperationStatus(this IFailoverGroupOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).GetFailoverGroupOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure Sql Database Failover Group create or
/// update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupCreateOrUpdateResponse> GetFailoverGroupOperationStatusAsync(this IFailoverGroupOperations operations, string operationStatusLink)
{
return operations.GetFailoverGroupOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Gets the status of an Azure Sql Database Failover Group Patch
/// update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupPatchUpdateResponse GetFailoverGroupPatchUpdateOperationStatus(this IFailoverGroupOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).GetFailoverGroupPatchUpdateOperationStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the status of an Azure Sql Database Failover Group Patch
/// update operation.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupPatchUpdateResponse> GetFailoverGroupPatchUpdateOperationStatusAsync(this IFailoverGroupOperations operations, string operationStatusLink)
{
return operations.GetFailoverGroupPatchUpdateOperationStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// Returns information about Azure SQL Database Failover Groups.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Serve belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server in which Azure
/// SQL Database Failover Groups belong.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Failover Group request.
/// </returns>
public static FailoverGroupListResponse List(this IFailoverGroupOperations operations, string resourceGroupName, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).ListAsync(resourceGroupName, serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns information about Azure SQL Database Failover Groups.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Serve belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server in which Azure
/// SQL Database Failover Groups belong.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Failover Group request.
/// </returns>
public static Task<FailoverGroupListResponse> ListAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName)
{
return operations.ListAsync(resourceGroupName, serverName, CancellationToken.None);
}
/// <summary>
/// Updates an existing Azure SQL Database Failover Group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// updated.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for patch updating an Azure Sql
/// Databaser Failover Group.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static FailoverGroupPatchUpdateResponse PatchUpdate(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupPatchUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IFailoverGroupOperations)s).PatchUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates an existing Azure SQL Database Failover Group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.IFailoverGroupOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// Azure SQL Database Failover Group is hosted.
/// </param>
/// <param name='failoverGroupName'>
/// Required. The name of the Azure SQL Database Failover Group to be
/// updated.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for patch updating an Azure Sql
/// Databaser Failover Group.
/// </param>
/// <returns>
/// Response for long running Azure Sql Database Failover Group
/// operation.
/// </returns>
public static Task<FailoverGroupPatchUpdateResponse> PatchUpdateAsync(this IFailoverGroupOperations operations, string resourceGroupName, string serverName, string failoverGroupName, FailoverGroupPatchUpdateParameters parameters)
{
return operations.PatchUpdateAsync(resourceGroupName, serverName, failoverGroupName, parameters, CancellationToken.None);
}
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
#if true
using System;
using Microsoft.Research.Naiad.Scheduling;
using Microsoft.Research.Naiad.Runtime.Progress;
#else
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.Research.Naiad.Dataflow;
using Microsoft.Research.Naiad.Dataflow.Channels;
using Microsoft.Research.Naiad.Scheduling;
using Microsoft.Research.Naiad.Serialization;
using Microsoft.Research.Naiad.Runtime.Progress;
#endif
namespace Microsoft.Research.Naiad.Diagnostics
{
/// <summary>
/// Enumeration describing which aspect of a Naiad computation a tracing region corresponds to
/// </summary>
public enum NaiadTracingRegion
{
/// <summary>
/// Region corresponding to a flush
/// </summary>
Flush,
/// <summary>
/// Region corresponding to a send
/// </summary>
Send,
/// <summary>
/// Region corresponding to a TCP message broadcast
/// </summary>
BroadcastTCP,
/// <summary>
/// Region corresponding to a UDP message broadcast
/// </summary>
BroadcastUDP,
/// <summary>
/// Region corresponding to a reachability computation
/// </summary>
Reachability,
/// <summary>
/// Region corresponding to codegen
/// </summary>
Compile,
/// <summary>
/// Region corresponding to waking up dormant workers
/// </summary>
Wakeup,
/// <summary>
/// Region corresponding to setting events to wake up dormant workers
/// </summary>
SetEvent,
/// <summary>
/// Unclassifed region
/// </summary>
Unspecified
}
#if true
internal class NaiadTracing
{
public static NaiadTracing Trace = new NaiadTracing();
public void RegionStart(NaiadTracingRegion region) { }
public void RegionStop(NaiadTracingRegion region) { }
public void ChannelInfo(int channel, int src, int dst, bool isExchange, bool isProgress) { }
public void ProcessInfo(int id, string name) { }
public void StageInfo(int id, string name) { }
public void VertexPlacement(int stageid, int vertexid, int proc, int worker) { }
public void LockInfo(Object obj, string name) { }
public void LockAcquire(Object obj) { }
public void LockHeld(Object obj) { }
public void LockRelease(Object obj) { }
public void ThreadName(string name, params object[] args) { }
public void SocketError(System.Net.Sockets.SocketError err) { }
public void MsgSend(int channel, int seqno, int len, int src, int dst) { }
public void MsgRecv(int channel, int seqno, int len, int src, int dst) { }
internal void StartSched(Scheduler.WorkItem workitem) { }
internal void StopSched(Scheduler.WorkItem workitem) { }
public void RefAlignFrontier() { }
public void AdvanceFrontier(Pointstamp[] frontier) { }
}
/// <summary>
/// This class containes methods that allow Mark events to be posted in the ETW Kernel Logger session.
/// </summary>
public class KernelLoggerTracing
{
/// <summary>
/// Formats and then writes a freetext Mark event into the ETW Kernel Logger trace session.
/// This event is expensive and should be used sparingly.
/// </summary>
/// <param name="msg">The format string to be logged, as in String.Format</param>
/// <param name="args">Arguments to be formatted.</param>
public static void PostKernelLoggerMarkEvent(string msg, params object[] args) { }
}
#else
/// <summary>
/// ETW provider for Naiad
/// GUID is 0ad7158e-b717-53ae-c71a-6f41ab15fe16
/// </summary>
///
// Some stuff to remember about the EventSource class:
// - Anything returning void will be considered an Event unless given the NonEvent attribute
// - Events can only have primitive types as arguments
[EventSource(Name = "Naiad")]
internal class NaiadTracing : EventSource
{
public static NaiadTracing Trace = new NaiadTracing();
public NaiadTracing()
: base(true)
{
Logging.Progress("Naiad provider guid = {0}", this.Guid);
Logging.Progress("Naiad provider enabled = {0}", this.IsEnabled());
this.DumpManifestToFile("naiadprovider.xml");
}
protected override void OnEventCommand(EventCommandEventArgs command)
{
//Logging.Progress("OnEventCommand: {0} {1}", command.Command, command.Arguments);
base.OnEventCommand(command);
}
/// <summary>
/// Identifies the Naiad subsystem the event pertains to
/// </summary>
public class Tasks
{
public const EventTask Channels = (EventTask)1;
public const EventTask Scheduling = (EventTask)2;
public const EventTask Control = (EventTask)3;
public const EventTask Locks = (EventTask)4;
public const EventTask Graph = (EventTask)5;
}
/// <summary>
/// Defines logical groups of events that can be turned on and off independently
/// </summary>
public class Keywords
{
public const EventKeywords Debug = (EventKeywords)0x0001;
public const EventKeywords Measurement = (EventKeywords)0x0002;
public const EventKeywords Network = (EventKeywords)0x0004;
public const EventKeywords Scheduling = (EventKeywords)0x0008;
public const EventKeywords Viz = (EventKeywords)0x0010;
public const EventKeywords Locks = (EventKeywords)0x0020;
public const EventKeywords GraphMetaData = (EventKeywords)0x0040;
}
#region Channels
/// <summary>
/// Generates an ETW event for message send.
/// Does nothing if there is no listener for the Network or Viz keywords of the NaiadTracing provider.
/// <param name="channel">Id of the channel the message is sent on</param>
/// <param name="seqno">Sequence number in the message header</param>
/// <param name="len">Length value in the message header</param>
/// <param name="src">Source vertex id</param>
/// <param name="dst">Destination vertex id</param>
/// </summary>
[Conditional("TRACING_ON")]
[Event(104, Task = Tasks.Channels, Opcode = EventOpcode.Send, Keywords = Keywords.Network | Keywords.Viz)]
public void MsgSend(int channel, int seqno, int len, int src, int dst)
{
if (Trace.IsEnabled(EventLevel.LogAlways, Keywords.Network | Keywords.Viz))
{
WriteEvent(104, channel, seqno, len, src, dst);
}
}
/// <summary>
/// Generates an ETW event for message receive.
/// Does nothing if there is no listener for the Network or Viz keywords of the NaiadTracing provider.
/// <param name="channel">Id of the channel the message is received on</param>
/// <param name="seqno">Sequence number in the message header</param>
/// <param name="len">Length value in the message header</param>
/// <param name="src">Source vertex id</param>
/// <param name="dst">Destination vertex id</param>
/// </summary>
[Conditional("TRACING_ON")]
[Event(105, Task = Tasks.Channels, Opcode = EventOpcode.Send, Keywords = Keywords.Network | Keywords.Viz)]
public void MsgRecv(int channel, int seqno, int len, int src, int dst)
{
if (Trace.IsEnabled(EventLevel.LogAlways, Keywords.Network | Keywords.Viz))
{
WriteEvent(105, channel, seqno, len, src, dst);
}
}
#endregion Channels
#region Scheduling
/// <summary>
/// Generates an ETW event for the scheduling of a work item.
/// Does nothing if there is no listener for the Viz keyword of the NaiadTracing provider.
/// </summary>
/// <param name="workitem">Item being scheduled</param>
[NonEvent]
[Conditional("TRACING_ON")]
internal void StartSched(Scheduler.WorkItem workitem)
{
if (Trace.IsEnabled(EventLevel.LogAlways, Keywords.Scheduling | Keywords.Viz))
StartSched(workitem.Vertex.Stage.StageId);
}
[Event(200, Task = Tasks.Scheduling, Opcode = EventOpcode.Start, Keywords = Keywords.Scheduling | Keywords.Viz)]
private void StartSched(int stageid)
{
WriteEvent(200, stageid);
}
/// <summary>
/// Generates an ETW event for the end of a scheduling period of a work item.
/// Does nothing if there is no listener for the Viz keyword of the NaiadTracing provider.
/// </summary>
/// <param name="workitem">Item being descheduled</param>
[NonEvent]
[Conditional("TRACING_ON")]
internal void StopSched(Scheduler.WorkItem workitem)
{
//Console.WriteLine("]Sched {0} {1}", id, workitem.ToString());
if (Trace.IsEnabled(EventLevel.LogAlways, Keywords.Scheduling | Keywords.Viz))
StopSched(workitem.Vertex.Stage.StageId);
}
[Event(201, Task = Tasks.Scheduling, Opcode = EventOpcode.Stop, Keywords = (Keywords.Scheduling | Keywords.Viz))]
private void StopSched(int stageid)
{
WriteEvent(201, stageid);
}
#endregion Scheduling
#region Control
[Event(300, Task = Tasks.Control, Opcode = EventOpcode.Info, Keywords = Keywords.Viz)]
public void RefAlignFrontier()
{
if (Trace.IsEnabled(EventLevel.LogAlways, Keywords.Viz))
WriteEvent(300);
}
/// <summary>
/// Generates an ETW event for frontier advance.
/// Does nothing if there is no listener for the Viz keyword of the NaiadTracing provider.
/// </summary>
/// <param name="frontier">The new PCS frontier</param>
[NonEvent]
[Conditional("TRACING_ON")]
public void AdvanceFrontier(Pointstamp[] frontier)
{
if (Trace.IsEnabled(EventLevel.LogAlways, Keywords.Viz))
AdvanceFrontier(frontier.Select(x => x.ToString()).Aggregate((x, y) => x + " " + y));
}
[Event(301, Task = Tasks.Control, Opcode = EventOpcode.Info, Keywords = Keywords.Viz)]
private void AdvanceFrontier(string newFrontier)
{
WriteEvent(301, newFrontier);
}
[NonEvent]
[Conditional("TRACING_ON")]
public void SocketError(System.Net.Sockets.SocketError err)
{
if (Trace.IsEnabled(EventLevel.Error, Keywords.Viz | Keywords.Network | Keywords.Debug))
{
SocketError(Enum.GetName(typeof(System.Net.Sockets.SocketError), err));
}
}
[Event(302, Task = Tasks.Control, Opcode = EventOpcode.Info, Keywords = Keywords.Viz | Keywords.Network | Keywords.Debug)]
private void SocketError(string msg)
{
WriteEvent(302, msg);
}
[NonEvent]
[Conditional("TRACING_ON")]
public void RegionStart(NaiadTracingRegion region)
{
if (Trace.IsEnabled(EventLevel.Error, Keywords.Viz | Keywords.Network | Keywords.Debug))
{
if (!regionInfoEventsPosted)
{
RegionInfo();
}
RegionStart((int)region);
}
}
[Event(303, Task = Tasks.Control, Opcode = EventOpcode.Info, Keywords = Keywords.Viz | Keywords.Debug)]
private void RegionStart(int id)
{
WriteEvent(303, id);
}
[NonEvent]
[Conditional("TRACING_ON")]
public void RegionStop(NaiadTracingRegion region)
{
if (Trace.IsEnabled(EventLevel.Error, Keywords.Viz | Keywords.Network | Keywords.Debug))
{
if (!regionInfoEventsPosted)
{
RegionInfo();
}
RegionStop((int)region);
}
}
[Event(304, Task = Tasks.Control, Opcode = EventOpcode.Info, Keywords = Keywords.Viz | Keywords.Debug)]
private void RegionStop(int id)
{
WriteEvent(304, id);
}
private bool regionInfoEventsPosted = false;
[Event(305, Task = Tasks.Control, Opcode = EventOpcode.Info, Keywords = Keywords.Viz | Keywords.Debug)]
[Conditional("TRACING_ON")]
private void RegionInfo()
{
foreach (var val in Enum.GetValues(typeof(NaiadTracingRegion)))
{
WriteEvent(305, val, Enum.GetName(typeof(NaiadTracingRegion), val));
}
regionInfoEventsPosted = true;
}
#endregion Control
#region Graph
[Event(500, Task = Tasks.Graph, Opcode = EventOpcode.Info, Keywords = Keywords.Viz | Keywords.GraphMetaData)]
[Conditional("TRACING_ON")]
public void StageInfo(int id, string name)
{
if (Trace.IsEnabled(EventLevel.LogAlways, Keywords.Viz | Keywords.GraphMetaData))
WriteEvent(500, id, name);
}
/// <summary>
/// Posts an event describing the placement of a vertex
/// </summary>
/// <param name="stageid">Stage id</param>
/// <param name="vertexid">Vertex id</param>
/// <param name="proc">Naiad process id</param>
/// <param name="worker">Worker thread id</param>
[Event(501, Task = Tasks.Graph, Opcode = EventOpcode.Info, Keywords = Keywords.Viz | Keywords.GraphMetaData)]
[Conditional("TRACING_ON")]
public void VertexPlacement(int stageid, int vertexid, int proc, int worker)
{
if (Trace.IsEnabled(EventLevel.LogAlways, Keywords.Viz | Keywords.GraphMetaData))
WriteEvent(501, stageid, vertexid, proc, worker);
}
/// <summary>
/// Posts channel info metadata event
/// </summary>
/// <param name="channel">Channel id</param>
/// <param name="src">Source stage id</param>
/// <param name="dst">Destination stage id</param>
/// <param name="isExchange">True if an exchange channel (otherwise a pipeline channel)</param>
/// <param name="isProgress">True if a progress channel (otherwise a data channel)</param>
[Event(502, Task = Tasks.Graph, Opcode = EventOpcode.Info, Keywords = Keywords.Viz | Keywords.GraphMetaData)]
[Conditional("TRACING_ON")]
public void ChannelInfo(int channel, int src, int dst, bool isExchange, bool isProgress)
{
if (Trace.IsEnabled(EventLevel.LogAlways, Keywords.Viz | Keywords.GraphMetaData))
WriteEvent(502, channel, src, dst, isExchange, isProgress);
}
/// <summary>
/// Posts a friendly name for the calling thread.
/// Note that this tracing event is not conditionally compiled because we want these events to appear
/// even when not tracing Naiad specifically.
/// </summary>
/// <param name="name">Name for this thread (usually to be displayed in a visualization of the trace)</param>
/// <param name="args">Any formatting args</param>
[NonEvent]
public void ThreadName(string name, params object[] args)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat(name, args);
ThreadName(sb.ToString());
}
[Event(503, Task = Tasks.Graph, Opcode = EventOpcode.Info, Keywords = Keywords.Viz)]
private void ThreadName(string name)
{
WriteEvent(503, name);
}
/// <summary>
/// Posts the Naiad process id and the name of the local machine.
/// </summary>
/// <param name="id">Naiad process id</param>
/// <param name="name">Local machine name</param>
[Event(504, Task = Tasks.Graph, Opcode = EventOpcode.Info, Keywords = Keywords.Viz | Keywords.GraphMetaData)]
[Conditional("TRACING_ON")]
public void ProcessInfo(int id, string name)
{
WriteEvent(504, id, name);
}
#endregion Graph
#region Locking
[NonEvent]
[Conditional("TRACE_LOCKS")]
public void LockInfo(Object obj, string name)
{
if (Trace.IsEnabled(EventLevel.Verbose, Keywords.Locks))
LockInfo(obj.GetHashCode(), name);
}
[Event(400, Task = Tasks.Locks, Opcode = EventOpcode.Info, Keywords = Keywords.Locks, Level = EventLevel.Verbose)]
private void LockInfo(int id, string name)
{
WriteEvent(400, id, name);
}
[NonEvent]
[Conditional("TRACE_LOCKS")]
public void LockAcquire(Object obj)
{
if (Trace.IsEnabled(EventLevel.Verbose, Keywords.Locks))
LockAcquire(obj.GetHashCode());
}
[Event(401, Task = Tasks.Locks, Opcode = EventOpcode.Info, Keywords = Keywords.Locks, Level = EventLevel.Verbose)]
private void LockAcquire(int id)
{
WriteEvent(401, id);
}
[NonEvent]
[Conditional("TRACE_LOCKS")]
public void LockHeld(Object obj)
{
if (Trace.IsEnabled(EventLevel.Verbose, Keywords.Locks))
LockHeld(obj.GetHashCode());
}
[Event(402, Task = Tasks.Locks, Opcode = EventOpcode.Info,
Keywords = Keywords.Locks, Level = EventLevel.Verbose)]
private void LockHeld(int id)
{
WriteEvent(402, id);
}
[NonEvent]
[Conditional("TRACE_LOCKS")]
public void LockRelease(Object obj)
{
if (Trace.IsEnabled(EventLevel.Verbose, Keywords.Locks))
LockRelease(obj.GetHashCode());
}
[Event(403, Task = Tasks.Locks, Opcode = EventOpcode.Info, Keywords = Keywords.Locks, Level = EventLevel.Verbose)]
private void LockRelease(int id)
{
WriteEvent(403, id);
}
#endregion
#region Misc utilities
/// <summary>
/// Writes the XML manifest of the Naiad ETW provider to a file.
/// This method is not thread-safe, but will catch exceptions and do nothing.
/// </summary>
/// <param name="filename">File to write to</param>
[NonEvent]
public void DumpManifestToFile(string filename)
{
try
{
using (var s = new StreamWriter(File.Open(filename, FileMode.Create)))
{
s.Write(NaiadTracing.GenerateManifest(typeof(NaiadTracing), "Naiad.dll"));
}
}
catch (Exception e)
{
Logging.Error("Error dumping ETW provider manifest: {0}", e.Message);
}
}
/// <summary>
/// DIY versions of WriteEvent to avoid the slow path.
/// See http://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.writeeventcore(v=vs.110).aspx.
/// </summary>
/// <param name="eventId"></param>
/// <param name="arg1"></param>
/// <param name="arg2"></param>
/// <param name="arg3"></param>
/// <param name="arg4"></param>
/// <param name="arg5"></param>
protected unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3, int arg4, int arg5)
{
EventSource.EventData* dataDesc = stackalloc EventSource.EventData[1];
int* data = stackalloc int[6];
data[0] = arg1;
data[1] = arg2;
data[2] = arg3;
data[3] = arg4;
data[4] = arg5;
dataDesc[0].DataPointer = (IntPtr)data;
dataDesc[0].Size = 4*5;
WriteEventCore(eventId, 1, dataDesc);
}
#endregion Misc utilities
}
/// <summary>
/// This class containes methods that allow Mark events to be posted in the ETW Kernel Logger session.
/// </summary>
public class KernelLoggerTracing
{
private static object _lock = new object();
private static bool _inited = false;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
private struct ETW_SET_MARK_INFORMATION
{
public Int32 Flag;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public String Mark;
};
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
private struct ETW_SET_BINARY_MARK_INFORMATION
{
public Int32 Flag;
public char Op;
public UInt64 Key;
};
[DllImport("ntdll", ExactSpelling = true, SetLastError = false)]
private static extern Int32 EtwSetMark(Int64 handle, ref ETW_SET_MARK_INFORMATION smi, Int32 size);
// Another name for the same entry point so we can overload
[DllImport("ntdll", ExactSpelling = true, EntryPoint = "EtwSetMark", SetLastError = false)]
private static extern Int32 EtwSetBinaryMark(Int64 handle, ref ETW_SET_BINARY_MARK_INFORMATION smi, Int32 size);
[DllImport("ntdll", ExactSpelling = true, SetLastError = false)]
unsafe private static extern Int32 EtwSetMark(Int64 handle, byte* buf, Int32 size);
private const UInt32 ETW_NT_FLAGS_TRACE_MARK = 6; // from sdpublic/internal/base/inc/ntwmi.h
// Initialise ETW logging
// Return true if initialization actually happened
private static bool _initEtwMarks()
{
bool res = false;
lock (_lock)
{
if (!_inited)
{
_inited = true;
res = true;
}
}
return res;
}
// Generate ETW Mark event using Naiad thread id, current operator name and message
private static void _etwMark(ref Logging.LogInfo info, string msg)
{
if (!_inited)
{
_initEtwMarks();
}
String m = String.Format("{0}, {1}, {2}\n", info.ThreadId, info.OperatorName, msg);
ETW_SET_MARK_INFORMATION smi = new ETW_SET_MARK_INFORMATION();
smi.Flag = 0;
smi.Mark = m;
var s = Marshal.SizeOf(smi);
var ret = EtwSetMark(0, ref smi, 4 + smi.Mark.Length);
}
// Generate raw ETW Mark event
private static void _etwMark(string msg)
{
if (!_inited)
{
_initEtwMarks();
}
ETW_SET_MARK_INFORMATION smi = new ETW_SET_MARK_INFORMATION();
smi.Flag = 0;
smi.Mark = msg;
var s = Marshal.SizeOf(smi);
var ret = EtwSetMark(0, ref smi, 4 + smi.Mark.Length);
}
// Generate raw binary ETW Mark event
private static void _etwBinaryMark(char op, UInt64 key)
{
ETW_SET_BINARY_MARK_INFORMATION smi = new ETW_SET_BINARY_MARK_INFORMATION();
smi.Flag = 0;
smi.Op = op;
smi.Key = key;
var ret = EtwSetBinaryMark(0, ref smi, 4 + 1 + 8);
}
/// <summary>
/// Message producer ETW event.
/// Generates mark event containing the character '+' followed by a 64-bit key constructed from the arguments.
/// Post-processing (eg by ViewEtl) will use the key to match message producer and consumer events.
/// </summary>
/// <param name="args">Array of bytes, must be size 8</param>
[Conditional("TRACING_ON")]
public static void TraceProducer(params byte[] args)
{
ulong key = 0;
for (int i = 0; i < args.Length; i++)
{
ulong foo = ((ulong)args[i] & 0xFF) << (i * 8);
key = key | foo;
//Console.Write("args[{0}]={1:x} ", i, args[i]);
}
//Console.WriteLine("key={0:x}", key);
_etwBinaryMark('+', key);
}
/// <summary>
/// Message consumer ETW event.
/// Generates mark event containing the character '-' followed by a 64-bit key constructed from the arguments.
/// Post-processing (eg by ViewEtl) will use the key to match message producer and consumer events.
/// </summary>
/// <param name="args">Array of bytes, must be size 8</param>
[Conditional("TRACING_ON")]
public static void TraceConsumer(params byte[] args)
{
ulong key = 0;
for (int i = 0; i < args.Length; i++)
{
ulong foo = ((ulong)args[i] & 0xFF) << (i * 8);
key = key | foo;
//Console.Write("args[{0}]={1:x} ", i, args[i]);
}
//Console.WriteLine("key={0:x}", key);
_etwBinaryMark('-', key);
}
// Wrap up a byte array and a stringbuilder which we will reuse frequently
internal class TracingBuffer
{
public byte[] buf;
public StringBuilder sb;
public TracingBuffer()
{
buf = new byte[4 + 128];
buf[0] = buf[1] = buf[2] = buf[3] = 0;
sb = new StringBuilder(128);
}
unsafe public void Trace(string msg, params object[] args)
{
if (!_inited)
{
_initEtwMarks();
}
sb.AppendFormat(msg, args);
for (int i = 0; i < Math.Min(sb.Length, buf.Length - 4); i++)
{
buf[i + 4] = (byte)sb[i];
}
fixed (byte* ptr = buf)
{
EtwSetMark(0, ptr, Math.Min(4 + sb.Length, buf.Length));
}
sb.Clear();
}
unsafe public void Trace(string msg)
{
if (!_inited)
{
_initEtwMarks();
}
for (int i = 0; i < msg.Length && i + 4 < buf.Length; i++)
{
buf[i + 4] = (byte) msg[i];
}
fixed (byte* ptr = buf)
{
EtwSetMark(0, ptr, Math.Min(4 + msg.Length, buf.Length));
}
}
}
// Per-thread instances of TracingBuffer;
private static ThreadLocal<TracingBuffer> tracingBuffer = new ThreadLocal<TracingBuffer>(() => new TracingBuffer());
/// <summary>
/// Formats and then writes a freetext Mark event into the ETW Kernel Logger trace session.
/// This event is expensive and should be used sparingly.
/// </summary>
/// <param name="msg">The format string to be logged, as in String.Format</param>
/// <param name="args">Arguments to be formatted.</param>
[Conditional("TRACING_ON")]
public static void PostKernelLoggerMarkEvent(string msg, params object[] args)
{
var tb = tracingBuffer.Value;
tb.Trace(msg, args);
}
/// <summary>
/// Writes a freetext Mark event into the ETW Kernel Logger trace session.
/// This event is expensive and should be used sparingly.
/// </summary>
/// <param name="msg">message</param>
[Conditional("TRACING_ON")]
public static void PostKernelLoggerMarkEvent(string msg)
{
var tb = tracingBuffer.Value;
tb.Trace(msg);
}
}
#endif
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Nop.Core.Domain.Common;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Discounts;
using Nop.Core.Domain.Payments;
using Nop.Core.Domain.Shipping;
using Nop.Core.Domain.Tax;
namespace Nop.Core.Domain.Orders
{
/// <summary>
/// Represents an order
/// </summary>
public partial class Order : BaseEntity
{
private ICollection<DiscountUsageHistory> _discountUsageHistory;
private ICollection<GiftCardUsageHistory> _giftCardUsageHistory;
private ICollection<OrderNote> _orderNotes;
private ICollection<OrderItem> _orderItems;
private ICollection<Shipment> _shipments;
#region Utilities
protected virtual SortedDictionary<decimal, decimal> ParseTaxRates(string taxRatesStr)
{
var taxRatesDictionary = new SortedDictionary<decimal, decimal>();
if (String.IsNullOrEmpty(taxRatesStr))
return taxRatesDictionary;
string[] lines = taxRatesStr.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
if (String.IsNullOrEmpty(line.Trim()))
continue;
string[] taxes = line.Split(new [] { ':' });
if (taxes.Length == 2)
{
try
{
decimal taxRate = decimal.Parse(taxes[0].Trim(), CultureInfo.InvariantCulture);
decimal taxValue = decimal.Parse(taxes[1].Trim(), CultureInfo.InvariantCulture);
taxRatesDictionary.Add(taxRate, taxValue);
}
catch (Exception exc)
{
Debug.WriteLine(exc.ToString());
}
}
}
//add at least one tax rate (0%)
if (!taxRatesDictionary.Any())
taxRatesDictionary.Add(decimal.Zero, decimal.Zero);
return taxRatesDictionary;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the order identifier
/// </summary>
public Guid OrderGuid { get; set; }
/// <summary>
/// Gets or sets the store identifier
/// </summary>
public int StoreId { get; set; }
/// <summary>
/// Gets or sets the customer identifier
/// </summary>
public int CustomerId { get; set; }
/// <summary>
/// Gets or sets the billing address identifier
/// </summary>
public int BillingAddressId { get; set; }
/// <summary>
/// Gets or sets the shipping address identifier
/// </summary>
public int? ShippingAddressId { get; set; }
/// <summary>
/// Gets or sets the pickup address identifier
/// </summary>
public int? PickupAddressId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether a customer chose "pick up in store" shipping option
/// </summary>
public bool PickUpInStore { get; set; }
/// <summary>
/// Gets or sets an order status identifier
/// </summary>
public int OrderStatusId { get; set; }
/// <summary>
/// Gets or sets the shipping status identifier
/// </summary>
public int ShippingStatusId { get; set; }
/// <summary>
/// Gets or sets the payment status identifier
/// </summary>
public int PaymentStatusId { get; set; }
/// <summary>
/// Gets or sets the payment method system name
/// </summary>
public string PaymentMethodSystemName { get; set; }
/// <summary>
/// Gets or sets the customer currency code (at the moment of order placing)
/// </summary>
public string CustomerCurrencyCode { get; set; }
/// <summary>
/// Gets or sets the currency rate
/// </summary>
public decimal CurrencyRate { get; set; }
/// <summary>
/// Gets or sets the customer tax display type identifier
/// </summary>
public int CustomerTaxDisplayTypeId { get; set; }
/// <summary>
/// Gets or sets the VAT number (the European Union Value Added Tax)
/// </summary>
public string VatNumber { get; set; }
/// <summary>
/// Gets or sets the order subtotal (incl tax)
/// </summary>
public decimal OrderSubtotalInclTax { get; set; }
/// <summary>
/// Gets or sets the order subtotal (excl tax)
/// </summary>
public decimal OrderSubtotalExclTax { get; set; }
/// <summary>
/// Gets or sets the order subtotal discount (incl tax)
/// </summary>
public decimal OrderSubTotalDiscountInclTax { get; set; }
/// <summary>
/// Gets or sets the order subtotal discount (excl tax)
/// </summary>
public decimal OrderSubTotalDiscountExclTax { get; set; }
/// <summary>
/// Gets or sets the order shipping (incl tax)
/// </summary>
public decimal OrderShippingInclTax { get; set; }
/// <summary>
/// Gets or sets the order shipping (excl tax)
/// </summary>
public decimal OrderShippingExclTax { get; set; }
/// <summary>
/// Gets or sets the payment method additional fee (incl tax)
/// </summary>
public decimal PaymentMethodAdditionalFeeInclTax { get; set; }
/// <summary>
/// Gets or sets the payment method additional fee (excl tax)
/// </summary>
public decimal PaymentMethodAdditionalFeeExclTax { get; set; }
/// <summary>
/// Gets or sets the tax rates
/// </summary>
public string TaxRates { get; set; }
/// <summary>
/// Gets or sets the order tax
/// </summary>
public decimal OrderTax { get; set; }
/// <summary>
/// Gets or sets the order discount (applied to order total)
/// </summary>
public decimal OrderDiscount { get; set; }
/// <summary>
/// Gets or sets the order total
/// </summary>
public decimal OrderTotal { get; set; }
/// <summary>
/// Gets or sets the refunded amount
/// </summary>
public decimal RefundedAmount { get; set; }
/// <summary>
/// Gets or sets the reward points history entry identifier when reward points were earned (gained) for placing this order
/// </summary>
public int? RewardPointsHistoryEntryId { get; set; }
/// <summary>
/// Gets or sets the checkout attribute description
/// </summary>
public string CheckoutAttributeDescription { get; set; }
/// <summary>
/// Gets or sets the checkout attributes in XML format
/// </summary>
public string CheckoutAttributesXml { get; set; }
/// <summary>
/// Gets or sets the customer language identifier
/// </summary>
public int CustomerLanguageId { get; set; }
/// <summary>
/// Gets or sets the affiliate identifier
/// </summary>
public int AffiliateId { get; set; }
/// <summary>
/// Gets or sets the customer IP address
/// </summary>
public string CustomerIp { get; set; }
/// <summary>
/// Gets or sets a value indicating whether storing of credit card number is allowed
/// </summary>
public bool AllowStoringCreditCardNumber { get; set; }
/// <summary>
/// Gets or sets the card type
/// </summary>
public string CardType { get; set; }
/// <summary>
/// Gets or sets the card name
/// </summary>
public string CardName { get; set; }
/// <summary>
/// Gets or sets the card number
/// </summary>
public string CardNumber { get; set; }
/// <summary>
/// Gets or sets the masked credit card number
/// </summary>
public string MaskedCreditCardNumber { get; set; }
/// <summary>
/// Gets or sets the card CVV2
/// </summary>
public string CardCvv2 { get; set; }
/// <summary>
/// Gets or sets the card expiration month
/// </summary>
public string CardExpirationMonth { get; set; }
/// <summary>
/// Gets or sets the card expiration year
/// </summary>
public string CardExpirationYear { get; set; }
/// <summary>
/// Gets or sets the authorization transaction identifier
/// </summary>
public string AuthorizationTransactionId { get; set; }
/// <summary>
/// Gets or sets the authorization transaction code
/// </summary>
public string AuthorizationTransactionCode { get; set; }
/// <summary>
/// Gets or sets the authorization transaction result
/// </summary>
public string AuthorizationTransactionResult { get; set; }
/// <summary>
/// Gets or sets the capture transaction identifier
/// </summary>
public string CaptureTransactionId { get; set; }
/// <summary>
/// Gets or sets the capture transaction result
/// </summary>
public string CaptureTransactionResult { get; set; }
/// <summary>
/// Gets or sets the subscription transaction identifier
/// </summary>
public string SubscriptionTransactionId { get; set; }
/// <summary>
/// Gets or sets the paid date and time
/// </summary>
public DateTime? PaidDateUtc { get; set; }
/// <summary>
/// Gets or sets the shipping method
/// </summary>
public string ShippingMethod { get; set; }
/// <summary>
/// Gets or sets the shipping rate computation method identifier or the pickup point provider identifier (if PickUpInStore is true)
/// </summary>
public string ShippingRateComputationMethodSystemName { get; set; }
/// <summary>
/// Gets or sets the serialized CustomValues (values from ProcessPaymentRequest)
/// </summary>
public string CustomValuesXml { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity has been deleted
/// </summary>
public bool Deleted { get; set; }
/// <summary>
/// Gets or sets the date and time of order creation
/// </summary>
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the custom order number without prefix
/// </summary>
public string CustomOrderNumber { get; set; }
#endregion
#region Navigation properties
/// <summary>
/// Gets or sets the customer
/// </summary>
public virtual Customer Customer { get; set; }
/// <summary>
/// Gets or sets the billing address
/// </summary>
public virtual Address BillingAddress { get; set; }
/// <summary>
/// Gets or sets the shipping address
/// </summary>
public virtual Address ShippingAddress { get; set; }
/// <summary>
/// Gets or sets the pickup address
/// </summary>
public virtual Address PickupAddress { get; set; }
/// <summary>
/// Gets or sets the reward points history record (spent by a customer when placing this order)
/// </summary>
public virtual RewardPointsHistory RedeemedRewardPointsEntry { get; set; }
/// <summary>
/// Gets or sets discount usage history
/// </summary>
public virtual ICollection<DiscountUsageHistory> DiscountUsageHistory
{
get { return _discountUsageHistory ?? (_discountUsageHistory = new List<DiscountUsageHistory>()); }
protected set { _discountUsageHistory = value; }
}
/// <summary>
/// Gets or sets gift card usage history (gift card that were used with this order)
/// </summary>
public virtual ICollection<GiftCardUsageHistory> GiftCardUsageHistory
{
get { return _giftCardUsageHistory ?? (_giftCardUsageHistory = new List<GiftCardUsageHistory>()); }
protected set { _giftCardUsageHistory = value; }
}
/// <summary>
/// Gets or sets order notes
/// </summary>
public virtual ICollection<OrderNote> OrderNotes
{
get { return _orderNotes ?? (_orderNotes = new List<OrderNote>()); }
protected set { _orderNotes = value; }
}
/// <summary>
/// Gets or sets order items
/// </summary>
public virtual ICollection<OrderItem> OrderItems
{
get { return _orderItems ?? (_orderItems = new List<OrderItem>()); }
protected set { _orderItems = value; }
}
/// <summary>
/// Gets or sets shipments
/// </summary>
public virtual ICollection<Shipment> Shipments
{
get { return _shipments ?? (_shipments = new List<Shipment>()); }
protected set { _shipments = value; }
}
#endregion
#region Custom properties
/// <summary>
/// Gets or sets the order status
/// </summary>
public OrderStatus OrderStatus
{
get
{
return (OrderStatus)this.OrderStatusId;
}
set
{
this.OrderStatusId = (int)value;
}
}
/// <summary>
/// Gets or sets the payment status
/// </summary>
public PaymentStatus PaymentStatus
{
get
{
return (PaymentStatus)this.PaymentStatusId;
}
set
{
this.PaymentStatusId = (int)value;
}
}
/// <summary>
/// Gets or sets the shipping status
/// </summary>
public ShippingStatus ShippingStatus
{
get
{
return (ShippingStatus)this.ShippingStatusId;
}
set
{
this.ShippingStatusId = (int)value;
}
}
/// <summary>
/// Gets or sets the customer tax display type
/// </summary>
public TaxDisplayType CustomerTaxDisplayType
{
get
{
return (TaxDisplayType)this.CustomerTaxDisplayTypeId;
}
set
{
this.CustomerTaxDisplayTypeId = (int)value;
}
}
/// <summary>
/// Gets the applied tax rates
/// </summary>
public SortedDictionary<decimal, decimal> TaxRatesDictionary
{
get
{
return ParseTaxRates(this.TaxRates);
}
}
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Speech.V1P1Beta1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedAdaptationClientSnippets
{
/// <summary>Snippet for CreatePhraseSet</summary>
public void CreatePhraseSetRequestObject()
{
// Snippet: CreatePhraseSet(CreatePhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
CreatePhraseSetRequest request = new CreatePhraseSetRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PhraseSetId = "",
PhraseSet = new PhraseSet(),
};
// Make the request
PhraseSet response = adaptationClient.CreatePhraseSet(request);
// End snippet
}
/// <summary>Snippet for CreatePhraseSetAsync</summary>
public async Task CreatePhraseSetRequestObjectAsync()
{
// Snippet: CreatePhraseSetAsync(CreatePhraseSetRequest, CallSettings)
// Additional: CreatePhraseSetAsync(CreatePhraseSetRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
CreatePhraseSetRequest request = new CreatePhraseSetRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
PhraseSetId = "",
PhraseSet = new PhraseSet(),
};
// Make the request
PhraseSet response = await adaptationClient.CreatePhraseSetAsync(request);
// End snippet
}
/// <summary>Snippet for CreatePhraseSet</summary>
public void CreatePhraseSet()
{
// Snippet: CreatePhraseSet(string, PhraseSet, string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
PhraseSet phraseSet = new PhraseSet();
string phraseSetId = "";
// Make the request
PhraseSet response = adaptationClient.CreatePhraseSet(parent, phraseSet, phraseSetId);
// End snippet
}
/// <summary>Snippet for CreatePhraseSetAsync</summary>
public async Task CreatePhraseSetAsync()
{
// Snippet: CreatePhraseSetAsync(string, PhraseSet, string, CallSettings)
// Additional: CreatePhraseSetAsync(string, PhraseSet, string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
PhraseSet phraseSet = new PhraseSet();
string phraseSetId = "";
// Make the request
PhraseSet response = await adaptationClient.CreatePhraseSetAsync(parent, phraseSet, phraseSetId);
// End snippet
}
/// <summary>Snippet for CreatePhraseSet</summary>
public void CreatePhraseSetResourceNames()
{
// Snippet: CreatePhraseSet(LocationName, PhraseSet, string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
PhraseSet phraseSet = new PhraseSet();
string phraseSetId = "";
// Make the request
PhraseSet response = adaptationClient.CreatePhraseSet(parent, phraseSet, phraseSetId);
// End snippet
}
/// <summary>Snippet for CreatePhraseSetAsync</summary>
public async Task CreatePhraseSetResourceNamesAsync()
{
// Snippet: CreatePhraseSetAsync(LocationName, PhraseSet, string, CallSettings)
// Additional: CreatePhraseSetAsync(LocationName, PhraseSet, string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
PhraseSet phraseSet = new PhraseSet();
string phraseSetId = "";
// Make the request
PhraseSet response = await adaptationClient.CreatePhraseSetAsync(parent, phraseSet, phraseSetId);
// End snippet
}
/// <summary>Snippet for GetPhraseSet</summary>
public void GetPhraseSetRequestObject()
{
// Snippet: GetPhraseSet(GetPhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
GetPhraseSetRequest request = new GetPhraseSetRequest
{
PhraseSetName = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]"),
};
// Make the request
PhraseSet response = adaptationClient.GetPhraseSet(request);
// End snippet
}
/// <summary>Snippet for GetPhraseSetAsync</summary>
public async Task GetPhraseSetRequestObjectAsync()
{
// Snippet: GetPhraseSetAsync(GetPhraseSetRequest, CallSettings)
// Additional: GetPhraseSetAsync(GetPhraseSetRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
GetPhraseSetRequest request = new GetPhraseSetRequest
{
PhraseSetName = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]"),
};
// Make the request
PhraseSet response = await adaptationClient.GetPhraseSetAsync(request);
// End snippet
}
/// <summary>Snippet for GetPhraseSet</summary>
public void GetPhraseSet()
{
// Snippet: GetPhraseSet(string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/phraseSets/[PHRASE_SET]";
// Make the request
PhraseSet response = adaptationClient.GetPhraseSet(name);
// End snippet
}
/// <summary>Snippet for GetPhraseSetAsync</summary>
public async Task GetPhraseSetAsync()
{
// Snippet: GetPhraseSetAsync(string, CallSettings)
// Additional: GetPhraseSetAsync(string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/phraseSets/[PHRASE_SET]";
// Make the request
PhraseSet response = await adaptationClient.GetPhraseSetAsync(name);
// End snippet
}
/// <summary>Snippet for GetPhraseSet</summary>
public void GetPhraseSetResourceNames()
{
// Snippet: GetPhraseSet(PhraseSetName, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
PhraseSetName name = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
// Make the request
PhraseSet response = adaptationClient.GetPhraseSet(name);
// End snippet
}
/// <summary>Snippet for GetPhraseSetAsync</summary>
public async Task GetPhraseSetResourceNamesAsync()
{
// Snippet: GetPhraseSetAsync(PhraseSetName, CallSettings)
// Additional: GetPhraseSetAsync(PhraseSetName, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
PhraseSetName name = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
// Make the request
PhraseSet response = await adaptationClient.GetPhraseSetAsync(name);
// End snippet
}
/// <summary>Snippet for ListPhraseSet</summary>
public void ListPhraseSetRequestObject()
{
// Snippet: ListPhraseSet(ListPhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
ListPhraseSetRequest request = new ListPhraseSetRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSet(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (PhraseSet item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPhraseSetResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPhraseSetAsync</summary>
public async Task ListPhraseSetRequestObjectAsync()
{
// Snippet: ListPhraseSetAsync(ListPhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
ListPhraseSetRequest request = new ListPhraseSetRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedAsyncEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSetAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PhraseSet item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPhraseSetResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPhraseSet</summary>
public void ListPhraseSet()
{
// Snippet: ListPhraseSet(string, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSet(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PhraseSet item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPhraseSetResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPhraseSetAsync</summary>
public async Task ListPhraseSetAsync()
{
// Snippet: ListPhraseSetAsync(string, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSetAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PhraseSet item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPhraseSetResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPhraseSet</summary>
public void ListPhraseSetResourceNames()
{
// Snippet: ListPhraseSet(LocationName, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSet(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PhraseSet item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPhraseSetResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPhraseSetAsync</summary>
public async Task ListPhraseSetResourceNamesAsync()
{
// Snippet: ListPhraseSetAsync(LocationName, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListPhraseSetResponse, PhraseSet> response = adaptationClient.ListPhraseSetAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PhraseSet item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPhraseSetResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PhraseSet item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PhraseSet> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PhraseSet item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for UpdatePhraseSet</summary>
public void UpdatePhraseSetRequestObject()
{
// Snippet: UpdatePhraseSet(UpdatePhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
UpdatePhraseSetRequest request = new UpdatePhraseSetRequest
{
PhraseSet = new PhraseSet(),
UpdateMask = new FieldMask(),
};
// Make the request
PhraseSet response = adaptationClient.UpdatePhraseSet(request);
// End snippet
}
/// <summary>Snippet for UpdatePhraseSetAsync</summary>
public async Task UpdatePhraseSetRequestObjectAsync()
{
// Snippet: UpdatePhraseSetAsync(UpdatePhraseSetRequest, CallSettings)
// Additional: UpdatePhraseSetAsync(UpdatePhraseSetRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
UpdatePhraseSetRequest request = new UpdatePhraseSetRequest
{
PhraseSet = new PhraseSet(),
UpdateMask = new FieldMask(),
};
// Make the request
PhraseSet response = await adaptationClient.UpdatePhraseSetAsync(request);
// End snippet
}
/// <summary>Snippet for UpdatePhraseSet</summary>
public void UpdatePhraseSet()
{
// Snippet: UpdatePhraseSet(PhraseSet, FieldMask, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
PhraseSet phraseSet = new PhraseSet();
FieldMask updateMask = new FieldMask();
// Make the request
PhraseSet response = adaptationClient.UpdatePhraseSet(phraseSet, updateMask);
// End snippet
}
/// <summary>Snippet for UpdatePhraseSetAsync</summary>
public async Task UpdatePhraseSetAsync()
{
// Snippet: UpdatePhraseSetAsync(PhraseSet, FieldMask, CallSettings)
// Additional: UpdatePhraseSetAsync(PhraseSet, FieldMask, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
PhraseSet phraseSet = new PhraseSet();
FieldMask updateMask = new FieldMask();
// Make the request
PhraseSet response = await adaptationClient.UpdatePhraseSetAsync(phraseSet, updateMask);
// End snippet
}
/// <summary>Snippet for DeletePhraseSet</summary>
public void DeletePhraseSetRequestObject()
{
// Snippet: DeletePhraseSet(DeletePhraseSetRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
DeletePhraseSetRequest request = new DeletePhraseSetRequest
{
PhraseSetName = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]"),
};
// Make the request
adaptationClient.DeletePhraseSet(request);
// End snippet
}
/// <summary>Snippet for DeletePhraseSetAsync</summary>
public async Task DeletePhraseSetRequestObjectAsync()
{
// Snippet: DeletePhraseSetAsync(DeletePhraseSetRequest, CallSettings)
// Additional: DeletePhraseSetAsync(DeletePhraseSetRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
DeletePhraseSetRequest request = new DeletePhraseSetRequest
{
PhraseSetName = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]"),
};
// Make the request
await adaptationClient.DeletePhraseSetAsync(request);
// End snippet
}
/// <summary>Snippet for DeletePhraseSet</summary>
public void DeletePhraseSet()
{
// Snippet: DeletePhraseSet(string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/phraseSets/[PHRASE_SET]";
// Make the request
adaptationClient.DeletePhraseSet(name);
// End snippet
}
/// <summary>Snippet for DeletePhraseSetAsync</summary>
public async Task DeletePhraseSetAsync()
{
// Snippet: DeletePhraseSetAsync(string, CallSettings)
// Additional: DeletePhraseSetAsync(string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/phraseSets/[PHRASE_SET]";
// Make the request
await adaptationClient.DeletePhraseSetAsync(name);
// End snippet
}
/// <summary>Snippet for DeletePhraseSet</summary>
public void DeletePhraseSetResourceNames()
{
// Snippet: DeletePhraseSet(PhraseSetName, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
PhraseSetName name = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
// Make the request
adaptationClient.DeletePhraseSet(name);
// End snippet
}
/// <summary>Snippet for DeletePhraseSetAsync</summary>
public async Task DeletePhraseSetResourceNamesAsync()
{
// Snippet: DeletePhraseSetAsync(PhraseSetName, CallSettings)
// Additional: DeletePhraseSetAsync(PhraseSetName, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
PhraseSetName name = PhraseSetName.FromProjectLocationPhraseSet("[PROJECT]", "[LOCATION]", "[PHRASE_SET]");
// Make the request
await adaptationClient.DeletePhraseSetAsync(name);
// End snippet
}
/// <summary>Snippet for CreateCustomClass</summary>
public void CreateCustomClassRequestObject()
{
// Snippet: CreateCustomClass(CreateCustomClassRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
CreateCustomClassRequest request = new CreateCustomClassRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CustomClassId = "",
CustomClass = new CustomClass(),
};
// Make the request
CustomClass response = adaptationClient.CreateCustomClass(request);
// End snippet
}
/// <summary>Snippet for CreateCustomClassAsync</summary>
public async Task CreateCustomClassRequestObjectAsync()
{
// Snippet: CreateCustomClassAsync(CreateCustomClassRequest, CallSettings)
// Additional: CreateCustomClassAsync(CreateCustomClassRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
CreateCustomClassRequest request = new CreateCustomClassRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
CustomClassId = "",
CustomClass = new CustomClass(),
};
// Make the request
CustomClass response = await adaptationClient.CreateCustomClassAsync(request);
// End snippet
}
/// <summary>Snippet for CreateCustomClass</summary>
public void CreateCustomClass()
{
// Snippet: CreateCustomClass(string, CustomClass, string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
CustomClass customClass = new CustomClass();
string customClassId = "";
// Make the request
CustomClass response = adaptationClient.CreateCustomClass(parent, customClass, customClassId);
// End snippet
}
/// <summary>Snippet for CreateCustomClassAsync</summary>
public async Task CreateCustomClassAsync()
{
// Snippet: CreateCustomClassAsync(string, CustomClass, string, CallSettings)
// Additional: CreateCustomClassAsync(string, CustomClass, string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
CustomClass customClass = new CustomClass();
string customClassId = "";
// Make the request
CustomClass response = await adaptationClient.CreateCustomClassAsync(parent, customClass, customClassId);
// End snippet
}
/// <summary>Snippet for CreateCustomClass</summary>
public void CreateCustomClassResourceNames()
{
// Snippet: CreateCustomClass(LocationName, CustomClass, string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
CustomClass customClass = new CustomClass();
string customClassId = "";
// Make the request
CustomClass response = adaptationClient.CreateCustomClass(parent, customClass, customClassId);
// End snippet
}
/// <summary>Snippet for CreateCustomClassAsync</summary>
public async Task CreateCustomClassResourceNamesAsync()
{
// Snippet: CreateCustomClassAsync(LocationName, CustomClass, string, CallSettings)
// Additional: CreateCustomClassAsync(LocationName, CustomClass, string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
CustomClass customClass = new CustomClass();
string customClassId = "";
// Make the request
CustomClass response = await adaptationClient.CreateCustomClassAsync(parent, customClass, customClassId);
// End snippet
}
/// <summary>Snippet for GetCustomClass</summary>
public void GetCustomClassRequestObject()
{
// Snippet: GetCustomClass(GetCustomClassRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
GetCustomClassRequest request = new GetCustomClassRequest
{
CustomClassName = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]"),
};
// Make the request
CustomClass response = adaptationClient.GetCustomClass(request);
// End snippet
}
/// <summary>Snippet for GetCustomClassAsync</summary>
public async Task GetCustomClassRequestObjectAsync()
{
// Snippet: GetCustomClassAsync(GetCustomClassRequest, CallSettings)
// Additional: GetCustomClassAsync(GetCustomClassRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
GetCustomClassRequest request = new GetCustomClassRequest
{
CustomClassName = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]"),
};
// Make the request
CustomClass response = await adaptationClient.GetCustomClassAsync(request);
// End snippet
}
/// <summary>Snippet for GetCustomClass</summary>
public void GetCustomClass()
{
// Snippet: GetCustomClass(string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/customClasses/[CUSTOM_CLASS]";
// Make the request
CustomClass response = adaptationClient.GetCustomClass(name);
// End snippet
}
/// <summary>Snippet for GetCustomClassAsync</summary>
public async Task GetCustomClassAsync()
{
// Snippet: GetCustomClassAsync(string, CallSettings)
// Additional: GetCustomClassAsync(string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/customClasses/[CUSTOM_CLASS]";
// Make the request
CustomClass response = await adaptationClient.GetCustomClassAsync(name);
// End snippet
}
/// <summary>Snippet for GetCustomClass</summary>
public void GetCustomClassResourceNames()
{
// Snippet: GetCustomClass(CustomClassName, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
CustomClassName name = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
// Make the request
CustomClass response = adaptationClient.GetCustomClass(name);
// End snippet
}
/// <summary>Snippet for GetCustomClassAsync</summary>
public async Task GetCustomClassResourceNamesAsync()
{
// Snippet: GetCustomClassAsync(CustomClassName, CallSettings)
// Additional: GetCustomClassAsync(CustomClassName, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
CustomClassName name = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
// Make the request
CustomClass response = await adaptationClient.GetCustomClassAsync(name);
// End snippet
}
/// <summary>Snippet for ListCustomClasses</summary>
public void ListCustomClassesRequestObject()
{
// Snippet: ListCustomClasses(ListCustomClassesRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
ListCustomClassesRequest request = new ListCustomClassesRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClasses(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (CustomClass item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCustomClassesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCustomClassesAsync</summary>
public async Task ListCustomClassesRequestObjectAsync()
{
// Snippet: ListCustomClassesAsync(ListCustomClassesRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
ListCustomClassesRequest request = new ListCustomClassesRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedAsyncEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClassesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CustomClass item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCustomClassesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCustomClasses</summary>
public void ListCustomClasses()
{
// Snippet: ListCustomClasses(string, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClasses(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (CustomClass item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCustomClassesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCustomClassesAsync</summary>
public async Task ListCustomClassesAsync()
{
// Snippet: ListCustomClassesAsync(string, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClassesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CustomClass item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCustomClassesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCustomClasses</summary>
public void ListCustomClassesResourceNames()
{
// Snippet: ListCustomClasses(LocationName, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClasses(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (CustomClass item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCustomClassesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCustomClassesAsync</summary>
public async Task ListCustomClassesResourceNamesAsync()
{
// Snippet: ListCustomClassesAsync(LocationName, string, int?, CallSettings)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClassesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CustomClass item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCustomClassesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CustomClass item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CustomClass> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CustomClass item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for UpdateCustomClass</summary>
public void UpdateCustomClassRequestObject()
{
// Snippet: UpdateCustomClass(UpdateCustomClassRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
UpdateCustomClassRequest request = new UpdateCustomClassRequest
{
CustomClass = new CustomClass(),
UpdateMask = new FieldMask(),
};
// Make the request
CustomClass response = adaptationClient.UpdateCustomClass(request);
// End snippet
}
/// <summary>Snippet for UpdateCustomClassAsync</summary>
public async Task UpdateCustomClassRequestObjectAsync()
{
// Snippet: UpdateCustomClassAsync(UpdateCustomClassRequest, CallSettings)
// Additional: UpdateCustomClassAsync(UpdateCustomClassRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
UpdateCustomClassRequest request = new UpdateCustomClassRequest
{
CustomClass = new CustomClass(),
UpdateMask = new FieldMask(),
};
// Make the request
CustomClass response = await adaptationClient.UpdateCustomClassAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateCustomClass</summary>
public void UpdateCustomClass()
{
// Snippet: UpdateCustomClass(CustomClass, FieldMask, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
CustomClass customClass = new CustomClass();
FieldMask updateMask = new FieldMask();
// Make the request
CustomClass response = adaptationClient.UpdateCustomClass(customClass, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateCustomClassAsync</summary>
public async Task UpdateCustomClassAsync()
{
// Snippet: UpdateCustomClassAsync(CustomClass, FieldMask, CallSettings)
// Additional: UpdateCustomClassAsync(CustomClass, FieldMask, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
CustomClass customClass = new CustomClass();
FieldMask updateMask = new FieldMask();
// Make the request
CustomClass response = await adaptationClient.UpdateCustomClassAsync(customClass, updateMask);
// End snippet
}
/// <summary>Snippet for DeleteCustomClass</summary>
public void DeleteCustomClassRequestObject()
{
// Snippet: DeleteCustomClass(DeleteCustomClassRequest, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
DeleteCustomClassRequest request = new DeleteCustomClassRequest
{
CustomClassName = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]"),
};
// Make the request
adaptationClient.DeleteCustomClass(request);
// End snippet
}
/// <summary>Snippet for DeleteCustomClassAsync</summary>
public async Task DeleteCustomClassRequestObjectAsync()
{
// Snippet: DeleteCustomClassAsync(DeleteCustomClassRequest, CallSettings)
// Additional: DeleteCustomClassAsync(DeleteCustomClassRequest, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
DeleteCustomClassRequest request = new DeleteCustomClassRequest
{
CustomClassName = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]"),
};
// Make the request
await adaptationClient.DeleteCustomClassAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteCustomClass</summary>
public void DeleteCustomClass()
{
// Snippet: DeleteCustomClass(string, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/customClasses/[CUSTOM_CLASS]";
// Make the request
adaptationClient.DeleteCustomClass(name);
// End snippet
}
/// <summary>Snippet for DeleteCustomClassAsync</summary>
public async Task DeleteCustomClassAsync()
{
// Snippet: DeleteCustomClassAsync(string, CallSettings)
// Additional: DeleteCustomClassAsync(string, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/customClasses/[CUSTOM_CLASS]";
// Make the request
await adaptationClient.DeleteCustomClassAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteCustomClass</summary>
public void DeleteCustomClassResourceNames()
{
// Snippet: DeleteCustomClass(CustomClassName, CallSettings)
// Create client
AdaptationClient adaptationClient = AdaptationClient.Create();
// Initialize request argument(s)
CustomClassName name = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
// Make the request
adaptationClient.DeleteCustomClass(name);
// End snippet
}
/// <summary>Snippet for DeleteCustomClassAsync</summary>
public async Task DeleteCustomClassResourceNamesAsync()
{
// Snippet: DeleteCustomClassAsync(CustomClassName, CallSettings)
// Additional: DeleteCustomClassAsync(CustomClassName, CancellationToken)
// Create client
AdaptationClient adaptationClient = await AdaptationClient.CreateAsync();
// Initialize request argument(s)
CustomClassName name = CustomClassName.FromProjectLocationCustomClass("[PROJECT]", "[LOCATION]", "[CUSTOM_CLASS]");
// Make the request
await adaptationClient.DeleteCustomClassAsync(name);
// End snippet
}
}
}
| |
${header}<%
if model.IsAbstract(node):
abstractClass = "abstract "
end
%>namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public ${abstractClass}partial class ${node.Name} : ${join(node.BaseTypes, ', ')}
{
<%
allFields = model.GetAllFields(node)
for field as Field in node.Members:
%> protected ${field.Type} ${GetPrivateName(field)};
<%
end
%>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ${node.Name} CloneNode()
{
return Clone() as ${node.Name};
}
<%
unless model.IsAbstract(node):
%>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get
{
return NodeType.${node.Name};
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.On${node.Name}(this);
}
<%
end
%>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
${node.Name} other = node as ${node.Name};
if (null == other) return false;
<%
for field in allFields:
fieldName = GetPrivateName(field)
fieldType = model.ResolveFieldType(field)
if fieldType is null or model.IsEnum(fieldType):
%> if (${fieldName} != other.${fieldName}) return NoMatch("${node.Name}.${fieldName}");
<%
elif model.IsCollectionField(field):
%> if (!Node.AllMatch(${fieldName}, other.${fieldName})) return NoMatch("${node.Name}.${fieldName}");
<% else:
%> if (!Node.Matches(${fieldName}, other.${fieldName})) return NoMatch("${node.Name}.${fieldName}");
<%
end
end
%> return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
<%
for field in allFields:
fieldType = model.ResolveFieldType(field)
continue if fieldType is null
continue if model.IsEnum(fieldType)
fieldName = GetPrivateName(field)
if model.IsCollection(fieldType):
collectionItemType = model.GetCollectionItemType(fieldType)
%> if (${fieldName} != null)
{
${collectionItemType} item = existing as ${collectionItemType};
if (null != item)
{
${collectionItemType} newItem = (${collectionItemType})newNode;
if (${fieldName}.Replace(item, newItem))
{
return true;
}
}
}
<%
else:
%> if (${fieldName} == existing)
{
this.${field.Name} = (${field.Type})newNode;
return true;
}
<%
end
end
%> return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
${node.Name} clone = (${node.Name})FormatterServices.GetUninitializedObject(typeof(${node.Name}));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
<%
if model.IsExpression(node):
%> clone._expressionType = _expressionType;
<%
end
for field in allFields:
fieldName = GetPrivateName(field)
if model.IsNodeField(field):
%> if (null != ${fieldName})
{
clone.${fieldName} = ${fieldName}.Clone() as ${field.Type};
clone.${fieldName}.InitializeParent(clone);
}
<%
else:
%> clone.${fieldName} = ${fieldName};
<%
end
end
%> return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
<%
if model.IsExpression(node):
%> _expressionType = null;
<%
end
for field in allFields:
fieldType = model.ResolveFieldType(field)
fieldName = GetPrivateName(field)
if fieldType is not null and not model.IsEnum(fieldType):
%> if (null != ${fieldName})
{
${fieldName}.ClearTypeSystemBindings();
}
<%
end
end
%>
}
<%
for field as Field in node.Members:
if field.Name == "Name":
Output.WriteLine("""
[System.Xml.Serialization.XmlAttribute]""")
elif field.Name == "Modifiers":
Output.WriteLine("""
[System.Xml.Serialization.XmlAttribute,
System.ComponentModel.DefaultValue(${field.Type}.None)]""")
else:
Output.WriteLine("""
[System.Xml.Serialization.XmlElement]""")
end
%> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ${field.Type} ${field.Name}
{
get
{
<%
if model.IsCollectionField(field):
%>
if (${GetPrivateName(field)} == null) ${GetPrivateName(field)} = new ${field.Type}(this);
<%
elif field.Attributes.Contains("auto"):
%> if (${GetPrivateName(field)} == null)
{
${GetPrivateName(field)} = new ${field.Type}();
${GetPrivateName(field)}.InitializeParent(this);
}
<%
end
%>
return ${GetPrivateName(field)};
}
<%
fieldType = model.ResolveFieldType(field)
if fieldType is not null and not model.IsEnum(fieldType):
%> set
{
if (${GetPrivateName(field)} != value)
{
${GetPrivateName(field)} = value;
if (null != ${GetPrivateName(field)})
{
${GetPrivateName(field)}.InitializeParent(this);
<%
if field.Attributes.Contains("LexicalInfo"):
%> this.LexicalInfo = value.LexicalInfo;
<%
end
%> }
}
}
<%
else:
%> set
{
${GetPrivateName(field)} = value;
}
<%
end
%>
}
<%
end
%>
}
}
| |
using System;
using System.Linq;
using DynamicProg.Validation;
using NUnit.Framework;
namespace UnitTest
{
[TestFixture]
public class CheckThat_String_Test
{
private string _stringToTest = "My string to test";
[Test]
[ExpectedException(typeof(FormatException))]
public void If_i_cant_convert_a_string_to_a_numeric_value_throw_an_exception()
{
new Validator().CheckThat(() => _stringToTest).CanConvertToInt32().ThrowFirst();
}
[Test]
public void If_i_can_convert_a_string_to_a_numeric_value_dont_throw_an_exception()
{
new Validator().CheckThat(()=>"23").CanConvertToInt32().ThrowFirst();
}
[Test]
[ExpectedException(typeof(FormatException))]
public void If_i_cant_convert_a_string_to_boolean_an_exception_is_thrown()
{
new Validator().CheckThat(() => _stringToTest).CanConvertToBool().ThrowFirst();
}
[Test]
public void If_i_can_convert_a_false_string_to_boolean_no_exception_is_thrown()
{
new Validator().CheckThat(() => "false").CanConvertToBool().ThrowFirst();
}
[Test]
public void If_i_can_convert_a_true_string_to_boolean_no_exception_is_thrown()
{
new Validator().CheckThat(()=> "true").CanConvertToBool().Throw();
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void If_string_is_not_one_of_a_series_of_options_throws_a_custom_exception()
{
var options = new[] { "0056", "0256", "0512", "0752", "1100" };
new Validator().CheckThat(() => _stringToTest).IsOneOf<ArgumentException>(options, null)
.ThrowFirst();
}
[Test]
public void If_string_is_one_of_a_series_of_options_no_exception_is_thrown()
{
var options = new[] { "0056", "0256", "0512", "0752", "1100" };
new Validator().CheckThat(() => "1100").IsOneOf(options)
.ThrowFirst();
}
[Test]
[ExpectedException(typeof(MatchNotFoundException))]
public void If_string_is_not_one_of_a_series_of_options_throws_exception()
{
var options = new[] { "0056", "0256", "0512", "0752", "1100" };
new Validator().CheckThat(() => _stringToTest).IsOneOf(options)
.ThrowFirst();
}
[Test]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void Check_that_length_is_between_two_limits_throws_a_custom_exception()
{
new Validator().CheckThat(() => _stringToTest)
.LengthIsBetween<ArgumentOutOfRangeException>(20, 100, null)
.ThrowFirst();
}
[Test]
[ExpectedException(typeof (InvalidSizeException))]
public void Check_that_a_string_length_is_between_two_limits_lower_bound_error()
{
new Validator().CheckThat(() => _stringToTest).LengthIsBetween(20, 100).ThrowFirst();
}
[Test]
[ExpectedException(typeof(InvalidSizeException))]
public void Check_that_a_string_length_is_between_two_limits_upper_bound_error()
{
new Validator().CheckThat(() => _stringToTest).LengthIsBetween(4, 10).ThrowFirst();
}
[Test]
[ExpectedException(typeof(InvalidFormatException))]
public void Check_that_a_string_is_an_email()
{
new Validator().CheckThat(() => _stringToTest).IsEmail().ThrowFirst();
}
[Test]
[ExpectedException(typeof (InvalidFormatException))]
public void Check_that_a_string_is_an_url()
{
new Validator().CheckThat(() => _stringToTest).IsUrl().ThrowFirst();
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void I_want_to_throw_an_exception_of_a_given_type_no_matter_how_many_exceptions_occur()
{
new Validator().CheckThat(()=>_stringToTest)
.HasNoSpaces().LengthLessThan(4).Throw<ArgumentNullException>(null);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void I_want_to_throw_an_exception_of_a_given_type_when_checking_multiple_variables()
{
var secondVariable = 45;
var validator = new Validator();
validator.CheckThat(() => _stringToTest).HasNoSpaces().LengthLessThan(4);
validator.CheckThat(() => secondVariable).IsBetween(56, 100);
validator.Throw<ArgumentException>(new[]{"Please check the data entered and try again."});
}
[Test]
[ExpectedException(typeof(InvalidFormatException))]
public void I_want_to_throw_the_first_exception_from_a_collection()
{
var secondVariable = 45;
var validator = new Validator();
validator.CheckThat(() => _stringToTest).HasNoSpaces().LengthLessThan(4);
validator.CheckThat(() => secondVariable).IsBetween(56, 100);
validator.ThrowFirst();
}
[Test]
[ExpectedException(typeof(InvalidSizeException))]
public void When_checking_for_only_one_thing_I_should_throw_the_exception_of_what_I_am_throwing()
{
new Validator().CheckThat(()=>_stringToTest).LengthEqualTo(10).ThrowFirst();
}
[Test]
public void Do_all_possible_checks_and_return_a_list()
{
var list = new Validator().CheckThat(() => _stringToTest)
.IsNotNull()
.IsNull()
.IsNotEmpty()
.IsEmpty()
.IsNullOrEmpty()
.IsNotNullOrEmpty()
.LengthEqualTo(5)
.LengthMoreThan(50)
.LengthLessThan(5)
.LengthMoreOrEqualTo(50)
.LengthLessOrEqualTo(10)
.Match("/abc/")
.HasNoSpaces()
.List();
Assert.That(list.ErrorsCollection.First().Value.Count, Is.EqualTo(10));
list = new Validator().CheckThat(() => _stringToTest)
.IsNullOrEmpty()
.LengthLessOrEqualTo(10)
.HasNoSpaces()
.List();
foreach (var exception in list.ErrorsCollection.First().Value)
{
Console.WriteLine("Exception type: " + exception.GetType() + " - Message: " + exception.Message );
}
}
[Test]
public void Do_all_possible_checks_and_return_a_list_of_custom_Exceptions()
{
var list = new Validator().CheckThat(() => _stringToTest)
.IsNotNull<ArgumentException>(null)
.IsNull<ArgumentException>(null)
.IsNotEmpty<ArgumentException>(null)
.IsEmpty<ArgumentException>(null)
.IsNullOrEmpty<ArgumentException>(null)
.IsNotNullOrEmpty<ArgumentException>(null)
.LengthEqualTo<ArgumentException>(5, null)
.LengthMoreThan<ArgumentException>(50, null)
.LengthLessThan<ArgumentException>(5, null)
.LengthMoreOrEqualTo<ArgumentException>(50, null)
.LengthLessOrEqualTo<ArgumentException>(10, null)
.Match<ArgumentException>("/abc/", null)
.HasNoSpaces<ArgumentException>(null)
.List();
Assert.That(list.ErrorsCollection.First().Value.Count, Is.EqualTo(10));
foreach (var exception in list.ErrorsCollection.First().Value)
{
Assert.IsInstanceOfType(typeof(ArgumentException),exception);
}
}
[Test]
public void Check_Null_and_empty_strings()
{
string empty = null;
var list = new Validator().CheckThat(() => empty)
.IsNotNull()
.IsNotEmpty()
.IsNotNullOrEmpty()
.List();
Assert.That(list.ErrorsCollection.First().Value.Count, Is.EqualTo(3));
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="DecimalKeyFrameCollection.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 KeyFrameDecimalAnimation
/// to animate a Decimal property value along a set of key frames.
/// </summary>
public class DecimalKeyFrameCollection : Freezable, IList
{
#region Data
private List<DecimalKeyFrame> _keyFrames;
private static DecimalKeyFrameCollection s_emptyCollection;
#endregion
#region Constructors
/// <Summary>
/// Creates a new DecimalKeyFrameCollection.
/// </Summary>
public DecimalKeyFrameCollection()
: base()
{
_keyFrames = new List< DecimalKeyFrame>(2);
}
#endregion
#region Static Methods
/// <summary>
/// An empty DecimalKeyFrameCollection.
/// </summary>
public static DecimalKeyFrameCollection Empty
{
get
{
if (s_emptyCollection == null)
{
DecimalKeyFrameCollection emptyCollection = new DecimalKeyFrameCollection();
emptyCollection._keyFrames = new List< DecimalKeyFrame>(0);
emptyCollection.Freeze();
s_emptyCollection = emptyCollection;
}
return s_emptyCollection;
}
}
#endregion
#region Freezable
/// <summary>
/// Creates a freezable copy of this DecimalKeyFrameCollection.
/// </summary>
/// <returns>The copy</returns>
public new DecimalKeyFrameCollection Clone()
{
return (DecimalKeyFrameCollection)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 DecimalKeyFrameCollection();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
DecimalKeyFrameCollection sourceCollection = (DecimalKeyFrameCollection) sourceFreezable;
base.CloneCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< DecimalKeyFrame>(count);
for (int i = 0; i < count; i++)
{
DecimalKeyFrame keyFrame = (DecimalKeyFrame)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)
{
DecimalKeyFrameCollection sourceCollection = (DecimalKeyFrameCollection) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< DecimalKeyFrame>(count);
for (int i = 0; i < count; i++)
{
DecimalKeyFrame keyFrame = (DecimalKeyFrame)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)
{
DecimalKeyFrameCollection sourceCollection = (DecimalKeyFrameCollection) sourceFreezable;
base.GetAsFrozenCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< DecimalKeyFrame>(count);
for (int i = 0; i < count; i++)
{
DecimalKeyFrame keyFrame = (DecimalKeyFrame)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)
{
DecimalKeyFrameCollection sourceCollection = (DecimalKeyFrameCollection) sourceFreezable;
base.GetCurrentValueAsFrozenCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< DecimalKeyFrame>(count);
for (int i = 0; i < count; i++)
{
DecimalKeyFrame keyFrame = (DecimalKeyFrame)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 DecimalKeyFrames in the collection.
/// </summary>
public IEnumerator GetEnumerator()
{
ReadPreamble();
return _keyFrames.GetEnumerator();
}
#endregion
#region ICollection
/// <summary>
/// Returns the number of DecimalKeyFrames 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 DecimalKeyFrames 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 DecimalKeyFrames in the collection to an
/// array of DecimalKeyFrames.
/// </summary>
public void CopyTo(DecimalKeyFrame[] array, int index)
{
ReadPreamble();
_keyFrames.CopyTo(array, index);
}
#endregion
#region IList
/// <summary>
/// Adds a DecimalKeyFrame to the collection.
/// </summary>
int IList.Add(object keyFrame)
{
return Add((DecimalKeyFrame)keyFrame);
}
/// <summary>
/// Adds a DecimalKeyFrame to the collection.
/// </summary>
public int Add(DecimalKeyFrame keyFrame)
{
if (keyFrame == null)
{
throw new ArgumentNullException("keyFrame");
}
WritePreamble();
OnFreezablePropertyChanged(null, keyFrame);
_keyFrames.Add(keyFrame);
WritePostscript();
return _keyFrames.Count - 1;
}
/// <summary>
/// Removes all DecimalKeyFrames 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 DecimalKeyFrame.
/// </summary>
bool IList.Contains(object keyFrame)
{
return Contains((DecimalKeyFrame)keyFrame);
}
/// <summary>
/// Returns true of the collection contains the given DecimalKeyFrame.
/// </summary>
public bool Contains(DecimalKeyFrame keyFrame)
{
ReadPreamble();
return _keyFrames.Contains(keyFrame);
}
/// <summary>
/// Returns the index of a given DecimalKeyFrame in the collection.
/// </summary>
int IList.IndexOf(object keyFrame)
{
return IndexOf((DecimalKeyFrame)keyFrame);
}
/// <summary>
/// Returns the index of a given DecimalKeyFrame in the collection.
/// </summary>
public int IndexOf(DecimalKeyFrame keyFrame)
{
ReadPreamble();
return _keyFrames.IndexOf(keyFrame);
}
/// <summary>
/// Inserts a DecimalKeyFrame into a specific location in the collection.
/// </summary>
void IList.Insert(int index, object keyFrame)
{
Insert(index, (DecimalKeyFrame)keyFrame);
}
/// <summary>
/// Inserts a DecimalKeyFrame into a specific location in the collection.
/// </summary>
public void Insert(int index, DecimalKeyFrame 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 DecimalKeyFrame from the collection.
/// </summary>
void IList.Remove(object keyFrame)
{
Remove((DecimalKeyFrame)keyFrame);
}
/// <summary>
/// Removes a DecimalKeyFrame from the collection.
/// </summary>
public void Remove(DecimalKeyFrame keyFrame)
{
WritePreamble();
if (_keyFrames.Contains(keyFrame))
{
OnFreezablePropertyChanged(keyFrame, null);
_keyFrames.Remove(keyFrame);
WritePostscript();
}
}
/// <summary>
/// Removes the DecimalKeyFrame 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 DecimalKeyFrame at a given index.
/// </summary>
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (DecimalKeyFrame)value;
}
}
/// <summary>
/// Gets or sets the DecimalKeyFrame at a given index.
/// </summary>
public DecimalKeyFrame this[int index]
{
get
{
ReadPreamble();
return _keyFrames[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "DecimalKeyFrameCollection[{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 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.CSharpCodeFixVerifier<
Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpImplementStandardExceptionConstructorsAnalyzer,
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ImplementStandardExceptionConstructorsFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicImplementStandardExceptionConstructorsAnalyzer,
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ImplementStandardExceptionConstructorsFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class ImplementStandardExceptionConstructorsTests
{
#region CSharp Unit Tests
[Fact]
public async Task CSharp_CA1032_NoDiagnostic_NotDerivingFromException()
{
await VerifyCS.VerifyAnalyzerAsync(@"
//example of a class that doesn't derive from Exception type
public class NotDerivingFromException
{
}
");
}
[Fact]
public async Task CSharp_CA1032_NoDiagnostic_GoodException1()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
//example of a class that derives from Exception type with all the minimum needed constructors
public class GoodException1 : Exception
{
public GoodException1()
{
}
public GoodException1(string message): base(message)
{
}
public GoodException1(string message, Exception innerException) : base(message, innerException)
{
}
}
");
}
[Fact]
public async Task CSharp_CA1032_NoDiagnostic_GoodException2()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
//example of a class that derives from Exception type with all the minimum needed constructors plus an extra constructor
public class GoodException2 : Exception
{
public GoodException2()
{
}
public GoodException2(string message): base(message)
{
}
public GoodException2(int i, string message)
{
}
public GoodException2(string message, Exception innerException) : base(message, innerException)
{
}
}
");
}
[Fact]
public async Task CSharp_CA1032_Diagnostic_MissingAllConstructors()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
//example of a class that derives from Exception type and missing all minimum required constructors - in this case system creates a default parameterless constructor
public class BadException1 : Exception
{
}
",
GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException1", constructor: "public BadException1(string message)"),
GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException1", constructor: "public BadException1(string message, Exception innerException)"));
}
[Fact]
public async Task CSharp_CA1032_Diagnostic_MissingTwoConstructors()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
//example of a class that derives from Exception type and missing 2 minimum required constructors
public class BadException2 : Exception
{
public BadException2()
{
}
}
",
GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException2", constructor: "public BadException2(string message)"),
GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException2", constructor: "public BadException2(string message, Exception innerException)"));
}
[Fact]
public async Task CSharp_CA1032_Diagnostic_MissingDefaultConstructor()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
//example of a class that derives from Exception type with missing default constructor
public class BadException3 : Exception
{
public BadException3(string message): base(message)
{
}
public BadException3(string message, Exception innerException) : base(message, innerException)
{
}
}
",
GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException3", constructor: "public BadException3()"));
}
[Fact]
public async Task CSharp_CA1032_Diagnostic_MissingConstructor2()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
//example of a class that derives from Exception type with missing constructor containing string type parameter
public class BadException4 : Exception
{
public BadException4()
{
}
public BadException4(string message, Exception innerException) : base(message, innerException)
{
}
}
",
GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException4", constructor: "public BadException4(string message)"));
}
[Fact]
public async Task CSharp_CA1032_Diagnostic_MissingConstructor3()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
//example of a class that derives from Exception type with missing constructor containing string type and exception type parameter
public class BadException5 : Exception
{
public BadException5()
{
}
public BadException5(string message): base(message)
{
}
}
",
GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException5", constructor: "public BadException5(string message, Exception innerException)"));
}
[Fact]
public async Task CSharp_CA1032_Diagnostic_SurplusButMissingConstructor3()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
//example of a class that derives from Exception type, and has 3 constructors but missing constructor containing string type parameter only
public class BadException6 : Exception
{
public BadException6()
{
}
public BadException6(int i, string message)
{
}
public BadException6(string message, Exception innerException) : base(message, innerException)
{
}
}
",
GetCA1032CSharpMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException6", constructor: "public BadException6(string message)"));
}
#endregion
#region VB Unit Test
[Fact]
public async Task Basic_CA1032_NoDiagnostic_NotDerivingFromException()
{
await VerifyVB.VerifyAnalyzerAsync(@"
'example of a class that doesn't derive from Exception type
Public Class NotDerivingFromException
End Class
");
}
[Fact]
public async Task Basic_CA1032_NoDiagnostic_GoodException1()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
'example of a class that derives from Exception type with all the minimum needed constructors
Public Class GoodException1 : Inherits Exception
Sub New()
End Sub
Sub New(message As String)
End Sub
Sub New(message As String, innerException As Exception)
End Sub
End Class
");
}
[Fact]
public async Task Basic_CA1032_NoDiagnostic_GoodException2()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
'example of a class that derives from Exception type with all the minimum needed constructors plus an extra constructor
Public Class GoodException2 : Inherits Exception
Sub New()
End Sub
Sub New(message As String)
End Sub
Sub New(message As String, innerException As Exception)
End Sub
Sub New(i As Integer, message As String)
End Sub
End Class
");
}
[Fact]
public async Task Basic_CA1032_Diagnostic_MissingAllConstructors()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
'example of a class that derives from Exception type and missing all minimum required constructors - in this case system creates a default parameterless constructor
Public Class BadException1 : Inherits Exception
End Class
",
GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException1", constructor: "Public Sub New(message As String)"),
GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException1", constructor: "Public Sub New(message As String, innerException As Exception)"));
}
[Fact]
public async Task Basic_CA1032_Diagnostic_MissingTwoConstructors()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
'example of a class that derives from Exception type and missing 2 minimum required constructors
Public Class BadException2 : Inherits Exception
Sub New()
End Sub
End Class
",
GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException2", constructor: "Public Sub New(message As String)"),
GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException2", constructor: "Public Sub New(message As String, innerException As Exception)"));
}
[Fact]
public async Task Basic_CA1032_Diagnostic_MissingDefaultConstructor()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
'example of a class that derives from Exception type with missing default constructor
Public Class BadException3 : Inherits Exception
Sub New(message As String)
End Sub
Sub New(message As String, innerException As Exception)
End Sub
End Class
",
GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException3", constructor: "Public Sub New()"));
}
[Fact]
public async Task Basic_CA1032_Diagnostic_MissingConstructor2()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
'example of a class that derives from Exception type with missing constructor containing string type parameter
Public Class BadException4 : Inherits Exception
Sub New()
End Sub
Sub New(message As String, innerException As Exception)
End Sub
End Class
",
GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException4", constructor: "Public Sub New(message As String)"));
}
[Fact]
public async Task Basic_CA1032_Diagnostic_MissingConstructor3()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
'example of a class that derives from Exception type with missing constructor containing string type and exception type parameter
Public Class BadException5 : Inherits Exception
Sub New()
End Sub
Sub New(message As String)
End Sub
End Class
",
GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException5", constructor: "Public Sub New(message As String, innerException As Exception)"));
}
[Fact]
public async Task Basic_CA1032_Diagnostic_SurplusButMissingConstructor3()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
'example of a class that derives from Exception type, and has 3 constructors but missing constructor containing string type parameter only
Public Class BadException6 : Inherits Exception
Sub New()
End Sub
Sub New(message As String, innerException As Exception)
End Sub
Sub New(i As Integer, message As String)
End Sub
End Class
",
GetCA1032BasicMissingConstructorResultAt(line: 4, column: 14, typeName: "BadException6", constructor: "Public Sub New(message As String)"));
}
#endregion
#region Helpers
private static DiagnosticResult GetCA1032CSharpMissingConstructorResultAt(int line, int column, string typeName, string constructor)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(typeName, constructor);
private static DiagnosticResult GetCA1032BasicMissingConstructorResultAt(int line, int column, string typeName, string constructor)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(typeName, constructor);
#endregion
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using System.Text;
using System.Collections;
using System.Management.Automation;
using System.Globalization;
using System.Management.Automation.Runspaces;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Implementing type for WSManConfigurationOption
/// </summary>
public class WSManConfigurationOption : PSTransportOption
{
private const string Token = " {0}='{1}'";
private const string QuotasToken = "<Quotas {0} />";
internal const string AttribOutputBufferingMode = "OutputBufferingMode";
internal static System.Management.Automation.Runspaces.OutputBufferingMode? DefaultOutputBufferingMode = System.Management.Automation.Runspaces.OutputBufferingMode.Block;
private System.Management.Automation.Runspaces.OutputBufferingMode? _outputBufferingMode = null;
private const string AttribProcessIdleTimeout = "ProcessIdleTimeoutSec";
internal static readonly int? DefaultProcessIdleTimeout_ForPSRemoting = 0; // in seconds
internal static readonly int? DefaultProcessIdleTimeout_ForWorkflow = 1209600; // in seconds
private int? _processIdleTimeoutSec = null;
internal const string AttribMaxIdleTimeout = "MaxIdleTimeoutms";
internal static readonly int? DefaultMaxIdleTimeout = int.MaxValue;
private int? _maxIdleTimeoutSec = null;
internal const string AttribIdleTimeout = "IdleTimeoutms";
internal static readonly int? DefaultIdleTimeout = 7200; // 2 hours in seconds
private int? _idleTimeoutSec = null;
private const string AttribMaxConcurrentUsers = "MaxConcurrentUsers";
internal static readonly int? DefaultMaxConcurrentUsers = int.MaxValue;
private int? _maxConcurrentUsers = null;
private const string AttribMaxProcessesPerSession = "MaxProcessesPerShell";
internal static readonly int? DefaultMaxProcessesPerSession = int.MaxValue;
private int? _maxProcessesPerSession = null;
private const string AttribMaxMemoryPerSessionMB = "MaxMemoryPerShellMB";
internal static readonly int? DefaultMaxMemoryPerSessionMB = int.MaxValue;
private int? _maxMemoryPerSessionMB = null;
private const string AttribMaxSessions = "MaxShells";
internal static readonly int? DefaultMaxSessions = int.MaxValue;
private int? _maxSessions = null;
private const string AttribMaxSessionsPerUser = "MaxShellsPerUser";
internal static readonly int? DefaultMaxSessionsPerUser = int.MaxValue;
private int? _maxSessionsPerUser = null;
private const string AttribMaxConcurrentCommandsPerSession = "MaxConcurrentCommandsPerShell";
internal static readonly int? DefaultMaxConcurrentCommandsPerSession = int.MaxValue;
private int? _maxConcurrentCommandsPerSession = null;
/// <summary>
/// Constructor that instantiates with default values
/// </summary>
internal WSManConfigurationOption()
{
}
/// <summary>
/// LoadFromDefaults
/// </summary>
/// <param name="sessionType"></param>
/// <param name="keepAssigned"></param>
protected internal override void LoadFromDefaults(PSSessionType sessionType, bool keepAssigned)
{
if (!keepAssigned || !_outputBufferingMode.HasValue)
{
_outputBufferingMode = DefaultOutputBufferingMode;
}
if (!keepAssigned || !_processIdleTimeoutSec.HasValue)
{
_processIdleTimeoutSec
= sessionType == PSSessionType.Workflow
? DefaultProcessIdleTimeout_ForWorkflow
: DefaultProcessIdleTimeout_ForPSRemoting;
}
if (!keepAssigned || !_maxIdleTimeoutSec.HasValue)
{
_maxIdleTimeoutSec = DefaultMaxIdleTimeout;
}
if (!keepAssigned || !_idleTimeoutSec.HasValue)
{
_idleTimeoutSec = DefaultIdleTimeout;
}
if (!keepAssigned || !_maxConcurrentUsers.HasValue)
{
_maxConcurrentUsers = DefaultMaxConcurrentUsers;
}
if (!keepAssigned || !_maxProcessesPerSession.HasValue)
{
_maxProcessesPerSession = DefaultMaxProcessesPerSession;
}
if (!keepAssigned || !_maxMemoryPerSessionMB.HasValue)
{
_maxMemoryPerSessionMB = DefaultMaxMemoryPerSessionMB;
}
if (!keepAssigned || !_maxSessions.HasValue)
{
_maxSessions = DefaultMaxSessions;
}
if (!keepAssigned || !_maxSessionsPerUser.HasValue)
{
_maxSessionsPerUser = DefaultMaxSessionsPerUser;
}
if (!keepAssigned || !_maxConcurrentCommandsPerSession.HasValue)
{
_maxConcurrentCommandsPerSession = DefaultMaxConcurrentCommandsPerSession;
}
}
/// <summary>
/// ProcessIdleTimeout in Seconds
/// </summary>
public int? ProcessIdleTimeoutSec
{
get
{
return _processIdleTimeoutSec;
}
internal set
{
_processIdleTimeoutSec = value;
}
}
/// <summary>
/// MaxIdleTimeout in Seconds
/// </summary>
public int? MaxIdleTimeoutSec
{
get
{
return _maxIdleTimeoutSec;
}
internal set
{
_maxIdleTimeoutSec = value;
}
}
/// <summary>
/// MaxSessions
/// </summary>
public int? MaxSessions
{
get
{
return _maxSessions;
}
internal set
{
_maxSessions = value;
}
}
/// <summary>
/// MaxConcurrentCommandsPerSession
/// </summary>
public int? MaxConcurrentCommandsPerSession
{
get
{
return _maxConcurrentCommandsPerSession;
}
internal set
{
_maxConcurrentCommandsPerSession = value;
}
}
/// <summary>
/// MaxSessionsPerUser
/// </summary>
public int? MaxSessionsPerUser
{
get
{
return _maxSessionsPerUser;
}
internal set
{
_maxSessionsPerUser = value;
}
}
/// <summary>
/// MaxMemoryPerSessionMB
/// </summary>
public int? MaxMemoryPerSessionMB
{
get
{
return _maxMemoryPerSessionMB;
}
internal set
{
_maxMemoryPerSessionMB = value;
}
}
/// <summary>
/// MaxProcessesPerSession
/// </summary>
public int? MaxProcessesPerSession
{
get
{
return _maxProcessesPerSession;
}
internal set
{
_maxProcessesPerSession = value;
}
}
/// <summary>
/// MaxConcurrentUsers
/// </summary>
public int? MaxConcurrentUsers
{
get
{
return _maxConcurrentUsers;
}
internal set
{
_maxConcurrentUsers = value;
}
}
/// <summary>
/// IdleTimeout in Seconds
/// </summary>
public int? IdleTimeoutSec
{
get
{
return _idleTimeoutSec;
}
internal set
{
_idleTimeoutSec = value;
}
}
/// <summary>
/// OutputBufferingMode
/// </summary>
public System.Management.Automation.Runspaces.OutputBufferingMode? OutputBufferingMode
{
get
{
return _outputBufferingMode;
}
internal set
{
_outputBufferingMode = value;
}
}
internal override Hashtable ConstructQuotasAsHashtable()
{
Hashtable quotas = new Hashtable();
if (_idleTimeoutSec.HasValue)
{
quotas[AttribIdleTimeout] = (1000 * _idleTimeoutSec.Value).ToString(CultureInfo.InvariantCulture);
}
if (_maxConcurrentUsers.HasValue)
{
quotas[AttribMaxConcurrentUsers] = _maxConcurrentUsers.Value.ToString(CultureInfo.InvariantCulture);
}
if (_maxProcessesPerSession.HasValue)
{
quotas[AttribMaxProcessesPerSession] = _maxProcessesPerSession.Value.ToString(CultureInfo.InvariantCulture);
}
if (_maxMemoryPerSessionMB.HasValue)
{
quotas[AttribMaxMemoryPerSessionMB] = _maxMemoryPerSessionMB.Value.ToString(CultureInfo.InvariantCulture);
}
if (_maxSessionsPerUser.HasValue)
{
quotas[AttribMaxSessionsPerUser] = _maxSessionsPerUser.Value.ToString(CultureInfo.InvariantCulture);
}
if (_maxConcurrentCommandsPerSession.HasValue)
{
quotas[AttribMaxConcurrentCommandsPerSession] = _maxConcurrentCommandsPerSession.Value.ToString(CultureInfo.InvariantCulture);
}
if (_maxSessions.HasValue)
{
quotas[AttribMaxSessions] = _maxSessions.Value.ToString(CultureInfo.InvariantCulture);
}
if (_maxIdleTimeoutSec.HasValue)
{
quotas[AttribMaxIdleTimeout] = (1000 * _maxIdleTimeoutSec.Value).ToString(CultureInfo.InvariantCulture);
}
return quotas;
}
/// <summary>
/// ConstructQuotas
/// </summary>
/// <returns></returns>
internal override string ConstructQuotas()
{
StringBuilder sb = new StringBuilder();
if (_idleTimeoutSec.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribIdleTimeout, 1000 * _idleTimeoutSec));
}
if (_maxConcurrentUsers.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentUsers, _maxConcurrentUsers));
}
if (_maxProcessesPerSession.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxProcessesPerSession, _maxProcessesPerSession));
}
if (_maxMemoryPerSessionMB.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxMemoryPerSessionMB, _maxMemoryPerSessionMB));
}
if (_maxSessionsPerUser.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessionsPerUser, _maxSessionsPerUser));
}
if (_maxConcurrentCommandsPerSession.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentCommandsPerSession, _maxConcurrentCommandsPerSession));
}
if (_maxSessions.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessions, _maxSessions));
}
if (_maxIdleTimeoutSec.HasValue)
{
// Special case max int value for unbounded default.
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxIdleTimeout,
(_maxIdleTimeoutSec == int.MaxValue) ? _maxIdleTimeoutSec : (1000 * _maxIdleTimeoutSec)));
}
return sb.Length > 0
? string.Format(CultureInfo.InvariantCulture, QuotasToken, sb.ToString())
: string.Empty;
}
/// <summary>
/// ConstructOptionsXmlAttributes
/// </summary>
/// <returns></returns>
internal override string ConstructOptionsAsXmlAttributes()
{
StringBuilder sb = new StringBuilder();
if (_outputBufferingMode.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribOutputBufferingMode, _outputBufferingMode.ToString()));
}
if (_processIdleTimeoutSec.HasValue)
{
sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribProcessIdleTimeout, _processIdleTimeoutSec));
}
return sb.ToString();
}
/// <summary>
/// ConstructOptionsXmlAttributes
/// </summary>
/// <returns></returns>
internal override Hashtable ConstructOptionsAsHashtable()
{
Hashtable table = new Hashtable();
if (_outputBufferingMode.HasValue)
{
table[AttribOutputBufferingMode] = _outputBufferingMode.ToString();
}
if (_processIdleTimeoutSec.HasValue)
{
table[AttribProcessIdleTimeout] = _processIdleTimeoutSec;
}
return table;
}
}
/// <summary>
/// Command to create an object for WSManConfigurationOption
/// </summary>
[Cmdlet(VerbsCommon.New, "PSTransportOption", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=210608", RemotingCapability = RemotingCapability.None)]
[OutputType(typeof(WSManConfigurationOption))]
public sealed class NewPSTransportOptionCommand : PSCmdlet
{
private WSManConfigurationOption _option = new WSManConfigurationOption();
/// <summary>
/// MaxIdleTimeoutSec
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(60, 2147483)]
public int? MaxIdleTimeoutSec
{
get
{
return _option.MaxIdleTimeoutSec;
}
set
{
_option.MaxIdleTimeoutSec = value;
}
}
/// <summary>
/// ProcessIdleTimeoutSec
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(0, 1209600)]
public int? ProcessIdleTimeoutSec
{
get
{
return _option.ProcessIdleTimeoutSec;
}
set
{
_option.ProcessIdleTimeoutSec = value;
}
}
/// <summary>
/// MaxSessions
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)]
public int? MaxSessions
{
get
{
return _option.MaxSessions;
}
set
{
_option.MaxSessions = value;
}
}
/// <summary>
/// MaxConcurrentCommandsPerSession
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)]
public int? MaxConcurrentCommandsPerSession
{
get
{
return _option.MaxConcurrentCommandsPerSession;
}
set
{
_option.MaxConcurrentCommandsPerSession = value;
}
}
/// <summary>
/// MaxSessionsPerUser
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)]
public int? MaxSessionsPerUser
{
get
{
return _option.MaxSessionsPerUser;
}
set
{
_option.MaxSessionsPerUser = value;
}
}
/// <summary>
/// MaxMemoryPerSessionMB
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(5, int.MaxValue)]
public int? MaxMemoryPerSessionMB
{
get
{
return _option.MaxMemoryPerSessionMB;
}
set
{
_option.MaxMemoryPerSessionMB = value;
}
}
/// <summary>
/// MaxProcessesPerSession
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)]
public int? MaxProcessesPerSession
{
get
{
return _option.MaxProcessesPerSession;
}
set
{
_option.MaxProcessesPerSession = value;
}
}
/// <summary>
/// MaxConcurrentUsers
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, 100)]
public int? MaxConcurrentUsers
{
get
{
return _option.MaxConcurrentUsers;
}
set
{
_option.MaxConcurrentUsers = value;
}
}
/// <summary>
/// IdleTimeoutMs
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(60, 2147483)]
public int? IdleTimeoutSec
{
get
{
return _option.IdleTimeoutSec;
}
set
{
_option.IdleTimeoutSec = value;
}
}
/// <summary>
/// OutputBufferingMode
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public System.Management.Automation.Runspaces.OutputBufferingMode? OutputBufferingMode
{
get
{
return _option.OutputBufferingMode;
}
set
{
_option.OutputBufferingMode = value;
}
}
/// <summary>
/// Overriding the base method
/// </summary>
protected override void ProcessRecord()
{
this.WriteObject(_option);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="AspCompat.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* Support for ASP compatible execution mode of ASP.NET pages
*
* ASP compatible executions involves:
* 1) Running on COM+1.0 STA thread pool
* 2) Attachment of unmanaged intrinsics to unmanaged COM+1.0 context
* 3) Support for OnStartPage/OnEndPage
*
* Copyright (c) 2000, Microsoft Corporation
*/
namespace System.Web.Util {
using System.Runtime.InteropServices;
using System.Threading;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Security.Permissions;
using System.Runtime.Remoting.Messaging;
using Microsoft.Win32;
using System.Globalization;
using System.Web.Caching;
//
// Interface for unmanaged call to call back into managed code for
// intrinsics implementation
//
internal enum RequestString {
QueryString = 1,
Form = 2,
Cookies = 3,
ServerVars = 4
}
[ComImport, Guid("a1cca730-0e36-4870-aa7d-ca39c211f99d"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
internal interface IManagedContext {
[return: MarshalAs(UnmanagedType.I4)] int Context_IsPresent();
void Application_Lock();
void Application_UnLock();
[return: MarshalAs(UnmanagedType.BStr)] String Application_GetContentsNames();
[return: MarshalAs(UnmanagedType.BStr)] String Application_GetStaticNames();
Object Application_GetContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
void Application_SetContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In] Object obj);
void Application_RemoveContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
void Application_RemoveAllContentsObjects();
Object Application_GetStaticObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
[return: MarshalAs(UnmanagedType.BStr)] String Request_GetAsString([In, MarshalAs(UnmanagedType.I4)] int what);
[return: MarshalAs(UnmanagedType.BStr)] String Request_GetCookiesAsString();
[return: MarshalAs(UnmanagedType.I4)] int Request_GetTotalBytes();
[return: MarshalAs(UnmanagedType.I4)] int Request_BinaryRead([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), Out] byte[] bytes, int size);
[return: MarshalAs(UnmanagedType.BStr)] String Response_GetCookiesAsString();
void Response_AddCookie([In, MarshalAs(UnmanagedType.LPWStr)] String name);
void Response_SetCookieText([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.LPWStr)] String text);
void Response_SetCookieSubValue([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.LPWStr)] String key, [In, MarshalAs(UnmanagedType.LPWStr)] String value);
void Response_SetCookieExpires([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.R8)] double dtExpires);
void Response_SetCookieDomain([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.LPWStr)] String domain);
void Response_SetCookiePath([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.LPWStr)] String path);
void Response_SetCookieSecure([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.I4)] int secure);
void Response_Write([In, MarshalAs(UnmanagedType.LPWStr)] String text);
void Response_BinaryWrite([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1), In] byte[] bytes, int size);
void Response_Redirect([In, MarshalAs(UnmanagedType.LPWStr)] String url);
void Response_AddHeader([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In, MarshalAs(UnmanagedType.LPWStr)] String value);
void Response_Pics([In, MarshalAs(UnmanagedType.LPWStr)] String value);
void Response_Clear();
void Response_Flush();
void Response_End();
void Response_AppendToLog([In, MarshalAs(UnmanagedType.LPWStr)] String entry);
[return: MarshalAs(UnmanagedType.BStr)] String Response_GetContentType();
void Response_SetContentType([In, MarshalAs(UnmanagedType.LPWStr)] String contentType);
[return: MarshalAs(UnmanagedType.BStr)] String Response_GetCharSet();
void Response_SetCharSet([In, MarshalAs(UnmanagedType.LPWStr)] String charSet);
[return: MarshalAs(UnmanagedType.BStr)] String Response_GetCacheControl();
void Response_SetCacheControl([In, MarshalAs(UnmanagedType.LPWStr)] String cacheControl);
[return: MarshalAs(UnmanagedType.BStr)] String Response_GetStatus();
void Response_SetStatus([In, MarshalAs(UnmanagedType.LPWStr)] String status);
[return: MarshalAs(UnmanagedType.I4)] int Response_GetExpiresMinutes();
void Response_SetExpiresMinutes([In, MarshalAs(UnmanagedType.I4)] int expiresMinutes);
[return: MarshalAs(UnmanagedType.R8)] double Response_GetExpiresAbsolute();
void Response_SetExpiresAbsolute([In, MarshalAs(UnmanagedType.R8)] double dtExpires);
[return: MarshalAs(UnmanagedType.I4)] int Response_GetIsBuffering();
void Response_SetIsBuffering([In, MarshalAs(UnmanagedType.I4)] int isBuffering);
[return: MarshalAs(UnmanagedType.I4)] int Response_IsClientConnected();
[return: MarshalAs(UnmanagedType.Interface)] Object Server_CreateObject([In, MarshalAs(UnmanagedType.LPWStr)] String progId);
[return: MarshalAs(UnmanagedType.BStr)] String Server_MapPath([In, MarshalAs(UnmanagedType.LPWStr)] String logicalPath);
[return: MarshalAs(UnmanagedType.BStr)] String Server_HTMLEncode([In, MarshalAs(UnmanagedType.LPWStr)] String str);
[return: MarshalAs(UnmanagedType.BStr)] String Server_URLEncode([In, MarshalAs(UnmanagedType.LPWStr)] String str);
[return: MarshalAs(UnmanagedType.BStr)] String Server_URLPathEncode([In, MarshalAs(UnmanagedType.LPWStr)] String str);
[return: MarshalAs(UnmanagedType.I4)] int Server_GetScriptTimeout();
void Server_SetScriptTimeout([In, MarshalAs(UnmanagedType.I4)] int timeoutSeconds);
void Server_Execute([In, MarshalAs(UnmanagedType.LPWStr)] String url);
void Server_Transfer([In, MarshalAs(UnmanagedType.LPWStr)] String url);
[return: MarshalAs(UnmanagedType.I4)] int Session_IsPresent();
[return: MarshalAs(UnmanagedType.BStr)] String Session_GetID();
[return: MarshalAs(UnmanagedType.I4)] int Session_GetTimeout();
void Session_SetTimeout([In, MarshalAs(UnmanagedType.I4)] int value);
[return: MarshalAs(UnmanagedType.I4)] int Session_GetCodePage();
void Session_SetCodePage([In, MarshalAs(UnmanagedType.I4)] int value);
[return: MarshalAs(UnmanagedType.I4)] int Session_GetLCID();
void Session_SetLCID([In, MarshalAs(UnmanagedType.I4)] int value);
void Session_Abandon();
[return: MarshalAs(UnmanagedType.BStr)] String Session_GetContentsNames();
[return: MarshalAs(UnmanagedType.BStr)] String Session_GetStaticNames();
Object Session_GetContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
void Session_SetContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name, [In]Object obj);
void Session_RemoveContentsObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
void Session_RemoveAllContentsObjects();
Object Session_GetStaticObject([In, MarshalAs(UnmanagedType.LPWStr)] String name);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
//
// Delegate to the code executing on within ASP compat context
// (provided by the caller and used internally to wrap it)
//
internal delegate void AspCompatCallback();
//
// Utility class for AspCompat work
//
internal class AspCompatApplicationStep : HttpApplication.IExecutionStep, IManagedContext {
private GCHandle _rootedThis; // for the duration of async
private HttpContext _context; // context for callback
private HttpApplication _app; // app instance to run the code under
private String _sessionId; // to run session on the same STA thread
private AspCompatCallback _code; // the code to run in asp compat mode
private EventHandler _codeEventHandler;// alt to running _code is to raise event
private Object _codeEventSource;
private EventArgs _codeEventArgs;
private Exception _error; // error during the execution
private HttpAsyncResult _ar; // async result returned to the caller
private bool _syncCaller; // called synchronously?
private AspCompatCallback _execCallback; // keep delegate as a member (not gc it)
private WorkItemCallback _compCallback; // keep delegate as a member (not gc it)
private ArrayList _staComponents; // list of STA components to be released
private static char[] TabOrBackSpace = new char[] { '\t', '\b' };
internal AspCompatApplicationStep(HttpContext context, AspCompatCallback code) {
_code = code;
Init(context, context.ApplicationInstance);
}
private AspCompatApplicationStep(HttpContext context, HttpApplication app, String sessionId, EventHandler codeEventHandler, Object codeEventSource, EventArgs codeEventArgs) {
_codeEventHandler = codeEventHandler;
_codeEventSource = codeEventSource;
_codeEventArgs = codeEventArgs;
_sessionId = sessionId;
Init(context, app);
}
private void Init(HttpContext context, HttpApplication app) {
_context = context;
_app = app;
_execCallback = new AspCompatCallback(this.OnAspCompatExecution);
_compCallback = new WorkItemCallback(this.OnAspCompatCompletion);
if (_sessionId == null && _context != null && _context.Session != null)
_sessionId = _context.Session.SessionID;
}
private void MarkCallContext(AspCompatApplicationStep mark) {
CallContext.SetData("AspCompat", mark);
}
private static AspCompatApplicationStep Current {
get { return (AspCompatApplicationStep)CallContext.GetData("AspCompat"); }
}
internal static bool IsInAspCompatMode {
get { return (Current != null); }
}
// IExecutionStep implementation
void HttpApplication.IExecutionStep.Execute() {
SynchronizationContextUtil.ValidateModeForAspCompat();
if (_code != null) {
_code();
}
else if (_codeEventHandler != null) {
_codeEventHandler(_codeEventSource, _codeEventArgs);
}
}
bool HttpApplication.IExecutionStep.CompletedSynchronously {
get { return true; }
}
bool HttpApplication.IExecutionStep.IsCancellable {
get { return (_context != null); }
}
// OnPageStart / OnPageEnd support
private void RememberStaComponent(Object component) {
if (_staComponents == null)
_staComponents = new ArrayList();
_staComponents.Add(component);
}
private bool IsStaComponentInSessionState(Object component) {
if (_context == null)
return false;
HttpSessionState session = _context.Session;
if (session == null)
return false;
// enumerate objects and call OnPageStart
int numObjects = session.Count;
for (int i = 0; i < numObjects; i++) {
if (component == session[i])
return true;
}
return false;
}
internal static bool AnyStaObjectsInSessionState(HttpSessionState session) {
if (session == null)
return false;
int numObjects = session.Count;
for (int i = 0; i < numObjects; i++) {
Object component = session[i];
if (component != null && component.GetType().FullName == "System.__ComObject") {
if (UnsafeNativeMethods.AspCompatIsApartmentComponent(component) != 0)
return true;
}
}
return false;
}
internal static void OnPageStart(Object component) {
// has to be in asp compat mode
if (!IsInAspCompatMode)
return;
int rc = UnsafeNativeMethods.AspCompatOnPageStart(component);
if (rc != 1)
throw new HttpException(SR.GetString(SR.Error_onpagestart));
if (UnsafeNativeMethods.AspCompatIsApartmentComponent(component) != 0)
Current.RememberStaComponent(component);
}
internal static void OnPageStartSessionObjects() {
// has to be in asp compat mode
if (!IsInAspCompatMode)
return;
// get session state if any
HttpContext context = Current._context;
if (context == null)
return;
HttpSessionState session = context.Session;
if (session == null)
return;
// enumerate objects and call OnPageStart
int numObjects = session.Count;
for (int i = 0; i < numObjects; i++) {
Object component = session[i];
if (component != null && !(component is string)) {
int rc = UnsafeNativeMethods.AspCompatOnPageStart(component);
if (rc != 1)
throw new HttpException(SR.GetString(SR.Error_onpagestart));
}
}
}
// Disallow Apartment components in when ASPCOMPAT is off
internal static void CheckThreadingModel(String progidDisplayName, Guid clsid) {
if (IsInAspCompatMode)
return;
// try cache first
CacheInternal cacheInternal = HttpRuntime.CacheInternal;
String key = CacheInternal.PrefixAspCompatThreading + progidDisplayName;
String threadingModel = (String)cacheInternal.Get(key);
RegistryKey regKey = null;
if (threadingModel == null) {
try {
regKey = Registry.ClassesRoot.OpenSubKey("CLSID\\{" + clsid + "}\\InprocServer32" );
if (regKey != null)
threadingModel = (String)regKey.GetValue("ThreadingModel");
}
catch {
}
finally {
if (regKey != null)
regKey.Close();
}
if (threadingModel == null)
threadingModel = String.Empty;
cacheInternal.UtcInsert(key, threadingModel);
}
if (StringUtil.EqualsIgnoreCase(threadingModel, "Apartment")) {
throw new HttpException(
SR.GetString(SR.Apartment_component_not_allowed, progidDisplayName));
}
}
// Async patern
[SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
internal /*public*/ IAsyncResult BeginAspCompatExecution(AsyncCallback cb, object extraData) {
SynchronizationContextUtil.ValidateModeForAspCompat();
if (IsInAspCompatMode) {
// already in AspCompatMode -- execute synchronously
bool sync = true;
Exception error = _app.ExecuteStep(this, ref sync);
_ar = new HttpAsyncResult(cb, extraData, true, null, error);
_syncCaller = true;
}
else {
_ar = new HttpAsyncResult(cb, extraData);
_syncCaller = (cb == null);
_rootedThis = GCHandle.Alloc(this);
// send requests from the same session to the same STA thread
bool sharedActivity = (_sessionId != null);
int activityHash = sharedActivity ? _sessionId.GetHashCode() : 0;
if (UnsafeNativeMethods.AspCompatProcessRequest(_execCallback, this, sharedActivity, activityHash) != 1) {
// failed to queue up the execution in ASP compat mode
_rootedThis.Free();
_ar.Complete(true, null, new HttpException(SR.GetString(SR.Cannot_access_AspCompat)));
}
}
return _ar;
}
internal /*public*/ void EndAspCompatExecution(IAsyncResult ar) {
Debug.Assert(_ar == ar);
_ar.End();
}
// helpers to raise event on STA threads in ASPCOMAP mode
internal static void RaiseAspCompatEvent(HttpContext context, HttpApplication app, String sessionId, EventHandler eventHandler, Object source, EventArgs eventArgs) {
AspCompatApplicationStep step = new AspCompatApplicationStep(context, app, sessionId, eventHandler, source, eventArgs);
IAsyncResult ar = step.BeginAspCompatExecution(null, null);
// wait until done
if (!ar.IsCompleted) {
WaitHandle h = ar.AsyncWaitHandle;
if (h != null) {
h.WaitOne();
}
else {
while (!ar.IsCompleted)
Thread.Sleep(1);
}
}
step.EndAspCompatExecution(ar);
}
private void ExecuteAspCompatCode() {
MarkCallContext(this);
try {
bool sync = true;
if (_context != null) {
ThreadContext threadContext = null;
try {
threadContext = _app.OnThreadEnter();
_error = _app.ExecuteStep(this, ref sync);
}
finally {
if (threadContext != null) {
threadContext.DisassociateFromCurrentThread();
}
}
}
else {
_error = _app.ExecuteStep(this, ref sync);
}
}
finally {
MarkCallContext(null);
}
}
private void OnAspCompatExecution() {
try {
if (_syncCaller) {
// for synchronous caller don't take the app lock (could dead lock because we switched threads)
ExecuteAspCompatCode();
}
else {
lock (_app) {
ExecuteAspCompatCode();
}
}
}
finally {
// call PageEnd
UnsafeNativeMethods.AspCompatOnPageEnd();
// release all STA components not in session
if (_staComponents != null) {
foreach (Object component in _staComponents) {
if (!IsStaComponentInSessionState(component))
Marshal.ReleaseComObject(component);
}
}
// notify any code polling for completion before QueueUserWorkItem to avoid deadlocks
// (the completion work item could be help up by the threads doing polling)
_ar.SetComplete();
// reschedule execution back to the regular thread pool
WorkItem.PostInternal(_compCallback);
}
}
private void OnAspCompatCompletion() {
_rootedThis.Free();
_ar.Complete(false, null, _error); // resume the application execution
}
//
// Implemenation of IManagedContext
//
// As we use tab as separator, marshaling data will be corrupted
// when user inputs contain any tabs. Therefore, we have tabs in user
// inputs encoded before marshaling (Dev10 #692392)
private static String EncodeTab(String value) {
if (String.IsNullOrEmpty(value) || value.IndexOfAny(TabOrBackSpace) < 0) {
return value;
}
return value.Replace("\b", "\bB").Replace("\t", "\bT");
}
private static String EncodeTab(object value) {
return EncodeTab((String)value);
}
private static String CollectionToString(NameValueCollection c) {
// 'easy' marshalling format key, # of strings, strings, ... (all '\t' separated)
int n = c.Count;
if (n == 0)
return String.Empty;
StringBuilder sb = new StringBuilder(256);
for (int i = 0; i < n; i++) {
String key = EncodeTab(c.GetKey(i));
String[] vv = c.GetValues(i);
int len = (vv != null) ? vv.Length : 0;
sb.Append(key + "\t" + len + "\t");
for (int j = 0; j < len; j++) {
sb.Append(EncodeTab(vv[j]));
if (j < vv.Length-1)
sb.Append("\t");
}
if (i < n-1)
sb.Append("\t");
}
return sb.ToString();
}
private static String CookiesToString(HttpCookieCollection cc) {
// marshalling of cookies as string (all '\t' separated):
// all cookies as one ';' separated string
// # of cookies
// [for each cookie] name, text, # of keys, key, value, ...
StringBuilder sb = new StringBuilder(256); // resulting string (per above)
StringBuilder st = new StringBuilder(128); // all cookies string
int numCookies = cc.Count;
sb.Append(numCookies.ToString() + "\t");
for (int i = 0; i < numCookies; i++) {
HttpCookie c = cc[i];
String name = EncodeTab(c.Name);
String value = EncodeTab(c.Value);
sb.Append(name + "\t" + value + "\t");
if (i > 0)
st.Append(";" + name + "=" + value);
else
st.Append(name + "=" + value);
NameValueCollection cv = c.Values;
int ncv = cv.Count;
bool hasNotEmptyKeys = false;
if (cv.HasKeys()) {
for (int j = 0; j < ncv; j++) {
String key = cv.GetKey(j);
if (!String.IsNullOrEmpty(key)) {
hasNotEmptyKeys = true;
break;
}
}
}
if (hasNotEmptyKeys) {
sb.Append(ncv + "\t");
for (int j = 0; j < ncv; j++)
sb.Append(EncodeTab(cv.GetKey(j)) + "\t" + EncodeTab(cv.Get(j)) + "\t");
}
else {
sb.Append("0\t");
}
}
// append the contructed text to the all cookies string
st.Append("\t");
st.Append(sb.ToString());
return st.ToString();
}
private static String StringArrayToString(String[] ss) {
// construct tab separeted string for marshalling
StringBuilder sb = new StringBuilder(256);
if (ss != null) {
for (int i = 0; i < ss.Length; i++) {
if (i > 0)
sb.Append("\t");
sb.Append(EncodeTab(ss[i]));
}
}
return sb.ToString();
}
private static String EnumKeysToString(IEnumerator e) {
StringBuilder sb = new StringBuilder(256);
if (e.MoveNext()) {
sb.Append(EncodeTab(e.Current));
while (e.MoveNext()) {
sb.Append("\t");
sb.Append(EncodeTab(e.Current));
}
}
return sb.ToString();
}
private static String DictEnumKeysToString(IDictionaryEnumerator e) {
StringBuilder sb = new StringBuilder(256);
if (e.MoveNext()) {
sb.Append(EncodeTab(e.Key));
while (e.MoveNext()) {
sb.Append("\t");
sb.Append(EncodeTab(e.Key));
}
}
return sb.ToString();
}
int IManagedContext.Context_IsPresent() {
return (_context != null) ? 1 : 0;
}
void IManagedContext.Application_Lock() {
_context.Application.Lock();
}
void IManagedContext.Application_UnLock() {
_context.Application.UnLock();
}
String IManagedContext.Application_GetContentsNames() {
return StringArrayToString(_context.Application.AllKeys);
}
String IManagedContext.Application_GetStaticNames() {
return DictEnumKeysToString((IDictionaryEnumerator)_context.Application.StaticObjects.GetEnumerator());
}
Object IManagedContext.Application_GetContentsObject(String name) {
return _context.Application[name];
}
void IManagedContext.Application_SetContentsObject(String name, Object obj) {
_context.Application[name] = obj;
}
void IManagedContext.Application_RemoveContentsObject(String name) {
_context.Application.Remove(name);
}
void IManagedContext.Application_RemoveAllContentsObjects() {
_context.Application.RemoveAll();
}
Object IManagedContext.Application_GetStaticObject(String name) {
return _context.Application.StaticObjects[name];
}
String IManagedContext.Request_GetAsString(int what) {
String s = String.Empty;
switch ((RequestString)what) {
case RequestString.QueryString:
return CollectionToString(_context.Request.QueryString);
case RequestString.Form:
return CollectionToString(_context.Request.Form);
case RequestString.Cookies:
return String.Empty;
case RequestString.ServerVars:
return CollectionToString(_context.Request.ServerVariables);
}
return s;
}
String IManagedContext.Request_GetCookiesAsString() {
return CookiesToString(_context.Request.Cookies);
}
int IManagedContext.Request_GetTotalBytes() {
return _context.Request.TotalBytes;
}
int IManagedContext.Request_BinaryRead(byte[] bytes, int size) {
return _context.Request.InputStream.Read(bytes, 0, size);
}
String IManagedContext.Response_GetCookiesAsString() {
return CookiesToString(_context.Response.Cookies);
}
void IManagedContext.Response_AddCookie(String name) {
_context.Response.Cookies.Add(new HttpCookie(name));
}
void IManagedContext.Response_SetCookieText(String name, String text) {
_context.Response.Cookies[name].Value = text;
}
void IManagedContext.Response_SetCookieSubValue(String name, String key, String value) {
_context.Response.Cookies[name].Values[key] = value;
}
void IManagedContext.Response_SetCookieExpires(String name, double dtExpires) {
_context.Response.Cookies[name].Expires = DateTime.FromOADate(dtExpires);
}
void IManagedContext.Response_SetCookieDomain(String name, String domain) {
_context.Response.Cookies[name].Domain = domain;
}
void IManagedContext.Response_SetCookiePath(String name, String path) {
_context.Response.Cookies[name].Path = path;
}
void IManagedContext.Response_SetCookieSecure(String name, int secure) {
_context.Response.Cookies[name].Secure = (secure != 0);
}
void IManagedContext.Response_Write(String text) {
_context.Response.Write(text);
}
void IManagedContext.Response_BinaryWrite(byte[] bytes, int size) {
_context.Response.OutputStream.Write(bytes, 0, size);
}
void IManagedContext.Response_Redirect(String url) {
_context.Response.Redirect(url);
}
void IManagedContext.Response_AddHeader(String name, String value) {
_context.Response.AppendHeader(name, value);
}
void IManagedContext.Response_Pics(String value) {
_context.Response.Pics(value);
}
void IManagedContext.Response_Clear() {
_context.Response.Clear();
}
void IManagedContext.Response_Flush() {
_context.Response.Flush();
}
void IManagedContext.Response_End() {
_context.Response.End();
}
void IManagedContext.Response_AppendToLog(String entry) {
_context.Response.AppendToLog(entry);
}
String IManagedContext.Response_GetContentType() {
return _context.Response.ContentType;
}
void IManagedContext.Response_SetContentType(String contentType) {
_context.Response.ContentType = contentType;
}
String IManagedContext.Response_GetCharSet() {
return _context.Response.Charset;
}
void IManagedContext.Response_SetCharSet(String charSet) {
_context.Response.Charset = charSet;
}
String IManagedContext.Response_GetCacheControl() {
return _context.Response.CacheControl;
}
void IManagedContext.Response_SetCacheControl(String cacheControl) {
_context.Response.CacheControl = cacheControl;
}
String IManagedContext.Response_GetStatus() {
return _context.Response.Status;
}
void IManagedContext.Response_SetStatus(String status) {
_context.Response.Status = status;
}
int IManagedContext.Response_GetExpiresMinutes() {
return _context.Response.Expires;
}
void IManagedContext.Response_SetExpiresMinutes(int expiresMinutes) {
_context.Response.Expires = expiresMinutes;
}
double IManagedContext.Response_GetExpiresAbsolute() {
return _context.Response.ExpiresAbsolute.ToOADate();
}
void IManagedContext.Response_SetExpiresAbsolute(double dtExpires) {
_context.Response.ExpiresAbsolute = DateTime.FromOADate(dtExpires);
}
int IManagedContext.Response_GetIsBuffering() {
return _context.Response.BufferOutput ? 1 : 0;
}
void IManagedContext.Response_SetIsBuffering(int isBuffering) {
_context.Response.BufferOutput = (isBuffering != 0);
}
int IManagedContext.Response_IsClientConnected() {
return _context.Response.IsClientConnected ? 1 : 0;
}
Object IManagedContext.Server_CreateObject(String progId) {
return _context.Server.CreateObject(progId);
}
String IManagedContext.Server_MapPath(String logicalPath) {
return _context.Server.MapPath(logicalPath);
}
String IManagedContext.Server_HTMLEncode(String str) {
return HttpUtility.HtmlEncode(str);
}
String IManagedContext.Server_URLEncode(String str) {
return _context.Server.UrlEncode(str);
}
String IManagedContext.Server_URLPathEncode(String str) {
return _context.Server.UrlPathEncode(str);
}
int IManagedContext.Server_GetScriptTimeout() {
return _context.Server.ScriptTimeout;
}
void IManagedContext.Server_SetScriptTimeout(int timeoutSeconds) {
_context.Server.ScriptTimeout = timeoutSeconds;
}
void IManagedContext.Server_Execute(String url) {
_context.Server.Execute(url);
}
void IManagedContext.Server_Transfer(String url) {
_context.Server.Transfer(url);
}
int IManagedContext.Session_IsPresent() {
return (_context.Session != null) ? 1 : 0;
}
String IManagedContext.Session_GetID() {
return _context.Session.SessionID;
}
int IManagedContext.Session_GetTimeout() {
return _context.Session.Timeout;
}
void IManagedContext.Session_SetTimeout(int value) {
_context.Session.Timeout = value;
}
int IManagedContext.Session_GetCodePage() {
return _context.Session.CodePage;
}
void IManagedContext.Session_SetCodePage(int value) {
_context.Session.CodePage = value;
}
int IManagedContext.Session_GetLCID() {
return _context.Session.LCID;
}
void IManagedContext.Session_SetLCID(int value) {
_context.Session.LCID = value;
}
void IManagedContext.Session_Abandon() {
_context.Session.Abandon();
}
String IManagedContext.Session_GetContentsNames() {
return EnumKeysToString(_context.Session.GetEnumerator());
}
String IManagedContext.Session_GetStaticNames() {
return DictEnumKeysToString((IDictionaryEnumerator)_context.Session.StaticObjects.GetEnumerator());
}
Object IManagedContext.Session_GetContentsObject(String name) {
return _context.Session[name];
}
void IManagedContext.Session_SetContentsObject(String name, Object obj) {
_context.Session[name] = obj;
}
void IManagedContext.Session_RemoveContentsObject(String name) {
_context.Session.Remove(name);
}
void IManagedContext.Session_RemoveAllContentsObjects() {
_context.Session.RemoveAll();
}
Object IManagedContext.Session_GetStaticObject(String name) {
return _context.Session.StaticObjects[name];
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using BookingApp.Areas.HelpPage.ModelDescriptions;
using BookingApp.Areas.HelpPage.Models;
namespace BookingApp.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default01.default01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default01.default01;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue(1)]
dynamic i)
{
if (i == 1)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo();
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default02.default02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default02.default02;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue(1)]
dynamic i)
{
if (i == 2)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default02a.default02a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default02a.default02a;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue(1)]
dynamic i)
{
if (i == 2)
return 0;
return 1;
}
}
public class Test
{
private static dynamic s_i = 2;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(s_i);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default02b.default02b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default02b.default02b;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue(1)]
dynamic i)
{
if (i == null)
return 0;
return 1;
}
}
public class Test
{
private const dynamic i = null;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default02c.default02c
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default02c.default02c;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue(1)]
dynamic i)
{
if (i == typeof(int?))
return 0;
return 1;
}
}
public class Test
{
private static dynamic s_i = typeof(int?);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(s_i);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default04.default04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default04.default04;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue((long)2)]
dynamic i)
{
if (i == 2)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo();
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default05.default05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default05.default05;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("test")]
dynamic i)
{
if (i == "test")
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo();
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default06.default06
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default06.default06;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("test2")]
dynamic i)
{
if (i == "test")
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo("test");
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default06a.default06a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default06a.default06a;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("test2")]
dynamic i)
{
if (i == null)
return 0;
return 1;
}
}
public class Test
{
private const dynamic i = null;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default06b.default06b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default06b.default06b;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("test2")]
dynamic i)
{
if (i.Length == 0 && i.GetType() == typeof(int[]))
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(new int[0]);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default06c.default06c
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default06c.default06c;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("test2")]
dynamic i)
{
if (i == 10)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(10);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default07.default07
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default07.default07;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue(1 + 1)]
dynamic i)
{
if (i == 2)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo();
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default09.default09
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default09.default09;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("foo")]
dynamic i, [Optional, DefaultParameterValue("boo")]
string str)
{
if (i == "foo" && str == "boo")
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo();
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default09a.default09a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default09a.default09a;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue(10)]
dynamic i, [Optional, DefaultParameterValue("boo")]
dynamic str)
{
if (i == null && str == null)
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(null, null);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default09b.default09b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default09b.default09b;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(19,14\).*CS0414</Expects>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("foo")]
dynamic i, [Optional, DefaultParameterValue(null)]
dynamic str)
{
if (i == 5 && str == null)
return 0;
return 1;
}
}
public class Test
{
private static int? s_i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(5);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default10.default10
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default10.default10;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("foo")]
dynamic i, [Optional, DefaultParameterValue("boo")]
string str)
{
if (i == 10 && str == "bar")
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(10, "bar");
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default10a.default10a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default10a.default10a;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("foo")]
string i, [Optional, DefaultParameterValue("boo")]
dynamic str)
{
if (i == "test" && str == typeof(int))
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo("test", typeof(int));
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default10b.default10b
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default10b.default10b;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("foo")]
dynamic i, [Optional, DefaultParameterValue("boo")]
dynamic str)
{
if (i == "test" && str == "bar")
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo("test", "bar");
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default10c.default10c
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.defaultParameter.default10c.default10c;
// <Area>Use of Optional Paramaters</Area>
// <Title>Optional Paramaters declared with Attributes</Title>
// <Description>Optional Paramaters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional, DefaultParameterValue("foo")]
string i, [Optional, DefaultParameterValue("boo")]
string str)
{
if (i == "test" && str == "bar")
return 0;
return 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo("test", "bar");
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Models;
namespace Microsoft.WindowsAzure.Management.Models
{
/// <summary>
/// The List Subscription Operations operation response.
/// </summary>
public partial class SubscriptionListOperationsResponse : AzureOperationResponse
{
private string _continuationToken;
/// <summary>
/// Optional. The string that can be used to return the rest of the
/// list. Subsequent requests must include this parameter to continue
/// listing operations from where the last response left off. This
/// element exists only if the complete list of subscription
/// operations was not returned.
/// </summary>
public string ContinuationToken
{
get { return this._continuationToken; }
set { this._continuationToken = value; }
}
private IList<SubscriptionListOperationsResponse.SubscriptionOperation> _subscriptionOperations;
/// <summary>
/// Optional. The list of operations that have been performed on the
/// subscription during the specified timeframe.
/// </summary>
public IList<SubscriptionListOperationsResponse.SubscriptionOperation> SubscriptionOperations
{
get { return this._subscriptionOperations; }
set { this._subscriptionOperations = value; }
}
/// <summary>
/// Initializes a new instance of the
/// SubscriptionListOperationsResponse class.
/// </summary>
public SubscriptionListOperationsResponse()
{
this.SubscriptionOperations = new LazyList<SubscriptionListOperationsResponse.SubscriptionOperation>();
}
/// <summary>
/// A collection of attributes that identify the source of the
/// operation.
/// </summary>
public partial class OperationCallerDetails
{
private string _clientIPAddress;
/// <summary>
/// Optional. The IP address of the client computer that initiated
/// the operation. This element is returned only if
/// UsedServiceManagementApi is true.
/// </summary>
public string ClientIPAddress
{
get { return this._clientIPAddress; }
set { this._clientIPAddress = value; }
}
private string _subscriptionCertificateThumbprint;
/// <summary>
/// Optional. The thumbprint of the subscription certificate used
/// to initiate the operation.
/// </summary>
public string SubscriptionCertificateThumbprint
{
get { return this._subscriptionCertificateThumbprint; }
set { this._subscriptionCertificateThumbprint = value; }
}
private bool _usedServiceManagementApi;
/// <summary>
/// Optional. Indicates whether the operation was initiated by
/// using the Service Management API. This will be false if it was
/// initiated by another source, such as the Management Portal.
/// </summary>
public bool UsedServiceManagementApi
{
get { return this._usedServiceManagementApi; }
set { this._usedServiceManagementApi = value; }
}
private string _userEmailAddress;
/// <summary>
/// Optional. The email associated with the Windows Live ID of the
/// user who initiated the operation from the Management Portal.
/// This element is returned only if UsedServiceManagementApi is
/// false.
/// </summary>
public string UserEmailAddress
{
get { return this._userEmailAddress; }
set { this._userEmailAddress = value; }
}
/// <summary>
/// Initializes a new instance of the OperationCallerDetails class.
/// </summary>
public OperationCallerDetails()
{
}
}
/// <summary>
/// An operation that has been performed on the subscription during the
/// specified timeframe.
/// </summary>
public partial class SubscriptionOperation
{
private SubscriptionListOperationsResponse.OperationCallerDetails _operationCaller;
/// <summary>
/// Optional. A collection of attributes that identify the source
/// of the operation.
/// </summary>
public SubscriptionListOperationsResponse.OperationCallerDetails OperationCaller
{
get { return this._operationCaller; }
set { this._operationCaller = value; }
}
private DateTime _operationCompletedTime;
/// <summary>
/// Optional. The time that the operation finished executing.
/// </summary>
public DateTime OperationCompletedTime
{
get { return this._operationCompletedTime; }
set { this._operationCompletedTime = value; }
}
private string _operationId;
/// <summary>
/// Optional. The globally unique identifier (GUID) of the
/// operation.
/// </summary>
public string OperationId
{
get { return this._operationId; }
set { this._operationId = value; }
}
private string _operationName;
/// <summary>
/// Optional. The name of the performed operation.
/// </summary>
public string OperationName
{
get { return this._operationName; }
set { this._operationName = value; }
}
private string _operationObjectId;
/// <summary>
/// Optional. The target object for the operation. This value is
/// equal to the URL for performing an HTTP GET on the object, and
/// corresponds to the same values for the ObjectIdFilter in the
/// request.
/// </summary>
public string OperationObjectId
{
get { return this._operationObjectId; }
set { this._operationObjectId = value; }
}
private IDictionary<string, string> _operationParameters;
/// <summary>
/// Optional. The collection of parameters for the performed
/// operation.
/// </summary>
public IDictionary<string, string> OperationParameters
{
get { return this._operationParameters; }
set { this._operationParameters = value; }
}
private DateTime _operationStartedTime;
/// <summary>
/// Optional. The time that the operation started to execute.
/// </summary>
public DateTime OperationStartedTime
{
get { return this._operationStartedTime; }
set { this._operationStartedTime = value; }
}
private string _operationStatus;
/// <summary>
/// Optional. An object that contains information on the current
/// status of the operation. The object returned has the following
/// XML format: <OperationStatus>
/// <ID>339c6c13-1f81-412f-9bc6-00e9c5876695</ID>
/// <Status>Succeeded</Status>
/// <HttpStatusCode>200</HttpStatusCode> </OperationStatus>.
/// Possible values of the Status element, whichholds the
/// operation status, are: Succeeded, Failed, or InProgress.
/// </summary>
public string OperationStatus
{
get { return this._operationStatus; }
set { this._operationStatus = value; }
}
/// <summary>
/// Initializes a new instance of the SubscriptionOperation class.
/// </summary>
public SubscriptionOperation()
{
this.OperationParameters = new LazyDictionary<string, string>();
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace CslaGenerator.Controls
{
// Custom control that draws the caption for each pane. Contains an active
// state and draws the caption different for each state. Caption is drawn
// with a gradient fill and antialias font.
public class PaneCaption : UserControl
{
private class Consts
{
public const int DefaultHeight = 26;
public const string DefaultFontName = "Tahoma";
public const int DefaultFontSize = 12;
public const int PosOffset = 4;
}
private bool m_active = false;
private bool m_antiAlias = false;
private bool m_allowActive = false;
private string m_text = string.Empty;
private Color m_colorActiveText = Color.Black;
private Color m_colorInactiveText = Color.White;
private Color m_colorActiveLow = Color.FromArgb(255, 165, 78);
private Color m_colorActiveHigh = Color.FromArgb(255, 225, 155);
private Color m_colorInactiveLow = Color.FromArgb(3, 55, 145);
private Color m_colorInactiveHigh = Color.FromArgb(90, 135, 215);
private SolidBrush m_brushActiveText;
private SolidBrush m_brushInactiveText;
private LinearGradientBrush m_brushActive;
private LinearGradientBrush m_brushInactive;
private StringFormat m_format = new StringFormat();
private LinearGradientMode mLinearGradientMode;
private IContainer components = null;
[CategoryAttribute("Appearance")]
[DescriptionAttribute("If should draw the text as antialiased.")]
[DefaultValueAttribute(true)]
public bool AntiAlias
{
get
{
return m_antiAlias;
}
set
{
m_antiAlias = value;
Invalidate();
}
}
[DefaultValueAttribute(typeof(Color), "Black")]
[DescriptionAttribute("Color of the text when active.")]
[CategoryAttribute("Appearance")]
public Color ActiveTextColor
{
get
{
return m_colorActiveText;
}
set
{
if (value == Color.Empty)
{
value = Color.Black;
}
m_colorActiveText = value;
m_brushActiveText = new SolidBrush(m_colorActiveText);
Invalidate();
}
}
[CategoryAttribute("Appearance")]
[DefaultValueAttribute(typeof(Color), "White")]
[DescriptionAttribute("Color of the text when inactive.")]
public Color InactiveTextColor
{
get
{
return m_colorInactiveText;
}
set
{
if (value == Color.Empty)
{
value = Color.White;
}
m_colorInactiveText = value;
m_brushInactiveText = new SolidBrush(m_colorInactiveText);
Invalidate();
}
}
[DescriptionAttribute("Linear Gradient Mode (direction of fade).")]
[CategoryAttribute("Appearance")]
[DefaultValueAttribute(LinearGradientMode.Horizontal)]
public LinearGradientMode LinearGradient
{
get
{
return mLinearGradientMode;
}
set
{
if (value != mLinearGradientMode)
{
mLinearGradientMode = value;
Invalidate();
}
}
}
[DescriptionAttribute("Low color of the active gradient.")]
[CategoryAttribute("Appearance")]
[DefaultValueAttribute(typeof(Color), "255, 165, 78")]
public Color ActiveGradientLowColor
{
get
{
return m_colorActiveLow;
}
set
{
if (value == Color.Empty)
{
value = Color.FromArgb(255, 165, 78);
}
m_colorActiveLow = value;
CreateGradientBrushes(mLinearGradientMode);
Invalidate();
}
}
[CategoryAttribute("Appearance")]
[DescriptionAttribute("High color of the active gradient.")]
[DefaultValueAttribute(typeof(Color), "255, 225, 155")]
public Color ActiveGradientHighColor
{
get
{
return m_colorActiveHigh;
}
set
{
if (value == Color.Empty)
{
value = Color.FromArgb(255, 225, 155);
}
m_colorActiveHigh = value;
CreateGradientBrushes(mLinearGradientMode);
Invalidate();
}
}
[DefaultValueAttribute(typeof(Color), "3, 55, 145")]
[DescriptionAttribute("Low color of the inactive gradient.")]
[CategoryAttribute("Appearance")]
public Color InactiveGradientLowColor
{
get
{
return m_colorInactiveLow;
}
set
{
if (value == Color.Empty)
{
value = Color.FromArgb(3, 55, 145);
}
m_colorInactiveLow = value;
CreateGradientBrushes(mLinearGradientMode);
Invalidate();
}
}
[CategoryAttribute("Appearance")]
[DescriptionAttribute("High color of the inactive gradient.")]
[DefaultValueAttribute(typeof(Color), "90, 135, 215")]
public Color InactiveGradientHighColor
{
get
{
return m_colorInactiveHigh;
}
set
{
if (value == Color.Empty)
{
value = Color.FromArgb(90, 135, 215);
}
m_colorInactiveHigh = value;
CreateGradientBrushes(mLinearGradientMode);
Invalidate();
}
}
// brush used to draw the caption
private SolidBrush TextBrush
{
get
{
if (m_active && m_allowActive)
return m_brushActiveText;
else
return m_brushInactiveText;
}
}
// gradient brush for the background
private LinearGradientBrush BackBrush
{
get
{
if (m_active && m_allowActive)
return m_brushActive;
else
return m_brushInactive;
}
}
public override string Text
{
get
{
return Caption;
}
set
{
Caption = value;
}
}
[DescriptionAttribute("Text displayed in the caption.")]
[DefaultValueAttribute("")]
[CategoryAttribute("Appearance")]
public string Caption
{
get
{
return m_text;
}
set
{
m_text = value;
Invalidate();
}
}
[DescriptionAttribute("The active state of the caption, draws the caption with different gradient colors.")]
[DefaultValueAttribute(false)]
[CategoryAttribute("Appearance")]
public bool Active
{
get
{
return m_active;
}
set
{
m_active = value;
Invalidate();
}
}
[DefaultValueAttribute(true)]
[CategoryAttribute("Appearance")]
[DescriptionAttribute("True always uses the inactive state colors, false maintains an active and inactive state.")]
public bool AllowActive
{
get
{
return m_allowActive;
}
set
{
m_allowActive = value;
Invalidate();
}
}
public PaneCaption()
{
InitializeComponent();
// set double buffer styles
SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer, true);
// init the height
Height = Consts.DefaultHeight;
// format used when drawing the text
m_format.FormatFlags = StringFormatFlags.NoWrap;
m_format.LineAlignment = StringAlignment.Center;
m_format.Trimming = StringTrimming.EllipsisCharacter;
// init the font
Font = new Font("Tahoma", 12.0F, FontStyle.Bold);
// create gdi objects
ActiveTextColor = m_colorActiveText;
InactiveTextColor = m_colorInactiveText;
// setting the height above actually does this, but leave
// in incase change the code (and forget to init the
// gradient brushes)
CreateGradientBrushes(mLinearGradientMode);
}
// the caption needs to be drawn
protected override void OnPaint(PaintEventArgs e)
{
DrawCaption(e.Graphics);
base.OnPaint(e);
}
// draw the caption
private void DrawCaption(Graphics g)
{
// background
g.FillRectangle(this.BackBrush, this.DisplayRectangle);
if (m_antiAlias)
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
// need a rectangle when want to use ellipsis
RectangleF bounds = new RectangleF(Consts.PosOffset,
0,
this.DisplayRectangle.Width - Consts.PosOffset,
this.DisplayRectangle.Height);
g.DrawString(m_text, this.Font, this.TextBrush, bounds, m_format);
}
// clicking on the caption does not give focus,
// handle the mouse down event and set focus to self
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (m_allowActive)
{
Focus();
}
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
// create the gradient brushes based on the new size
CreateGradientBrushes(mLinearGradientMode);
}
private void CreateGradientBrushes(LinearGradientMode lgm)
{
// can only create brushes when have a width and height
if (Width > 0 && Height > 0)
{
if (m_brushActive != null)
{
m_brushActive.Dispose();
}
m_brushActive = new LinearGradientBrush(DisplayRectangle, m_colorActiveHigh, m_colorActiveLow, lgm);
if (m_brushInactive != null)
{
m_brushInactive.Dispose();
}
m_brushInactive = new LinearGradientBrush(DisplayRectangle, m_colorInactiveHigh, m_colorInactiveLow, lgm);
}
}
protected override void Dispose(bool disposing)
{
if (disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
[DebuggerStepThroughAttribute()]
private void InitializeComponent()
{
this.Name = "PaneCaption";
this.Size = new Size(150, 30);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.DataFeeds.Enumerators;
using QuantConnect.Lean.Engine.DataFeeds.Enumerators.Factories;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
using QuantConnect.Util;
namespace QuantConnect.Tests.Engine.DataFeeds.Enumerators.Factories
{
[TestFixture]
public class OptionChainUniverseSubscriptionEnumeratorFactoryTests
{
[Test]
public void DoesNotEmitInvalidData()
{
var startTime = new DateTime(2014, 06, 06, 0, 0, 0);
var endTime = new DateTime(2014, 06, 09, 20, 0, 0);
var canonicalSymbol = Symbol.Create("AAPL", SecurityType.Option, Market.USA, "?AAPL");
var quoteCurrency = new Cash(Currencies.USD, 0, 1);
var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, canonicalSymbol, SecurityType.Option);
var config = new SubscriptionDataConfig(
typeof(ZipEntryName),
canonicalSymbol,
Resolution.Minute,
TimeZones.Utc,
TimeZones.NewYork,
true,
false,
false,
false,
TickType.Quote,
false,
DataNormalizationMode.Raw
);
var option = new Option(
canonicalSymbol,
exchangeHours,
quoteCurrency,
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache(),
null
);
var dataProvider = TestGlobals.DataProvider;
using var cache = new ZipDataCacheProvider(dataProvider);
var enumeratorFactory = new BaseDataSubscriptionEnumeratorFactory(false, TestGlobals.MapFileProvider, cache);
var fillForwardResolution = Ref.CreateReadOnly(() => Resolution.Minute.ToTimeSpan());
Func<SubscriptionRequest, IEnumerator<BaseData>> underlyingEnumeratorFunc = (req) =>
{
var input = enumeratorFactory.CreateEnumerator(req, dataProvider);
input = new BaseDataCollectionAggregatorEnumerator(input, req.Configuration.Symbol);
return new FillForwardEnumerator(
input,
option.Exchange,
fillForwardResolution,
false,
endTime,
Resolution.Minute.ToTimeSpan(),
TimeZones.Utc);
};
var factory = new OptionChainUniverseSubscriptionEnumeratorFactory(underlyingEnumeratorFunc);
var request = new SubscriptionRequest(true, null, option, config, startTime, endTime);
var enumerator = factory.CreateEnumerator(request, dataProvider);
var emittedCount = 0;
foreach (var data in enumerator.AsEnumerable())
{
emittedCount++;
var optionData = data as OptionChainUniverseDataCollection;
Assert.IsNotNull(optionData);
Assert.IsNotNull(optionData.Underlying);
Assert.AreNotEqual(0, optionData.Data.Count);
}
// 9:30 to 15:59 -> 6.5 hours * 60 => 390 minutes * 2 days = 780
Assert.AreEqual(780, emittedCount);
}
[Test]
public void RefreshesOptionChainUniverseOnDateChange()
{
var startTime = new DateTime(2018, 10, 19, 10, 0, 0);
var timeProvider = new ManualTimeProvider(startTime);
var canonicalSymbol = Symbol.Create("SPY", SecurityType.Option, Market.USA, "?SPY");
var quoteCurrency = new Cash(Currencies.USD, 0, 1);
var exchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, canonicalSymbol, SecurityType.Option);
var config = new SubscriptionDataConfig(
typeof(ZipEntryName),
canonicalSymbol,
Resolution.Minute,
TimeZones.Utc,
TimeZones.NewYork,
true,
false,
false,
false,
TickType.Quote,
false,
DataNormalizationMode.Raw
);
var option = new Option(
canonicalSymbol,
exchangeHours,
quoteCurrency,
new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache(),
null
);
var fillForwardResolution = Ref.CreateReadOnly(() => Resolution.Minute.ToTimeSpan());
var symbolUniverse = new TestDataQueueUniverseProvider(timeProvider);
EnqueueableEnumerator<BaseData> underlyingEnumerator = null;
Func<SubscriptionRequest, IEnumerator<BaseData>> underlyingEnumeratorFunc =
(req) =>
{
underlyingEnumerator = new EnqueueableEnumerator<BaseData>();
return new LiveFillForwardEnumerator(
timeProvider,
underlyingEnumerator,
option.Exchange,
fillForwardResolution,
false,
Time.EndOfTime,
Resolution.Minute.ToTimeSpan(),
TimeZones.Utc);
};
var factory = new OptionChainUniverseSubscriptionEnumeratorFactory(underlyingEnumeratorFunc, symbolUniverse, timeProvider);
var universeSettings = new UniverseSettings(Resolution.Minute, 0, true, false, TimeSpan.Zero);
var universe = new OptionChainUniverse(option, universeSettings, true);
var request = new SubscriptionRequest(true, universe, option, config, startTime, Time.EndOfTime);
var enumerator = (DataQueueOptionChainUniverseDataCollectionEnumerator) factory.CreateEnumerator(request, TestGlobals.DataProvider);
// 2018-10-19 10:00 AM UTC
underlyingEnumerator.Enqueue(new Tick { Symbol = Symbols.SPY, Value = 280m });
// 2018-10-19 10:01 AM UTC
timeProvider.Advance(Time.OneMinute);
underlyingEnumerator.Enqueue(new Tick { Symbol = Symbols.SPY, Value = 280m });
Assert.IsTrue(enumerator.MoveNext());
Assert.IsNotNull(enumerator.Current);
Assert.AreEqual(1, symbolUniverse.TotalLookupCalls);
var data = enumerator.Current;
Assert.IsNotNull(data);
Assert.AreEqual(1, data.Data.Count);
Assert.IsNotNull(data.Underlying);
// 2018-10-19 10:02 AM UTC
timeProvider.Advance(Time.OneMinute);
underlyingEnumerator.Enqueue(new Tick { Symbol = Symbols.SPY, Value = 280m });
Assert.IsTrue(enumerator.MoveNext());
Assert.IsNotNull(enumerator.Current);
Assert.AreEqual(1, symbolUniverse.TotalLookupCalls);
data = enumerator.Current;
Assert.IsNotNull(data);
Assert.AreEqual(1, data.Data.Count);
Assert.IsNotNull(data.Underlying);
// 2018-10-19 10:03 AM UTC
timeProvider.Advance(Time.OneMinute);
underlyingEnumerator.Enqueue(new Tick { Symbol = Symbols.SPY, Value = 280m });
Assert.IsTrue(enumerator.MoveNext());
Assert.IsNotNull(enumerator.Current);
Assert.AreEqual(1, symbolUniverse.TotalLookupCalls);
data = enumerator.Current;
Assert.IsNotNull(data);
Assert.AreEqual(1, data.Data.Count);
Assert.IsNotNull(data.Underlying);
// 2018-10-20 10:03 AM UTC
timeProvider.Advance(Time.OneDay);
underlyingEnumerator.Enqueue(new Tick { Symbol = Symbols.SPY, Value = 280m });
Assert.IsTrue(enumerator.MoveNext());
Assert.IsNotNull(enumerator.Current);
Assert.AreEqual(2, symbolUniverse.TotalLookupCalls);
data = enumerator.Current;
Assert.IsNotNull(data);
Assert.AreEqual(2, data.Data.Count);
Assert.IsNotNull(data.Underlying);
// 2018-10-20 10:04 AM UTC
timeProvider.Advance(Time.OneMinute);
underlyingEnumerator.Enqueue(new Tick { Symbol = Symbols.SPY, Value = 280m });
Assert.IsTrue(enumerator.MoveNext());
Assert.IsNotNull(enumerator.Current);
Assert.AreEqual(2, symbolUniverse.TotalLookupCalls);
data = enumerator.Current;
Assert.IsNotNull(data);
Assert.AreEqual(2, data.Data.Count);
Assert.IsNotNull(data.Underlying);
enumerator.Dispose();
}
public class TestDataQueueUniverseProvider : IDataQueueUniverseProvider
{
private readonly Symbol[] _symbolList1 =
{
Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 280m, new DateTime(2018, 10, 19))
};
private readonly Symbol[] _symbolList2 =
{
Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 280m, new DateTime(2018, 10, 19)),
Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Put, 280m, new DateTime(2018, 10, 19))
};
private readonly ITimeProvider _timeProvider;
public int TotalLookupCalls { get; set; }
public TestDataQueueUniverseProvider(ITimeProvider timeProvider)
{
_timeProvider = timeProvider;
}
public IEnumerable<Symbol> LookupSymbols(Symbol symbol, bool includeExpired, string securityCurrency = null)
{
TotalLookupCalls++;
return _timeProvider.GetUtcNow().Date.Day >= 20 ? _symbolList2 : _symbolList1;
}
public bool CanPerformSelection()
{
return true;
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Data.Custom;
using QuantConnect.Data.Custom.Tiingo;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds.Enumerators;
using QuantConnect.Lean.Engine.DataFeeds.Enumerators.Factories;
using QuantConnect.Lean.Engine.Results;
using QuantConnect.Logging;
using QuantConnect.Packets;
using QuantConnect.Securities;
using QuantConnect.Util;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// Provides an implementation of <see cref="IDataFeed"/> that is designed to deal with
/// live, remote data sources
/// </summary>
public class LiveTradingDataFeed : IDataFeed
{
private LiveNodePacket _job;
// used to get current time
private ITimeProvider _timeProvider;
private ITimeProvider _frontierTimeProvider;
private IDataProvider _dataProvider;
private IMapFileProvider _mapFileProvider;
private IDataQueueHandler _dataQueueHandler;
private BaseDataExchange _customExchange;
private SubscriptionCollection _subscriptions;
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private IDataChannelProvider _channelProvider;
/// <summary>
/// Public flag indicator that the thread is still busy.
/// </summary>
public bool IsActive
{
get; private set;
}
/// <summary>
/// Initializes the data feed for the specified job and algorithm
/// </summary>
public void Initialize(IAlgorithm algorithm,
AlgorithmNodePacket job,
IResultHandler resultHandler,
IMapFileProvider mapFileProvider,
IFactorFileProvider factorFileProvider,
IDataProvider dataProvider,
IDataFeedSubscriptionManager subscriptionManager,
IDataFeedTimeProvider dataFeedTimeProvider,
IDataChannelProvider dataChannelProvider)
{
if (!(job is LiveNodePacket))
{
throw new ArgumentException("The LiveTradingDataFeed requires a LiveNodePacket.");
}
_cancellationTokenSource = new CancellationTokenSource();
_job = (LiveNodePacket) job;
_timeProvider = dataFeedTimeProvider.TimeProvider;
_dataProvider = dataProvider;
_mapFileProvider = mapFileProvider;
_channelProvider = dataChannelProvider;
_frontierTimeProvider = dataFeedTimeProvider.FrontierTimeProvider;
_customExchange = new BaseDataExchange("CustomDataExchange") {SleepInterval = 10};
_subscriptions = subscriptionManager.DataFeedSubscriptions;
_dataQueueHandler = GetDataQueueHandler();
_dataQueueHandler?.SetJob(_job);
// run the custom data exchange
var manualEvent = new ManualResetEventSlim(false);
Task.Factory.StartNew(() =>
{
manualEvent.Set();
_customExchange.Start(_cancellationTokenSource.Token);
}, TaskCreationOptions.LongRunning);
manualEvent.Wait();
manualEvent.DisposeSafely();
IsActive = true;
}
/// <summary>
/// Creates a new subscription to provide data for the specified security.
/// </summary>
/// <param name="request">Defines the subscription to be added, including start/end times the universe and security</param>
/// <returns>The created <see cref="Subscription"/> if successful, null otherwise</returns>
public Subscription CreateSubscription(SubscriptionRequest request)
{
// create and add the subscription to our collection
var subscription = request.IsUniverseSubscription
? CreateUniverseSubscription(request)
: CreateDataSubscription(request);
return subscription;
}
/// <summary>
/// Removes the subscription from the data feed, if it exists
/// </summary>
/// <param name="subscription">The subscription to remove</param>
public void RemoveSubscription(Subscription subscription)
{
var symbol = subscription.Configuration.Symbol;
// remove the subscriptions
if (!_channelProvider.ShouldStreamSubscription(subscription.Configuration))
{
_customExchange.RemoveEnumerator(symbol);
_customExchange.RemoveDataHandler(symbol);
}
else
{
_dataQueueHandler.Unsubscribe(subscription.Configuration);
if (subscription.Configuration.SecurityType == SecurityType.Equity && !subscription.Configuration.IsInternalFeed)
{
_dataQueueHandler.Unsubscribe(new SubscriptionDataConfig(subscription.Configuration, typeof(Dividend)));
_dataQueueHandler.Unsubscribe(new SubscriptionDataConfig(subscription.Configuration, typeof(Split)));
}
}
}
/// <summary>
/// External controller calls to signal a terminate of the thread.
/// </summary>
public virtual void Exit()
{
if (IsActive)
{
IsActive = false;
Log.Trace("LiveTradingDataFeed.Exit(): Start. Setting cancellation token...");
_cancellationTokenSource.Cancel();
_customExchange?.Stop();
Log.Trace("LiveTradingDataFeed.Exit(): Exit Finished.");
}
}
/// <summary>
/// Gets the <see cref="IDataQueueHandler"/> to use. By default this will try to load
/// the type specified in the configuration via the 'data-queue-handler'
/// </summary>
/// <returns>The loaded <see cref="IDataQueueHandler"/></returns>
protected virtual IDataQueueHandler GetDataQueueHandler()
{
Log.Trace($"LiveTradingDataFeed.GetDataQueueHandler(): will use {_job.DataQueueHandler}");
return Composer.Instance.GetExportedValueByTypeName<IDataQueueHandler>(_job.DataQueueHandler);
}
/// <summary>
/// Creates a new subscription for the specified security
/// </summary>
/// <param name="request">The subscription request</param>
/// <returns>A new subscription instance of the specified security</returns>
protected Subscription CreateDataSubscription(SubscriptionRequest request)
{
Subscription subscription = null;
try
{
var localEndTime = request.EndTimeUtc.ConvertFromUtc(request.Security.Exchange.TimeZone);
var timeZoneOffsetProvider = new TimeZoneOffsetProvider(request.Security.Exchange.TimeZone, request.StartTimeUtc, request.EndTimeUtc);
IEnumerator<BaseData> enumerator;
if (!_channelProvider.ShouldStreamSubscription(request.Configuration))
{
if (!Quandl.IsAuthCodeSet)
{
// we're not using the SubscriptionDataReader, so be sure to set the auth token here
Quandl.SetAuthCode(Config.Get("quandl-auth-token"));
}
if (!Tiingo.IsAuthCodeSet)
{
// we're not using the SubscriptionDataReader, so be sure to set the auth token here
Tiingo.SetAuthCode(Config.Get("tiingo-auth-token"));
}
var factory = new LiveCustomDataSubscriptionEnumeratorFactory(_timeProvider);
var enumeratorStack = factory.CreateEnumerator(request, _dataProvider);
_customExchange.AddEnumerator(request.Configuration.Symbol, enumeratorStack);
var enqueable = new EnqueueableEnumerator<BaseData>();
_customExchange.SetDataHandler(request.Configuration.Symbol, data =>
{
enqueable.Enqueue(data);
subscription.OnNewDataAvailable();
});
enumerator = enqueable;
}
else
{
EventHandler handler = (sender, args) => subscription?.OnNewDataAvailable();
enumerator = _dataQueueHandler.Subscribe(request.Configuration, handler);
var securityType = request.Configuration.SecurityType;
var auxEnumerators = new List<IEnumerator<BaseData>>();
if (securityType == SecurityType.Equity)
{
auxEnumerators.Add(_dataQueueHandler.Subscribe(new SubscriptionDataConfig(request.Configuration, typeof(Dividend)), handler));
auxEnumerators.Add(_dataQueueHandler.Subscribe(new SubscriptionDataConfig(request.Configuration, typeof(Split)), handler));
}
IEnumerator<BaseData> delistingEnumerator;
if (LiveDelistingEventProviderEnumerator.TryCreate(request.Configuration, _timeProvider, _dataQueueHandler, request.Security.Cache, _mapFileProvider, out delistingEnumerator))
{
auxEnumerators.Add(delistingEnumerator);
}
if (auxEnumerators.Count > 0)
{
enumerator = new LiveAuxiliaryDataSynchronizingEnumerator(_timeProvider, request.Configuration.ExchangeTimeZone, enumerator, auxEnumerators.ToArray());
}
}
if (request.Configuration.FillDataForward)
{
var fillForwardResolution = _subscriptions.UpdateAndGetFillForwardResolution(request.Configuration);
enumerator = new LiveFillForwardEnumerator(_frontierTimeProvider, enumerator, request.Security.Exchange, fillForwardResolution, request.Configuration.ExtendedMarketHours, localEndTime, request.Configuration.Increment, request.Configuration.DataTimeZone);
}
// define market hours and user filters to incoming data
if (request.Configuration.IsFilteredSubscription)
{
enumerator = new SubscriptionFilterEnumerator(enumerator, request.Security, localEndTime, request.Configuration.ExtendedMarketHours, true, request.ExchangeHours);
}
// finally, make our subscriptions aware of the frontier of the data feed, prevents future data from spewing into the feed
enumerator = new FrontierAwareEnumerator(enumerator, _frontierTimeProvider, timeZoneOffsetProvider);
var subscriptionDataEnumerator = new SubscriptionDataEnumerator(request.Configuration, request.Security.Exchange.Hours, timeZoneOffsetProvider, enumerator);
subscription = new Subscription(request, subscriptionDataEnumerator, timeZoneOffsetProvider);
}
catch (Exception err)
{
Log.Error(err);
}
return subscription;
}
/// <summary>
/// Creates a new subscription for universe selection
/// </summary>
/// <param name="request">The subscription request</param>
private Subscription CreateUniverseSubscription(SubscriptionRequest request)
{
Subscription subscription = null;
// TODO : Consider moving the creating of universe subscriptions to a separate, testable class
// grab the relevant exchange hours
var config = request.Universe.Configuration;
var localEndTime = request.EndTimeUtc.ConvertFromUtc(request.Security.Exchange.TimeZone);
var tzOffsetProvider = new TimeZoneOffsetProvider(request.Security.Exchange.TimeZone, request.StartTimeUtc, request.EndTimeUtc);
IEnumerator<BaseData> enumerator = null;
var timeTriggered = request.Universe as ITimeTriggeredUniverse;
if (timeTriggered != null)
{
Log.Trace($"LiveTradingDataFeed.CreateUniverseSubscription(): Creating user defined universe: {config.Symbol.ID}");
// spoof a tick on the requested interval to trigger the universe selection function
var enumeratorFactory = new TimeTriggeredUniverseSubscriptionEnumeratorFactory(timeTriggered, MarketHoursDatabase.FromDataFolder(), _frontierTimeProvider);
enumerator = enumeratorFactory.CreateEnumerator(request, _dataProvider);
enumerator = new FrontierAwareEnumerator(enumerator, _timeProvider, tzOffsetProvider);
var enqueueable = new EnqueueableEnumerator<BaseData>();
_customExchange.AddEnumerator(new EnumeratorHandler(config.Symbol, enumerator, enqueueable));
enumerator = enqueueable;
}
else if (config.Type == typeof (CoarseFundamental))
{
Log.Trace($"LiveTradingDataFeed.CreateUniverseSubscription(): Creating coarse universe: {config.Symbol.ID}");
// we subscribe using a normalized symbol, without a random GUID,
// since the ticker plant will send the coarse data using this symbol
var normalizedSymbol = CoarseFundamental.CreateUniverseSymbol(config.Symbol.ID.Market, false);
// Will try to pull coarse data from the data folder every 10min, file with today's date.
// If lean is started today it will trigger initial coarse universe selection
var factory = new LiveCustomDataSubscriptionEnumeratorFactory(_timeProvider,
// we adjust time to the previous tradable date
time => Time.GetStartTimeForTradeBars(request.Security.Exchange.Hours, time, Time.OneDay, 1, false, config.DataTimeZone),
TimeSpan.FromMinutes(10)
);
var enumeratorStack = factory.CreateEnumerator(request, _dataProvider);
// aggregates each coarse data point into a single BaseDataCollection
var aggregator = new BaseDataCollectionAggregatorEnumerator(enumeratorStack, normalizedSymbol, true);
_customExchange.AddEnumerator(normalizedSymbol, aggregator);
var enqueable = new EnqueueableEnumerator<BaseData>();
_customExchange.SetDataHandler(normalizedSymbol, data =>
{
var coarseData = data as BaseDataCollection;
enqueable.Enqueue(new BaseDataCollection(coarseData.Time, config.Symbol, coarseData.Data));
subscription.OnNewDataAvailable();
});
enumerator = GetConfiguredFrontierAwareEnumerator(enqueable, tzOffsetProvider,
// advance time if before 23pm or after 5am and not on Saturdays
time => time.Hour < 23 && time.Hour > 5 && time.DayOfWeek != DayOfWeek.Saturday);
}
else if (request.Universe is OptionChainUniverse)
{
Log.Trace("LiveTradingDataFeed.CreateUniverseSubscription(): Creating option chain universe: " + config.Symbol.ID);
Func<SubscriptionRequest, IEnumerator<BaseData>> configure = (subRequest) =>
{
var fillForwardResolution = _subscriptions.UpdateAndGetFillForwardResolution(subRequest.Configuration);
var input = _dataQueueHandler.Subscribe(subRequest.Configuration, (sender, args) => subscription.OnNewDataAvailable());
return new LiveFillForwardEnumerator(_frontierTimeProvider, input, subRequest.Security.Exchange, fillForwardResolution, subRequest.Configuration.ExtendedMarketHours, localEndTime, subRequest.Configuration.Increment, subRequest.Configuration.DataTimeZone);
};
var symbolUniverse = _dataQueueHandler as IDataQueueUniverseProvider;
if (symbolUniverse == null)
{
throw new NotSupportedException("The DataQueueHandler does not support Options.");
}
var enumeratorFactory = new OptionChainUniverseSubscriptionEnumeratorFactory(configure, symbolUniverse, _timeProvider);
enumerator = enumeratorFactory.CreateEnumerator(request, _dataProvider);
enumerator = new FrontierAwareEnumerator(enumerator, _frontierTimeProvider, tzOffsetProvider);
}
else if (request.Universe is FuturesChainUniverse)
{
Log.Trace("LiveTradingDataFeed.CreateUniverseSubscription(): Creating futures chain universe: " + config.Symbol.ID);
var symbolUniverse = _dataQueueHandler as IDataQueueUniverseProvider;
if (symbolUniverse == null)
{
throw new NotSupportedException("The DataQueueHandler does not support Futures.");
}
var enumeratorFactory = new FuturesChainUniverseSubscriptionEnumeratorFactory(symbolUniverse, _timeProvider);
enumerator = enumeratorFactory.CreateEnumerator(request, _dataProvider);
enumerator = new FrontierAwareEnumerator(enumerator, _frontierTimeProvider, tzOffsetProvider);
}
else
{
Log.Trace("LiveTradingDataFeed.CreateUniverseSubscription(): Creating custom universe: " + config.Symbol.ID);
var factory = new LiveCustomDataSubscriptionEnumeratorFactory(_timeProvider);
var enumeratorStack = factory.CreateEnumerator(request, _dataProvider);
enumerator = new BaseDataCollectionAggregatorEnumerator(enumeratorStack, config.Symbol, liveMode:true);
var enqueueable = new EnqueueableEnumerator<BaseData>();
_customExchange.AddEnumerator(new EnumeratorHandler(config.Symbol, enumerator, enqueueable));
enumerator = enqueueable;
}
// create the subscription
var subscriptionDataEnumerator = new SubscriptionDataEnumerator(request.Configuration, request.Security.Exchange.Hours, tzOffsetProvider, enumerator);
subscription = new Subscription(request, subscriptionDataEnumerator, tzOffsetProvider);
// send the subscription for the new symbol through to the data queuehandler
if (_channelProvider.ShouldStreamSubscription(subscription.Configuration))
{
_dataQueueHandler.Subscribe(request.Configuration, (sender, args) => subscription.OnNewDataAvailable());
}
return subscription;
}
/// <summary>
/// Will wrap the provided enumerator with a <see cref="FrontierAwareEnumerator"/>
/// using a <see cref="PredicateTimeProvider"/> that will advance time based on the provided
/// function
/// </summary>
/// <remarks>Won't advance time if now.Hour is bigger or equal than 23pm, less or equal than 5am or Saturday.
/// This is done to prevent universe selection occurring in those hours so that the subscription changes
/// are handled correctly.</remarks>
private IEnumerator<BaseData> GetConfiguredFrontierAwareEnumerator(
IEnumerator<BaseData> enumerator,
TimeZoneOffsetProvider tzOffsetProvider,
Func<DateTime, bool> customStepEvaluator)
{
var stepTimeProvider = new PredicateTimeProvider(_frontierTimeProvider, customStepEvaluator);
return new FrontierAwareEnumerator(enumerator, stepTimeProvider, tzOffsetProvider);
}
/// <summary>
/// Overrides methods of the base data exchange implementation
/// </summary>
class EnumeratorHandler : BaseDataExchange.EnumeratorHandler
{
private readonly EnqueueableEnumerator<BaseData> _enqueueable;
public EnumeratorHandler(Symbol symbol, IEnumerator<BaseData> enumerator, EnqueueableEnumerator<BaseData> enqueueable)
: base(symbol, enumerator, true)
{
_enqueueable = enqueueable;
}
/// <summary>
/// Returns true if this enumerator should move next
/// </summary>
public override bool ShouldMoveNext() { return true; }
/// <summary>
/// Calls stop on the internal enqueueable enumerator
/// </summary>
public override void OnEnumeratorFinished() { _enqueueable.Stop(); }
/// <summary>
/// Enqueues the data
/// </summary>
/// <param name="data">The data to be handled</param>
public override void HandleData(BaseData data)
{
_enqueueable.Enqueue(data);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Avalonia.Automation.Peers;
using Avalonia.Controls;
using Avalonia.Controls.Platform.Surfaces;
using Avalonia.Controls.Primitives.PopupPositioning;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Threading;
using Avalonia.Utilities;
namespace Avalonia.Headless
{
class HeadlessWindowImpl : IWindowImpl, IPopupImpl, IFramebufferPlatformSurface, IHeadlessWindow
{
private IKeyboardDevice _keyboard;
private Stopwatch _st = Stopwatch.StartNew();
private Pointer _mousePointer;
private WriteableBitmap _lastRenderedFrame;
private object _sync = new object();
public bool IsPopup { get; }
public HeadlessWindowImpl(bool isPopup)
{
IsPopup = isPopup;
Surfaces = new object[] { this };
_keyboard = AvaloniaLocator.Current.GetService<IKeyboardDevice>();
_mousePointer = new Pointer(Pointer.GetNextFreeId(), PointerType.Mouse, true);
MouseDevice = new MouseDevice(_mousePointer);
ClientSize = new Size(1024, 768);
}
public void Dispose()
{
Closed?.Invoke();
_lastRenderedFrame?.Dispose();
_lastRenderedFrame = null;
}
public Size ClientSize { get; set; }
public Size? FrameSize => null;
public double RenderScaling { get; } = 1;
public double DesktopScaling => RenderScaling;
public IEnumerable<object> Surfaces { get; }
public Action<RawInputEventArgs> Input { get; set; }
public Action<Rect> Paint { get; set; }
public Action<Size, PlatformResizeReason> Resized { get; set; }
public Action<double> ScalingChanged { get; set; }
public IRenderer CreateRenderer(IRenderRoot root)
=> new DeferredRenderer(root, AvaloniaLocator.Current.GetService<IRenderLoop>());
public void Invalidate(Rect rect)
{
}
public void SetInputRoot(IInputRoot inputRoot)
{
InputRoot = inputRoot;
}
public IInputRoot InputRoot { get; set; }
public Point PointToClient(PixelPoint point) => point.ToPoint(RenderScaling);
public PixelPoint PointToScreen(Point point) => PixelPoint.FromPoint(point, RenderScaling);
public void SetCursor(ICursorImpl cursor)
{
}
public Action Closed { get; set; }
public IMouseDevice MouseDevice { get; }
public void Show(bool activate, bool isDialog)
{
if (activate)
Dispatcher.UIThread.Post(() => Activated?.Invoke(), DispatcherPriority.Input);
}
public void Hide()
{
Dispatcher.UIThread.Post(() => Deactivated?.Invoke(), DispatcherPriority.Input);
}
public void BeginMoveDrag()
{
}
public void BeginResizeDrag(WindowEdge edge)
{
}
public PixelPoint Position { get; set; }
public Action<PixelPoint> PositionChanged { get; set; }
public void Activate()
{
Dispatcher.UIThread.Post(() => Activated?.Invoke(), DispatcherPriority.Input);
}
public Action Deactivated { get; set; }
public Action Activated { get; set; }
public IPlatformHandle Handle { get; } = new PlatformHandle(IntPtr.Zero, "STUB");
public Size MaxClientSize { get; } = new Size(1920, 1280);
public void Resize(Size clientSize, PlatformResizeReason reason)
{
// Emulate X11 behavior here
if (IsPopup)
DoResize(clientSize);
else
Dispatcher.UIThread.Post(() =>
{
DoResize(clientSize);
});
}
void DoResize(Size clientSize)
{
// Uncomment this check and experience a weird bug in layout engine
if (ClientSize != clientSize)
{
ClientSize = clientSize;
Resized?.Invoke(clientSize, PlatformResizeReason.Unspecified);
}
}
public void SetMinMaxSize(Size minSize, Size maxSize)
{
}
public void SetTopmost(bool value)
{
}
public IScreenImpl Screen { get; } = new HeadlessScreensStub();
public WindowState WindowState { get; set; }
public Action<WindowState> WindowStateChanged { get; set; }
public void SetTitle(string title)
{
}
public void SetSystemDecorations(bool enabled)
{
}
public void SetIcon(IWindowIconImpl icon)
{
}
public void ShowTaskbarIcon(bool value)
{
}
public void CanResize(bool value)
{
}
public Func<bool> Closing { get; set; }
class FramebufferProxy : ILockedFramebuffer
{
private readonly ILockedFramebuffer _fb;
private readonly Action _onDispose;
private bool _disposed;
public FramebufferProxy(ILockedFramebuffer fb, Action onDispose)
{
_fb = fb;
_onDispose = onDispose;
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
_fb.Dispose();
_onDispose();
}
public IntPtr Address => _fb.Address;
public PixelSize Size => _fb.Size;
public int RowBytes => _fb.RowBytes;
public Vector Dpi => _fb.Dpi;
public PixelFormat Format => _fb.Format;
}
public ILockedFramebuffer Lock()
{
var bmp = new WriteableBitmap(PixelSize.FromSize(ClientSize, RenderScaling), new Vector(96, 96) * RenderScaling, PixelFormat.Rgba8888, AlphaFormat.Premul);
var fb = bmp.Lock();
return new FramebufferProxy(fb, () =>
{
lock (_sync)
{
_lastRenderedFrame?.Dispose();
_lastRenderedFrame = bmp;
}
});
}
public IRef<IWriteableBitmapImpl> GetLastRenderedFrame()
{
lock (_sync)
return _lastRenderedFrame?.PlatformImpl?.CloneAs<IWriteableBitmapImpl>();
}
private ulong Timestamp => (ulong)_st.ElapsedMilliseconds;
// TODO: Hook recent Popup changes.
IPopupPositioner IPopupImpl.PopupPositioner => null;
public Size MaxAutoSizeHint => new Size(1920, 1080);
public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; }
public WindowTransparencyLevel TransparencyLevel => WindowTransparencyLevel.None;
public Action GotInputWhenDisabled { get; set; }
public bool IsClientAreaExtendedToDecorations => false;
public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; }
public bool NeedsManagedDecorations => false;
public Thickness ExtendedMargins => new Thickness();
public Thickness OffScreenMargin => new Thickness();
public Action LostFocus { get; set; }
public AcrylicPlatformCompensationLevels AcrylicCompensationLevels => new AcrylicPlatformCompensationLevels(1, 1, 1);
void IHeadlessWindow.KeyPress(Key key, RawInputModifiers modifiers)
{
Input?.Invoke(new RawKeyEventArgs(_keyboard, Timestamp, InputRoot, RawKeyEventType.KeyDown, key, modifiers));
}
void IHeadlessWindow.KeyRelease(Key key, RawInputModifiers modifiers)
{
Input?.Invoke(new RawKeyEventArgs(_keyboard, Timestamp, InputRoot, RawKeyEventType.KeyUp, key, modifiers));
}
void IHeadlessWindow.MouseDown(Point point, int button, RawInputModifiers modifiers)
{
Input?.Invoke(new RawPointerEventArgs(MouseDevice, Timestamp, InputRoot,
button == 0 ? RawPointerEventType.LeftButtonDown :
button == 1 ? RawPointerEventType.MiddleButtonDown : RawPointerEventType.RightButtonDown,
point, modifiers));
}
void IHeadlessWindow.MouseMove(Point point, RawInputModifiers modifiers)
{
Input?.Invoke(new RawPointerEventArgs(MouseDevice, Timestamp, InputRoot,
RawPointerEventType.Move, point, modifiers));
}
void IHeadlessWindow.MouseUp(Point point, int button, RawInputModifiers modifiers)
{
Input?.Invoke(new RawPointerEventArgs(MouseDevice, Timestamp, InputRoot,
button == 0 ? RawPointerEventType.LeftButtonUp :
button == 1 ? RawPointerEventType.MiddleButtonUp : RawPointerEventType.RightButtonUp,
point, modifiers));
}
void IWindowImpl.Move(PixelPoint point)
{
}
public IPopupImpl CreatePopup()
{
// TODO: Hook recent Popup changes.
return null;
}
public void SetWindowManagerAddShadowHint(bool enabled)
{
}
public void SetTransparencyLevelHint(WindowTransparencyLevel transparencyLevel)
{
}
public void SetParent(IWindowImpl parent)
{
}
public void SetEnabled(bool enable)
{
}
public void SetSystemDecorations(SystemDecorations enabled)
{
}
public void BeginMoveDrag(PointerPressedEventArgs e)
{
}
public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e)
{
}
public void SetExtendClientAreaToDecorationsHint(bool extendIntoClientAreaHint)
{
}
public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints)
{
}
public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight)
{
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.TypeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseExplicitType
{
public partial class UseExplicitTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) =>
new Tuple<DiagnosticAnalyzer, CodeFixProvider>(
new CSharpUseExplicitTypeDiagnosticAnalyzer(), new UseExplicitTypeCodeFixProvider());
private readonly CodeStyleOption<bool> onWithNone = new CodeStyleOption<bool>(true, NotificationOption.None);
private readonly CodeStyleOption<bool> offWithNone = new CodeStyleOption<bool>(false, NotificationOption.None);
private readonly CodeStyleOption<bool> onWithInfo = new CodeStyleOption<bool>(true, NotificationOption.Suggestion);
private readonly CodeStyleOption<bool> offWithInfo = new CodeStyleOption<bool>(false, NotificationOption.Suggestion);
private readonly CodeStyleOption<bool> onWithWarning = new CodeStyleOption<bool>(true, NotificationOption.Warning);
private readonly CodeStyleOption<bool> offWithWarning = new CodeStyleOption<bool>(false, NotificationOption.Warning);
private readonly CodeStyleOption<bool> onWithError = new CodeStyleOption<bool>(true, NotificationOption.Error);
private readonly CodeStyleOption<bool> offWithError = new CodeStyleOption<bool>(false, NotificationOption.Error);
// specify all options explicitly to override defaults.
private IDictionary<OptionKey, object> ExplicitTypeEverywhere() =>
Options(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithInfo)
.With(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, offWithInfo)
.With(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo);
private IDictionary<OptionKey, object> ExplicitTypeExceptWhereApparent() =>
Options(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithInfo)
.With(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, onWithInfo)
.With(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo);
private IDictionary<OptionKey, object> ExplicitTypeForBuiltInTypesOnly() =>
Options(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, onWithInfo)
.With(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, onWithInfo)
.With(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo);
private IDictionary<OptionKey, object> ExplicitTypeEnforcements() =>
Options(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithWarning)
.With(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, offWithError)
.With(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithInfo);
private IDictionary<OptionKey, object> ExplicitTypeNoneEnforcement() =>
Options(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, offWithNone)
.With(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, offWithNone)
.With(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, offWithNone);
private IDictionary<OptionKey, object> Options(OptionKey option, object value)
{
var options = new Dictionary<OptionKey, object>();
options.Add(option, value);
return options;
}
#region Error Cases
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldDeclaration()
{
await TestMissingAsync(
@"using System;
class Program
{
[|var|] _myfield = 5;
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnFieldLikeEvents()
{
await TestMissingAsync(
@"using System;
class Program
{
public event [|var|] _myevent;
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnAnonymousMethodExpression()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] comparer = delegate (string value) {
return value != ""0"";
};
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnLambdaExpression()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = y => y * y;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithMultipleDeclarators()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = 5, y = x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDeclarationWithoutInitializer()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotDuringConflicts()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] p = new var();
}
class var
{
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotIfAlreadyExplicitlyTyped()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|Program|] p = new Program();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnRHS()
{
await TestMissingAsync(
@"using System;
class C
{
void M()
{
var c = new [|var|]();
}
}
class var
{
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnErrorSymbol()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new Foo();
}
}", options: ExplicitTypeEverywhere());
}
#endregion
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnDynamic()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|dynamic|] x = 1;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnForEachVarWithAnonymousType()
{
await TestMissingAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5).Select(i => new { Value = i });
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task OnForEachVarWithExplicitType()
{
await TestAsync(
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach ([|var|] value in values)
{
Console.WriteLine(value.Value);
}
}
}",
@"using System;
using System.Linq;
class Program
{
void Method()
{
var values = Enumerable.Range(1, 5);
foreach (int value in values)
{
Console.WriteLine(value.Value);
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnAnonymousType()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new { Amount = 108, Message = ""Hello"" };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnArrayOfAnonymousType()
{
await TestMissingAsync(
@"using System;
class Program
{
void Method()
{
[|var|] x = new[] { new { name = ""apple"", diam = 4 }, new { name = ""grape"", diam = 1 } };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task NotOnEnumerableOfAnonymousTypeFromAQueryExpression()
{
await TestMissingAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
void Method()
{
var products = new List<Product>();
[|var|] productQuery = from prod in products
select new { prod.Color, prod.Price };
}
}
class Product
{
public ConsoleColor Color { get; set; }
public int Price { get; set; }
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeString()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = ""hello"";
}
}",
@"using System;
class C
{
static void M()
{
string s = ""hello"";
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnIntrinsicType()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}",
@"using System;
class C
{
static void M()
{
int s = 5;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnFrameworkType()
{
await TestAsync(
@"using System.Collections.Generic;
class C
{
static void M()
{
[|var|] c = new List<int>();
}
}",
@"using System.Collections.Generic;
class C
{
static void M()
{
List<int> c = new List<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnUserDefinedType()
{
await TestAsync(
@"using System;
class C
{
void M()
{
[|var|] c = new C();
}
}",
@"using System;
class C
{
void M()
{
C c = new C();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnGenericType()
{
await TestAsync(
@"using System;
class C<T>
{
static void M()
{
[|var|] c = new C<int>();
}
}",
@"using System;
class C<T>
{
static void M()
{
C<int> c = new C<int>();
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new int[4] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new int[4] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalArrayTypeWithNewOperator2()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] { 2, 4, 6, 8 };
}
}",
@"using System;
class C
{
static void M()
{
int[] n1 = new[] { 2, 4, 6, 8 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnSingleDimensionalJaggedArrayType()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}",
@"using System;
class C
{
static void M()
{
int[][] cs = new[] {
new[] { 1, 2, 3, 4 },
new[] { 5, 6, 7, 8 }
};
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithObjectInitializer()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
[|var|] cc = new Customer { City = ""Madras"" };
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
class C
{
static void M()
{
Customer cc = new Customer { City = ""Madras"" };
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionInitializer()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] digits = new List<int> { 1, 2, 3 };
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<int> digits = new List<int> { 1, 2, 3 };
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnDeclarationWithCollectionAndObjectInitializers()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
[|var|] cs = new List<Customer>
{
new Customer { City = ""Madras"" }
};
}
private class Customer
{
public string City { get; set; }
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
List<Customer> cs = new List<Customer>
{
new Customer { City = ""Madras"" }
};
}
private class Customer
{
public string City { get; set; }
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForStatement()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
for ([|var|] i = 0; i < 5; i++)
{
}
}
}",
@"using System;
class C
{
static void M()
{
for (int i = 0; i < 5; i++)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnForeachStatement()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach ([|var|] item in l)
{
}
}
}",
@"using System;
using System.Collections.Generic;
class C
{
static void M()
{
var l = new List<int> { 1, 3, 5 };
foreach (int item in l)
{
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnQueryExpression()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
[|var|] expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
var customers = new List<Customer>();
IEnumerable<Customer> expr = from c in customers
where c.City == ""London""
select c;
}
private class Customer
{
public string City { get; set; }
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeInUsingStatement()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
using ([|var|] r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}",
@"using System;
class C
{
static void M()
{
using (Res r = new Res())
{
}
}
private class Res : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnInterpolatedString()
{
await TestAsync(
@"using System;
class Program
{
void Method()
{
[|var|] s = $""Hello, {name}""
}
}",
@"using System;
class Program
{
void Method()
{
string s = $""Hello, {name}""
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnExplicitConversion()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
double x = 1234.7;
[|var|] a = (int)x;
}
}",
@"using System;
class C
{
static void M()
{
double x = 1234.7;
int a = (int)x;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnConditionalAccessExpression()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
C obj = new C();
[|var|] anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}",
@"using System;
class C
{
static void M()
{
C obj = new C();
C anotherObj = obj?.Test();
}
C Test()
{
return this;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInCheckedExpression()
{
await TestAsync(
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
[|var|] intNumber = checked((int)number1);
}
}",
@"using System;
class C
{
static void M()
{
long number1 = int.MaxValue + 20L;
int intNumber = checked((int)number1);
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInAwaitExpression()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
[|var|] text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public async void ProcessRead()
{
string text = await ReadTextAsync(null);
}
private async Task<string> ReadTextAsync(string filePath)
{
return string.Empty;
}
}", options: ExplicitTypeEverywhere());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInNumericType()
{
await TestAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = 1;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
int text = 1;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInCharType()
{
await TestAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = GetChar();
}
public char GetChar() => 'c';
}",
@"using System;
class C
{
public void ProcessRead()
{
char text = GetChar();
}
public char GetChar() => 'c';
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_string()
{
// though string isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestAsync(
@"using System;
class C
{
public void ProcessRead()
{
[|var|] text = string.Empty;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
string text = string.Empty;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeInBuiltInType_object()
{
// object isn't an intrinsic type per the compiler
// we in the IDE treat it as an intrinsic type for this feature.
await TestAsync(
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
[|var|] text = j;
}
}",
@"using System;
class C
{
public void ProcessRead()
{
object j = new C();
object text = j;
}
}", options: ExplicitTypeForBuiltInTypesOnly());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelNone()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestMissingAsync(source, ExplicitTypeNoneEnforcement());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelInfo()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] s = 5;
}
}";
await TestDiagnosticSeverityAndCountAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticCount: 1,
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Info);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelWarning()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new[] {2, 4, 6, 8};
}
}";
await TestDiagnosticSeverityAndCountAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticCount: 1,
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseImplicitType)]
public async Task SuggestExplicitTypeNotificationLevelError()
{
var source =
@"using System;
class C
{
static void M()
{
[|var|] n1 = new C();
}
}";
await TestDiagnosticSeverityAndCountAsync(source,
options: ExplicitTypeEnforcements(),
diagnosticCount: 1,
diagnosticId: IDEDiagnosticIds.UseExplicitTypeDiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Error);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTuple()
{
await TestAsync(
@"class C
{
static void M()
{
[|var|] s = (1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int, string) s = (1, ""hello"");
}
}",
options: ExplicitTypeEverywhere(),
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithNames()
{
await TestAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, b: ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string b) s = (a: 1, b: ""hello"");
}
}",
options: ExplicitTypeEverywhere(),
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExplicitType)]
public async Task SuggestExplicitTypeOnLocalWithIntrinsicTypeTupleWithOneName()
{
await TestAsync(
@"class C
{
static void M()
{
[|var|] s = (a: 1, ""hello"");
}
}",
@"class C
{
static void M()
{
(int a, string) s = (a: 1, ""hello"");
}
}",
options: ExplicitTypeEverywhere(),
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
/// <summary>
/// Will store animation information about a sequence of <see cref="OTContainer" /> frames.
/// </summary>
[System.Serializable]
public class OTAnimationFrameset
{
/// <summary>
/// Animation frameset name
/// </summary>
public string name;
/// <summary>
/// Animation frameset container
/// </summary>
public OTContainer container;
/// <summary>
/// Frameset container start frame, used if frameType is BY_FRAMENUMBER
/// </summary>
public int startFrame;
/// <summary>
/// Frameset container end frame, used if frameType is BY_FRAMENUMBER
/// </summary>
public int endFrame;
/// <summary>
/// Set of frame names, used if frameType is BY_NAME
/// </summary>
public string[] frameNames;
/// <summary>
/// Get frame names from container using this mask
/// </summary>
/// <description>
/// Can be the name prefix or a regular expression
/// For example a value of '^(?i:(idle))' will get all
/// frames that start with 'idle' and ignoring case.
/// When using a regular string value, the mask will
/// be validated as a case insensitive prefix
/// </description>
public string frameNameMask;
/// <summary>
/// If true, frame names will be sorted
/// </summary>
public bool sortFrameNames = true;
/// <summary>
/// Frameset (start to end) play count
/// </summary>
public int playCount = 1;
/// <summary>
/// Ping pong indicator
/// </summary>
/// <remarks>
/// By setting pingPong to true you indicate that this animation frameset has to bounce
/// back after the animation reaches this frameset's last frame. The end and start frame
/// of this animation frameset's will be only displayed once.
/// </remarks>
public bool pingPong = false;
/// <summary>
/// Animation frameset duration.
/// </summary>
/// <remarks>
/// This duration is used if only this animation's frameset is played and
/// this setting has a value bigger than 0. If the singleDuration is 0
/// the animation's fps setting will be used to calculate the actual duration.
/// </remarks>
public float singleDuration = 0f;
/// <summary>
/// Get the list of frame numbers for this frameset
/// </summary>
public int[] frameNumbers
{
get
{
int totalFrames = frameCount;
if ((container == null) || (totalFrames == 0))
{
return new int[] { };
}
int[] frames = new int[totalFrames];
int start, end, direction;
if (frameNameMask!="" && container!=null)
{
Regex regex = null;
try
{
if ((frameNameMask[0] == '^' || frameNameMask[0] == '[' || frameNameMask[0] == '('))
regex = new Regex( @frameNameMask );
}
catch(System.Exception)
{
regex = null;
}
List<string> names = new List<string>();
for (int f=0; f<container.frameCount; f++)
{
OTContainer.Frame fr = container.GetFrame(f);
try
{
if ((regex!=null && regex.Match(fr.name).Success) || (fr.name.ToLower().StartsWith(frameNameMask.ToLower())))
names.Add(fr.name);
}
catch(System.Exception)
{
}
}
frameNames = names.ToArray();
}
if (frameNames!=null && frameNames.Length > 0)
{
if (sortFrameNames)
System.Array.Sort(frameNames);
start = 0;
end = frameNames.Length - 1;
direction = 1;
}
else
{
start = (startFrame <= endFrame) ? startFrame : endFrame;
end = (startFrame <= endFrame) ? endFrame : startFrame;
direction = (startFrame <= endFrame) ? 1 : -1;
}
int numFrames = (end - start) + 1;
// Calculate a single play's worth of frames (this includes a ping pong)
int frameIndex = 0;
if (frames.Length<numFrames)
System.Array.Resize<int>(ref frames,numFrames);
for (int i = 0; i < numFrames; ++i)
{
if (frameNames != null && frameNames.Length>0)
frames[i] = container.GetFrameIndex(frameNames[frameIndex]);
else
frames[i] = start + frameIndex;
frameIndex += direction;
}
// Since we don't repeat the start or end frames, then we have to have more than 2 frames for this
// to work.
if ((numFrames > 2) && pingPong)
{
System.Array.Copy(frames, 1, frames, numFrames, numFrames - 2);
System.Array.Reverse(frames, numFrames, numFrames - 2);
numFrames = numFrames + (numFrames - 2);
}
// Now repeat that array copy for playCount times
if (playCount>1 && playCount<=10)
{
for (int i = 1; i < playCount; i++)
System.Array.Copy(frames, 0, frames, i * numFrames, numFrames);
}
else
if (playCount>1)
Debug.LogWarning("AnimationFrameset "+name+" is set to played more than 10 times!");
return frames;
}
}
/// <summary>
///
/// </summary>
public int baseFrameCount
{
get
{
int c;
if (frameNames!=null && frameNames.Length > 0)
c = frameNames.Length;
else
{
if (endFrame > startFrame)
{
c = (endFrame - startFrame + 1);
}
else
{
c = (startFrame - endFrame + 1);
}
}
return c;
}
}
/// <summary>
/// Frame count per play
/// </summary>
public int frameCountPerPlay
{
get
{
int c = baseFrameCount;
if ((c > 2) && pingPong)
{
c *= 2;
c -= 2;
}
return c;
}
}
int _frameCount = -1;
/// <summary>
/// Number of animation frames
/// </summary>
public int frameCount
{
get
{
if (Application.isPlaying)
{
if (_frameCount==-1)
_frameCount = frameCountPerPlay * playCount;
return _frameCount;
}
return frameCountPerPlay * playCount;
}
}
[HideInInspector]
public int startIndex = 0;
[HideInInspector]
public string _containerName = "";
}
| |
namespace android.preference
{
[global::MonoJavaBridge.JavaClass()]
public partial class PreferenceManager : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static PreferenceManager()
{
InitJNI();
}
protected PreferenceManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.preference.PreferenceManager.OnActivityDestroyListener_))]
public interface OnActivityDestroyListener : global::MonoJavaBridge.IJavaObject
{
void onActivityDestroy();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.preference.PreferenceManager.OnActivityDestroyListener))]
public sealed partial class OnActivityDestroyListener_ : java.lang.Object, OnActivityDestroyListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnActivityDestroyListener_()
{
InitJNI();
}
internal OnActivityDestroyListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onActivityDestroy6948;
void android.preference.PreferenceManager.OnActivityDestroyListener.onActivityDestroy()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.preference.PreferenceManager.OnActivityDestroyListener_._onActivityDestroy6948);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.PreferenceManager.OnActivityDestroyListener_.staticClass, global::android.preference.PreferenceManager.OnActivityDestroyListener_._onActivityDestroy6948);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.OnActivityDestroyListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager$OnActivityDestroyListener"));
global::android.preference.PreferenceManager.OnActivityDestroyListener_._onActivityDestroy6948 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.OnActivityDestroyListener_.staticClass, "onActivityDestroy", "()V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.preference.PreferenceManager.OnActivityResultListener_))]
public interface OnActivityResultListener : global::MonoJavaBridge.IJavaObject
{
bool onActivityResult(int arg0, int arg1, android.content.Intent arg2);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.preference.PreferenceManager.OnActivityResultListener))]
public sealed partial class OnActivityResultListener_ : java.lang.Object, OnActivityResultListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnActivityResultListener_()
{
InitJNI();
}
internal OnActivityResultListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onActivityResult6949;
bool android.preference.PreferenceManager.OnActivityResultListener.onActivityResult(int arg0, int arg1, android.content.Intent arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.preference.PreferenceManager.OnActivityResultListener_._onActivityResult6949, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.preference.PreferenceManager.OnActivityResultListener_.staticClass, global::android.preference.PreferenceManager.OnActivityResultListener_._onActivityResult6949, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.OnActivityResultListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager$OnActivityResultListener"));
global::android.preference.PreferenceManager.OnActivityResultListener_._onActivityResult6949 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.OnActivityResultListener_.staticClass, "onActivityResult", "(IILandroid/content/Intent;)Z");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.preference.PreferenceManager.OnActivityStopListener_))]
public interface OnActivityStopListener : global::MonoJavaBridge.IJavaObject
{
void onActivityStop();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.preference.PreferenceManager.OnActivityStopListener))]
public sealed partial class OnActivityStopListener_ : java.lang.Object, OnActivityStopListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnActivityStopListener_()
{
InitJNI();
}
internal OnActivityStopListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onActivityStop6950;
void android.preference.PreferenceManager.OnActivityStopListener.onActivityStop()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.preference.PreferenceManager.OnActivityStopListener_._onActivityStop6950);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.PreferenceManager.OnActivityStopListener_.staticClass, global::android.preference.PreferenceManager.OnActivityStopListener_._onActivityStop6950);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.OnActivityStopListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager$OnActivityStopListener"));
global::android.preference.PreferenceManager.OnActivityStopListener_._onActivityStop6950 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.OnActivityStopListener_.staticClass, "onActivityStop", "()V");
}
}
internal static global::MonoJavaBridge.MethodId _getSharedPreferences6951;
public virtual global::android.content.SharedPreferences getSharedPreferences()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.SharedPreferences>(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.PreferenceManager._getSharedPreferences6951)) as android.content.SharedPreferences;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.SharedPreferences>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._getSharedPreferences6951)) as android.content.SharedPreferences;
}
internal static global::MonoJavaBridge.MethodId _createPreferenceScreen6952;
public virtual global::android.preference.PreferenceScreen createPreferenceScreen(android.content.Context arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.PreferenceManager._createPreferenceScreen6952, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.preference.PreferenceScreen;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._createPreferenceScreen6952, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.preference.PreferenceScreen;
}
internal static global::MonoJavaBridge.MethodId _getSharedPreferencesName6953;
public virtual global::java.lang.String getSharedPreferencesName()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.PreferenceManager._getSharedPreferencesName6953)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._getSharedPreferencesName6953)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _setSharedPreferencesName6954;
public virtual void setSharedPreferencesName(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.preference.PreferenceManager._setSharedPreferencesName6954, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._setSharedPreferencesName6954, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSharedPreferencesMode6955;
public virtual int getSharedPreferencesMode()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.preference.PreferenceManager._getSharedPreferencesMode6955);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._getSharedPreferencesMode6955);
}
internal static global::MonoJavaBridge.MethodId _setSharedPreferencesMode6956;
public virtual void setSharedPreferencesMode(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.preference.PreferenceManager._setSharedPreferencesMode6956, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._setSharedPreferencesMode6956, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getDefaultSharedPreferences6957;
public static global::android.content.SharedPreferences getDefaultSharedPreferences(android.content.Context arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.SharedPreferences>(@__env.CallStaticObjectMethod(android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._getDefaultSharedPreferences6957, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.SharedPreferences;
}
internal static global::MonoJavaBridge.MethodId _findPreference6958;
public virtual global::android.preference.Preference findPreference(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.preference.PreferenceManager._findPreference6958, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.preference.Preference;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._findPreference6958, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.preference.Preference;
}
public android.preference.Preference findPreference(string arg0)
{
return findPreference((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
internal static global::MonoJavaBridge.MethodId _setDefaultValues6959;
public static void setDefaultValues(android.content.Context arg0, int arg1, bool arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._setDefaultValues6959, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _setDefaultValues6960;
public static void setDefaultValues(android.content.Context arg0, java.lang.String arg1, int arg2, int arg3, bool arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.preference.PreferenceManager.staticClass, global::android.preference.PreferenceManager._setDefaultValues6960, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
public static global::java.lang.String METADATA_KEY_PREFERENCES
{
get
{
return "android.preference";
}
}
public static global::java.lang.String KEY_HAS_SET_DEFAULT_VALUES
{
get
{
return "_has_set_default_values";
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.preference.PreferenceManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/preference/PreferenceManager"));
global::android.preference.PreferenceManager._getSharedPreferences6951 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "getSharedPreferences", "()Landroid/content/SharedPreferences;");
global::android.preference.PreferenceManager._createPreferenceScreen6952 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "createPreferenceScreen", "(Landroid/content/Context;)Landroid/preference/PreferenceScreen;");
global::android.preference.PreferenceManager._getSharedPreferencesName6953 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "getSharedPreferencesName", "()Ljava/lang/String;");
global::android.preference.PreferenceManager._setSharedPreferencesName6954 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "setSharedPreferencesName", "(Ljava/lang/String;)V");
global::android.preference.PreferenceManager._getSharedPreferencesMode6955 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "getSharedPreferencesMode", "()I");
global::android.preference.PreferenceManager._setSharedPreferencesMode6956 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "setSharedPreferencesMode", "(I)V");
global::android.preference.PreferenceManager._getDefaultSharedPreferences6957 = @__env.GetStaticMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "getDefaultSharedPreferences", "(Landroid/content/Context;)Landroid/content/SharedPreferences;");
global::android.preference.PreferenceManager._findPreference6958 = @__env.GetMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "findPreference", "(Ljava/lang/CharSequence;)Landroid/preference/Preference;");
global::android.preference.PreferenceManager._setDefaultValues6959 = @__env.GetStaticMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "setDefaultValues", "(Landroid/content/Context;IZ)V");
global::android.preference.PreferenceManager._setDefaultValues6960 = @__env.GetStaticMethodIDNoThrow(global::android.preference.PreferenceManager.staticClass, "setDefaultValues", "(Landroid/content/Context;Ljava/lang/String;IIZ)V");
}
}
}
| |
using DevExpress.Mvvm;
using DevExpress.Mvvm.UI;
using DevExpress.Mvvm.UI.Interactivity;
using NUnit.Framework;
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using System.Windows.Data;
using DevExpress.Mvvm.POCO;
using System.Windows.Interop;
using System.Reflection;
using System.Security;
using System.Security.Policy;
using System.Linq;
using DevExpress.Mvvm.Native;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Collections.Generic;
namespace DevExpress.Mvvm.UI.Tests {
internal class SplashScreenTestWindow : Window, ISplashScreen {
public Button WindowContent { get; private set; }
public double Progress { get; private set; }
public bool IsIndeterminate { get; private set; }
public string TextProp { get; private set; }
public bool CloseRequested { get; private set; }
public void Text(string value) {
TextProp = value;
}
public SplashScreenTestWindow() {
Instance = this;
Progress = double.NaN;
IsIndeterminate = true;
Width = 100;
Height = 100;
Content = WindowContent = new Button();
SetCurrentValue(ShowInTaskbarProperty, false);
}
void ISplashScreen.Progress(double value) {
Progress = value;
}
void ISplashScreen.CloseSplashScreen() {
Close();
CloseRequested = true;
}
void ISplashScreen.SetProgressState(bool isIndeterminate) {
IsIndeterminate = isIndeterminate;
}
public static volatile SplashScreenTestWindow Instance = null;
public static void DoEvents(DispatcherPriority priority = DispatcherPriority.Background) {
DispatcherObject dispObj = (Instance ?? DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen);
if(dispObj == null)
return;
DispatcherFrame frame = new DispatcherFrame();
dispObj.Dispatcher.BeginInvoke(
priority,
new DispatcherOperationCallback(ExitFrame),
frame);
Dispatcher.PushFrame(frame);
}
static object ExitFrame(object f) {
((DispatcherFrame)f).Continue = false;
return null;
}
}
internal class SplashScreenTestUserControl : UserControl {
public static volatile Window Window;
public static volatile SplashScreenViewModel ViewModel;
public static Func<ControlTemplate> TemplateCreator;
public static SplashScreenTestUserControl Instance { get; set; }
public static void DoEvents(DispatcherPriority priority = DispatcherPriority.Background) {
DispatcherObject dispObj = DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen;
if(dispObj == null)
return;
DispatcherFrame frame = new DispatcherFrame();
dispObj.Dispatcher.BeginInvoke(
priority,
new DispatcherOperationCallback(ExitFrame),
frame);
Dispatcher.PushFrame(frame);
}
static object ExitFrame(object f) {
Window = Window.GetWindow(Instance);
ViewModel = (SplashScreenViewModel)Instance.DataContext;
((DispatcherFrame)f).Continue = false;
return null;
}
public SplashScreenTestUserControl() {
Instance = this;
if(TemplateCreator != null)
Template = TemplateCreator.Invoke();
}
}
public class DXSplashScreenBaseTestFixture : BaseWpfFixture {
protected override void SetUpCore() {
base.SetUpCore();
DXSplashScreen.UIThreadDelay = 700;
DXSplashScreen.NotInitializedStateMethodCallPolicy = NotInitializedStateMethodCallPolicy.CallWhenReady;
}
protected override void TearDownCore() {
SplashScreenTestUserControl.Window = null;
SplashScreenTestUserControl.ViewModel = null;
SplashScreenTestUserControl.Instance = null;
SplashScreenTestUserControl.TemplateCreator = null;
SplashScreenTestWindow.Instance = null;
var info = DXSplashScreen.SplashContainer?.ActiveInfo;
var oldInfo = DXSplashScreen.SplashContainer?.OldInfo;
if(info != null && info.WaitEvent != null)
info.WaitEvent.Set();
if(oldInfo != null && oldInfo.WaitEvent != null)
oldInfo.WaitEvent.Set();
CloseDXSplashScreen();
base.TearDownCore();
}
protected void CloseDXSplashScreen() {
SplashScreenTestsHelper.CloseDXSplashScreen();
}
protected Rect GetSplashScreenBounds() {
var splashScreen = DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen;
Rect pos = Rect.Empty;
SplashScreenHelper.InvokeAsync(splashScreen, () => {
pos = new Rect(splashScreen.Left, splashScreen.Top, splashScreen.ActualWidth, splashScreen.ActualHeight);
});
SplashScreenTestUserControl.DoEvents();
return pos;
}
protected WindowStartupLocation? GetSplashScreenStartupLocation() {
WindowStartupLocation? pos = null;
var spScr = DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen;
SplashScreenHelper.InvokeAsync(spScr, () => pos = spScr.WindowStartupLocation);
SplashScreenTestUserControl.DoEvents();
return pos;
}
protected static bool HasFadeAnimation(Window wnd) {
return Interaction.GetBehaviors(wnd).Any(x => x is WindowFadeAnimationBehavior);
}
protected static bool AreRectsClose(Rect rect1, Rect rect2, double accuracy = 5) {
return ArePointsClose(rect1.TopLeft, rect2.TopLeft)
&& rect1.Size == rect2.Size;
}
protected static bool ArePointsClose(Point point1, Point point2, double accuracy = 5) {
return Math.Abs(point1.X - point2.X) < accuracy
&& Math.Abs(point1.Y - point2.Y) < accuracy;
}
}
[TestFixture]
public class DXSplashScreenTests : DXSplashScreenBaseTestFixture {
[Test, Order(1)]
public void InvalidUsage_Test01() {
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.Show<SplashScreenTestWindow>();
DXSplashScreen.Show<SplashScreenTestWindow>();
});
}
[Test, Order(2)]
public void InvalidUsage_Test02() {
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.Close();
});
}
[Test, Order(3)]
public void InvalidUsage_Test03() {
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.Progress(0);
});
}
[Test, Ignore("Ignore")]
public void Simple_Test() {
DXSplashScreen.Show<SplashScreenTestWindow>();
Assert.IsNotNull(DXSplashScreen.SplashContainer.ActiveInfo.InternalThread);
Assert.IsNotNull(DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen);
SplashScreenTestWindow.DoEvents();
Assert.IsNotNull(SplashScreenTestWindow.Instance, "SplashScreenTestWindow.Instance == null");
Assert.IsNotNull(SplashScreenTestWindow.Instance.WindowContent, "SplashScreenTestWindow.Instance == null");
Assert.IsTrue(SplashScreenTestWindow.Instance.WindowContent.IsVisible);
Assert.AreEqual(double.NaN, SplashScreenTestWindow.Instance.Progress);
Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate);
CloseDXSplashScreen();
Assert.IsNull(DXSplashScreen.SplashContainer.OldInfo.InternalThread);
Assert.IsNull(DXSplashScreen.SplashContainer.OldInfo.SplashScreen);
}
[Test, Order(4)]
public void Complex_Test() {
DXSplashScreen.Show<SplashScreenTestWindow>();
Assert.IsNotNull(DXSplashScreen.SplashContainer.ActiveInfo.InternalThread);
Assert.IsNotNull(DXSplashScreen.SplashContainer.ActiveInfo.Dispatcher);
Assert.IsNotNull(DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen);
Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate);
DXSplashScreen.Progress(0);
SplashScreenTestWindow.DoEvents();
Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate);
for(int i = 1; i < 10; i++) {
DXSplashScreen.Progress(i);
SplashScreenTestWindow.DoEvents();
Assert.AreEqual(i, SplashScreenTestWindow.Instance.Progress);
}
CloseDXSplashScreen();
Assert.IsNull(DXSplashScreen.SplashContainer.OldInfo.InternalThread);
Assert.IsNull(DXSplashScreen.SplashContainer.OldInfo.SplashScreen);
}
[Test, Order(5)]
public void IsActive_Test() {
Assert.IsFalse(DXSplashScreen.IsActive);
DXSplashScreen.Show<SplashScreenTestWindow>();
Assert.IsTrue(DXSplashScreen.IsActive);
CloseDXSplashScreen();
Assert.IsFalse(DXSplashScreen.IsActive);
}
[Test, Order(6)]
public void CustomSplashScreen_Test() {
Func<object, Window> windowCreator = (p) => {
Assert.AreEqual(1, p);
return new SplashScreenTestWindow();
};
Func<object, object> splashScreenCreator = (p) => {
Assert.AreEqual(1, p);
return new TextBlock();
};
DXSplashScreen.Show(windowCreator, splashScreenCreator, 1, 1);
Assert.IsNotNull(DXSplashScreen.SplashContainer.ActiveInfo.InternalThread);
Assert.IsNotNull(DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen);
CloseDXSplashScreen();
Assert.IsNull(DXSplashScreen.SplashContainer.OldInfo.InternalThread);
Assert.IsNull(DXSplashScreen.SplashContainer.OldInfo.SplashScreen);
}
[Test, Order(7)]
public void ShowWindowISplashScreen_Test() {
DXSplashScreen.Show<SplashScreenTestWindow>();
SplashScreenTestWindow.DoEvents();
Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(double.NaN, SplashScreenTestWindow.Instance.Progress);
DXSplashScreen.Progress(100);
SplashScreenTestWindow.DoEvents();
Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress);
DXSplashScreen.Progress(100, 200);
SplashScreenTestWindow.DoEvents();
Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress);
DXSplashScreen.CallSplashScreenMethod<SplashScreenTestWindow>(x => x.Text("test"));
SplashScreenTestWindow.DoEvents();
Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress);
Assert.AreEqual("test", ((SplashScreenTestWindow)SplashScreenTestWindow.Instance).TextProp);
DXSplashScreen.SetState("test");
SplashScreenTestWindow.DoEvents();
}
[Test, Order(8)]
public void ShowWindowNotISplashScreen_Test() {
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.Show<Window>();
});
}
[Test, Order(9)]
public void ShowUserControl_Test() {
DXSplashScreen.Show<SplashScreenTestUserControl>();
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(0, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(true, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
DXSplashScreen.Progress(50);
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(50, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
DXSplashScreen.Progress(100, 200);
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
DXSplashScreen.SetState("Test");
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Test", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
}
[Test, Order(10)]
public void ShowUserControlAndCheckWindowProperties_Test() {
DXSplashScreen.Show<SplashScreenTestUserControl>();
SplashScreenTestUserControl.DoEvents();
Window wnd = SplashScreenTestUserControl.Window;
AutoResetEvent SyncEvent = new AutoResetEvent(false);
bool hasError = true;
wnd.Dispatcher.BeginInvoke(new Action(() => {
hasError = false;
hasError = hasError | !(WindowStartupLocation.CenterScreen == wnd.WindowStartupLocation);
hasError = hasError | !(true == HasFadeAnimation(wnd));
hasError = hasError | !(null == wnd.Style);
hasError = hasError | !(WindowStyle.None == wnd.WindowStyle);
hasError = hasError | !(ResizeMode.NoResize == wnd.ResizeMode);
hasError = hasError | !(true == wnd.AllowsTransparency);
hasError = hasError | !(Colors.Transparent == ((SolidColorBrush)wnd.Background).Color);
hasError = hasError | !(false == wnd.ShowInTaskbar);
hasError = hasError | !(true == wnd.Topmost);
hasError = hasError | !(SizeToContent.WidthAndHeight == wnd.SizeToContent);
SyncEvent.Set();
}));
SyncEvent.WaitOne(TimeSpan.FromSeconds(2));
Assert.IsFalse(hasError);
CloseDXSplashScreen();
}
[Test, Order(11)]
public void TestQ338517_1() {
DXSplashScreen.Show<SplashScreenTestWindow>();
Assert.IsNotNull(DXSplashScreen.SplashContainer.ActiveInfo.InternalThread);
Assert.IsNotNull(DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen);
SplashScreenTestWindow.DoEvents();
Assert.IsTrue(SplashScreenTestWindow.Instance.WindowContent.IsVisible);
Assert.AreEqual(double.NaN, SplashScreenTestWindow.Instance.Progress);
Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate);
DXSplashScreen.CallSplashScreenMethod<SplashScreenTestWindow>(x => x.Text("Test"));
SplashScreenTestWindow.DoEvents();
Assert.AreEqual("Test", ((SplashScreenTestWindow)SplashScreenTestWindow.Instance).TextProp);
CloseDXSplashScreen();
Assert.IsNull(DXSplashScreen.SplashContainer.OldInfo.InternalThread);
Assert.IsNull(DXSplashScreen.SplashContainer.OldInfo.SplashScreen);
}
[Test, Order(13)]
public void SplashScreenOwner_Test00() {
var owner = new SplashScreenOwner(new Border());
DXSplashScreen.Show<SplashScreenTestUserControl>(WindowStartupLocation.CenterScreen, owner);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.AreEqual(owner.Owner, info.Owner.WindowObject);
Assert.IsNotNull(info.InternalThread);
Assert.IsFalse(info.Owner.IsInitialized);
CloseDXSplashScreen();
}
[Test, Order(14)]
public void SplashScreenOwner_Test01() {
DXSplashScreen.Show<SplashScreenTestUserControl>();
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.IsNull(info.Owner);
Assert.IsNotNull(info.InternalThread);
Assert.IsNull(info.RelationInfo);
CloseDXSplashScreen();
}
[Test, Order(15)]
public void SplashScreenOwner_Test02() {
var owner = new SplashScreenOwner(new Border());
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, new object[] { owner }, null);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.AreEqual(owner.Owner, info.Owner.WindowObject);
Assert.IsNotNull(info.InternalThread);
Assert.IsFalse(info.Owner.IsInitialized);
CloseDXSplashScreen();
}
[Test, Order(16)]
public void SplashScreenOwner_Test03() {
var owner = new WindowContainer(new Border());
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, new object[] { owner }, null);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.AreEqual(owner, info.Owner);
Assert.IsNotNull(info.InternalThread);
Assert.IsFalse(info.Owner.IsInitialized);
CloseDXSplashScreen();
}
[Test, Order(17)]
public void SplashScreenOwner_Test04() {
var owner = new WindowContainer(new Border());
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, new object[] { owner.CreateOwnerContainer() }, null);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.AreEqual(owner, info.Owner);
Assert.IsNotNull(info.InternalThread);
Assert.IsFalse(info.Owner.IsInitialized);
CloseDXSplashScreen();
}
[Test, Order(18)]
public void SplashScreenOwner_Test05() {
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, null, null);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.IsNull(info.Owner);
Assert.IsNotNull(info.InternalThread);
Assert.IsNull(info.RelationInfo);
CloseDXSplashScreen();
}
[Test, Order(19)]
public void NotShowIfOwnerClosedTest00_T268403() {
RealWindow.Show();
DispatcherHelper.DoEvents();
var owner = new SplashScreenOwner(RealWindow);
RealWindow.Close();
if(DXSplashScreen.SplashContainer != null)
DXSplashScreen.SplashContainer.Test_SkipWindowOpen = false;
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, new object[] { owner }, null);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
EnqueueWait(() => info.InternalThread == null);
Assert.IsFalse(DXSplashScreen.IsActive);
Assert.IsTrue(DXSplashScreen.SplashContainer.Test_SkipWindowOpen);
CloseDXSplashScreen();
}
[Test, Order(20)]
public void NotShowIfOwnerClosedTest01_T268403() {
RealWindow.Show();
RealWindow.Close();
DispatcherHelper.DoEvents();
var owner = new SplashScreenOwner(RealWindow);
if(DXSplashScreen.SplashContainer != null)
DXSplashScreen.SplashContainer.Test_SkipWindowOpen = true;
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, new object[] { owner, SplashScreenClosingMode.ManualOnly }, null);
EnqueueDelay(100);
DispatcherHelper.DoEvents();
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.IsNotNull(info.InternalThread);
Assert.IsFalse(info.RelationInfo.IsInitialized, "relation");
Assert.IsTrue(DXSplashScreen.IsActive);
Assert.IsFalse(DXSplashScreen.SplashContainer.Test_SkipWindowOpen, "skipOpen");
CloseDXSplashScreen();
}
[Test, Order(21)]
public void SplashScreenStartupLocation_Test00() {
var owner = new SplashScreenOwner(RealWindow);
RealWindow.WindowStartupLocation = WindowStartupLocation.Manual;
RealWindow.Left = 200;
RealWindow.Width = 300;
RealWindow.Top = 100;
RealWindow.Height = 240;
RealWindow.Show();
DispatcherHelper.DoEvents();
SplashScreenTestUserControl.TemplateCreator = SplashScreenTestsHelper.CreateControlTemplate;
DXSplashScreen.Show<SplashScreenTestUserControl>(WindowStartupLocation.CenterOwner, owner);
SplashScreenTestUserControl.DoEvents();
Rect pos = GetSplashScreenBounds();
Assert.AreEqual(true, ArePointsClose(new Point(290, 150), pos.TopLeft));
CloseDXSplashScreen();
}
[Test, Order(22)]
public void SplashScreenStartupLocation_Test01() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show<SplashScreenTestUserControl>(WindowStartupLocation.CenterOwner);
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(WindowStartupLocation.CenterOwner, GetSplashScreenStartupLocation().Value);
CloseDXSplashScreen();
}
[Test, Order(23)]
public void SplashScreenStartupLocation_Test02() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show<SplashScreenTestUserControl>(WindowStartupLocation.CenterScreen);
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(WindowStartupLocation.CenterScreen, GetSplashScreenStartupLocation().Value);
CloseDXSplashScreen();
}
[Test, Order(24)]
public void SplashScreenStartupLocation_Test03() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show<SplashScreenTestUserControl>(WindowStartupLocation.Manual);
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(WindowStartupLocation.Manual, GetSplashScreenStartupLocation().Value);
CloseDXSplashScreen();
}
[Test, Order(25)]
public void SplashScreenStartupLocation_Test04() {
var owner = new SplashScreenOwner(RealWindow);
RealWindow.WindowStartupLocation = WindowStartupLocation.Manual;
RealWindow.Left = 200;
RealWindow.Width = 300;
RealWindow.Top = 100;
RealWindow.Height = 240;
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, new object[] { owner, WindowStartupLocation.CenterOwner }, null);
SplashScreenTestUserControl.DoEvents();
Rect pos = GetSplashScreenBounds();
Assert.AreEqual(true, ArePointsClose(new Point(270, 130), pos.TopLeft));
CloseDXSplashScreen();
}
[Test, Order(26)]
public void SplashScreenStartupLocation_Test05() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show<SplashScreenTestUserControl>(WindowStartupLocation.CenterScreen, new SplashScreenOwner(RealWindow));
SplashScreenTestUserControl.DoEvents();
Rect pos = GetSplashScreenBounds();
var screen = System.Windows.Forms.Screen.PrimaryScreen;
Assert.IsNotNull(screen);
var area = screen.WorkingArea;
var expectedPos = new Point(area.X + (area.Width - pos.Width) * 0.5, area.Y + (area.Height - pos.Height) * 0.5);
Assert.IsTrue(Math.Abs(expectedPos.X - pos.Left) < 2);
Assert.IsTrue(Math.Abs(expectedPos.Y - pos.Top) < 2);
var splashScreen = DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen;
SplashScreenHelper.InvokeAsync(splashScreen, () => {
SplashScreenTestUserControl.Instance.Width = 400;
SplashScreenTestUserControl.Instance.Height = 300;
});
SplashScreenTestUserControl.DoEvents();
DispatcherHelper.DoEvents();
pos = GetSplashScreenBounds();
expectedPos = new Point(area.X + (area.Width - pos.Width) * 0.5, area.Y + (area.Height - pos.Height) * 0.5);
Assert.IsTrue(Math.Abs(expectedPos.X - pos.Left) < 2);
Assert.IsTrue(Math.Abs(expectedPos.Y - pos.Top) < 2);
CloseDXSplashScreen();
}
[Test, Order(27)]
public void SplashScreenClosingMode_Test00() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show<SplashScreenTestUserControl>(WindowStartupLocation.CenterScreen, new SplashScreenOwner(RealWindow), SplashScreenClosingMode.Default);
SplashScreenTestUserControl.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
RealWindow.Close();
DispatcherHelper.DoEvents();
Assert.IsFalse(DXSplashScreen.IsActive);
}
[Test, Order(28)]
public void SplashScreenClosingMode_Test01() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show<SplashScreenTestUserControl>(WindowStartupLocation.CenterScreen, new SplashScreenOwner(RealWindow), SplashScreenClosingMode.ManualOnly);
SplashScreenTestUserControl.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
RealWindow.Close();
DispatcherHelper.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
CloseDXSplashScreen();
}
[Test, Order(29)]
public void SplashScreenClosingMode_Test02() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show<SplashScreenTestUserControl>(WindowStartupLocation.CenterScreen, new SplashScreenOwner(RealWindow), SplashScreenClosingMode.OnParentClosed);
SplashScreenTestUserControl.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
RealWindow.Close();
DispatcherHelper.DoEvents();
Assert.IsFalse(DXSplashScreen.IsActive);
}
[Test, Order(30)]
public void SplashScreenClosingMode_Test03() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show<SplashScreenTestUserControl>(WindowStartupLocation.CenterScreen, new SplashScreenOwner(RealWindow), SplashScreenClosingMode.OnParentClosed);
SplashScreenTestUserControl.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
CloseDXSplashScreen();
Assert.IsFalse(DXSplashScreen.IsActive);
RealWindow.Close();
}
[Test, Order(31)]
public void SplashScreenClosingMode_Test04() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, new object[] { new SplashScreenOwner(RealWindow), SplashScreenClosingMode.Default }, null);
SplashScreenTestUserControl.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
RealWindow.Close();
DispatcherHelper.DoEvents();
Assert.IsFalse(DXSplashScreen.IsActive);
}
[Test, Order(32)]
public void SplashScreenClosingMode_Test05() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, new object[] { new SplashScreenOwner(RealWindow), SplashScreenClosingMode.ManualOnly }, null);
SplashScreenTestUserControl.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
RealWindow.Close();
DispatcherHelper.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
CloseDXSplashScreen();
Assert.IsFalse(DXSplashScreen.IsActive);
}
[Test, Order(33)]
public void SplashScreenClosingMode_Test06() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, new object[] { new SplashScreenOwner(RealWindow), SplashScreenClosingMode.OnParentClosed }, null);
SplashScreenTestUserControl.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
RealWindow.Close();
DispatcherHelper.DoEvents();
Assert.IsFalse(DXSplashScreen.IsActive);
}
[Test, Order(34)]
public void SplashScreenClosingMode_Test07() {
RealWindow.Show();
DispatcherHelper.DoEvents();
DXSplashScreen.Show(CreateDefaultWindow, CreateDefaultContent, new object[] { new SplashScreenOwner(RealWindow), SplashScreenClosingMode.OnParentClosed }, null);
SplashScreenTestUserControl.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
CloseDXSplashScreen();
Assert.IsFalse(DXSplashScreen.IsActive);
RealWindow.Close();
}
[Test, Order(35)]
public void NonInitializedCallbacks_Test00() {
EnsureSplashScreenContainer(true);
DXSplashScreen.UIThreadDelay = 0;
DXSplashScreen.Show<SplashScreenTestUserControl>();
DXSplashScreen.SetState("init");
DXSplashScreen.Progress(1, 2);
Assert.IsNull(SplashScreenTestUserControl.Instance);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
info.WaitEvent.Set();
EnqueueWait(() => SplashScreenTestUserControl.Instance != null);
SplashScreenTestUserControl.DoEvents();
Assert.IsNotNull(SplashScreenTestUserControl.Instance);
Assert.IsNotNull(SplashScreenTestUserControl.ViewModel);
Assert.AreEqual("init", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(1, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(2, SplashScreenTestUserControl.ViewModel.MaxProgress);
DispatcherHelper.DoEvents();
}
[Test, Order(36)]
public void NonInitializedCallbacks_Test01() {
EnsureSplashScreenContainer(true);
DXSplashScreen.UIThreadDelay = 0;
DXSplashScreen.Show<SplashScreenTestUserControl>();
Assert.IsTrue(DXSplashScreen.IsActive);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
DXSplashScreen.Close();
Assert.IsFalse(DXSplashScreen.IsActive);
Assert.IsTrue(info.IsActive);
info.WaitEvent.Set();
EnqueueWait(() => !info.IsActive);
}
[Test, Order(37)]
public void NonInitializedCallbacks_Test02() {
EnsureSplashScreenContainer(true);
DXSplashScreen.NotInitializedStateMethodCallPolicy = NotInitializedStateMethodCallPolicy.Discard;
DXSplashScreen.UIThreadDelay = 0;
DXSplashScreen.Show<SplashScreenTestUserControl>();
DXSplashScreen.SetState("init");
DXSplashScreen.Progress(1, 2);
Assert.IsNull(SplashScreenTestUserControl.Instance);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
info.WaitEvent.Set();
EnqueueWait(() => SplashScreenTestUserControl.Instance != null);
SplashScreenTestUserControl.DoEvents();
Assert.IsNotNull(SplashScreenTestUserControl.Instance);
Assert.IsNotNull(SplashScreenTestUserControl.ViewModel);
Assert.AreEqual(SplashScreenViewModel.StateDefaultValue, SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(SplashScreenViewModel.ProgressDefaultValue, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(SplashScreenViewModel.MaxProgressDefaultValue, SplashScreenTestUserControl.ViewModel.MaxProgress);
DispatcherHelper.DoEvents();
}
[Test, Order(38)]
public void NonInitializedCallbacks_Test03() {
EnsureSplashScreenContainer(true);
DXSplashScreen.NotInitializedStateMethodCallPolicy = NotInitializedStateMethodCallPolicy.Discard;
DXSplashScreen.UIThreadDelay = 0;
DXSplashScreen.Show<SplashScreenTestUserControl>();
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.IsTrue(DXSplashScreen.IsActive);
DXSplashScreen.Close();
Assert.IsFalse(DXSplashScreen.IsActive);
Assert.IsTrue(info.IsActive);
info.WaitEvent.Set();
EnqueueWait(() => SplashScreenTestUserControl.Instance != null);
SplashScreenTestUserControl.DoEvents();
DispatcherHelper.DoEvents();
EnqueueDelay(2000);
Assert.IsTrue(info.IsActive);
info.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(info.SplashScreen.Close));
SplashScreenTestsHelper.JoinThread(info);
}
[Test, Order(39)]
public void NonInitializedCallbacks_Test04() {
EnsureSplashScreenContainer(true);
DXSplashScreen.NotInitializedStateMethodCallPolicy = NotInitializedStateMethodCallPolicy.Exception;
DXSplashScreen.UIThreadDelay = 0;
DXSplashScreen.Show<SplashScreenTestUserControl>();
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.SetState("state");
});
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.Progress(1, 2);
});
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.Close();
});
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.CallSplashScreenMethod<Window>(x => { });
});
var info = DXSplashScreen.SplashContainer.ActiveInfo;
info.WaitEvent.Set();
EnqueueWait(() => SplashScreenTestUserControl.Instance != null);
}
[Test, Order(40)]
public void NonInitializedCallbacks_Test05() {
EnsureSplashScreenContainer(true);
DXSplashScreen.UIThreadDelay = 0;
DXSplashScreen.Show<SplashScreenTestWindow>();
Assert.IsNull(SplashScreenTestWindow.Instance);
DXSplashScreen.SetState("init");
DXSplashScreen.Progress(2, 3);
DXSplashScreen.CallSplashScreenMethod<SplashScreenTestWindow>(x => x.Text("init"));
var info = DXSplashScreen.SplashContainer.ActiveInfo;
info.WaitEvent.Set();
EnqueueWait(() => SplashScreenTestWindow.Instance != null);
SplashScreenTestWindow.DoEvents();
Assert.IsNotNull(SplashScreenTestWindow.Instance);
Assert.AreEqual("init", SplashScreenTestWindow.Instance.TextProp);
Assert.AreEqual(2, SplashScreenTestWindow.Instance.Progress);
DispatcherHelper.DoEvents();
}
[Test, Order(41)]
public void NonInitializedCallbacks_Test06() {
EnsureSplashScreenContainer(true);
DXSplashScreen.UIThreadDelay = 0;
DXSplashScreen.Show<SplashScreenTestWindow>();
Assert.IsTrue(DXSplashScreen.IsActive);
Assert.IsNull(SplashScreenTestWindow.Instance);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
DXSplashScreen.Close();
Assert.IsFalse(DXSplashScreen.IsActive);
Assert.IsTrue(info.IsActive);
info.WaitEvent.Set();
EnqueueWait(() => SplashScreenTestWindow.Instance != null && SplashScreenTestWindow.Instance.CloseRequested);
}
[Test, Order(43)]
public void NonInitializedCallbacks_Test07() {
EnsureSplashScreenContainer(true);
DXSplashScreen.UIThreadDelay = 0;
DXSplashScreen.NotInitializedStateMethodCallPolicy = NotInitializedStateMethodCallPolicy.Discard;
DXSplashScreen.Show<SplashScreenTestWindow>();
Assert.IsNull(SplashScreenTestWindow.Instance);
DXSplashScreen.SetState("init");
DXSplashScreen.Progress(2, 3);
DXSplashScreen.CallSplashScreenMethod<SplashScreenTestWindow>(x => x.Text("init"));
var info = DXSplashScreen.SplashContainer.ActiveInfo;
info.WaitEvent.Set();
EnqueueWait(() => SplashScreenTestWindow.Instance != null);
SplashScreenTestWindow.DoEvents();
Assert.IsNotNull(SplashScreenTestWindow.Instance);
Assert.IsNull(SplashScreenTestWindow.Instance.TextProp);
Assert.AreEqual(double.NaN, SplashScreenTestWindow.Instance.Progress);
DispatcherHelper.DoEvents();
}
[Test, Order(44)]
public void NonInitializedCallbacks_Test08() {
EnsureSplashScreenContainer(true);
DXSplashScreen.UIThreadDelay = 0;
DXSplashScreen.NotInitializedStateMethodCallPolicy = NotInitializedStateMethodCallPolicy.Discard;
DXSplashScreen.Show<SplashScreenTestWindow>();
Assert.IsNull(SplashScreenTestWindow.Instance);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.IsTrue(DXSplashScreen.IsActive);
DXSplashScreen.Close();
Assert.IsFalse(DXSplashScreen.IsActive);
Assert.IsTrue(info.IsActive);
info.WaitEvent.Set();
EnqueueWait(() => SplashScreenTestWindow.Instance != null);
SplashScreenTestWindow.DoEvents();
DispatcherHelper.DoEvents();
EnqueueDelay(2000);
Assert.IsTrue(info.IsActive);
Assert.IsFalse(SplashScreenTestWindow.Instance.CloseRequested);
info.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(info.SplashScreen.Close));
SplashScreenTestsHelper.JoinThread(info);
}
[Test, Order(45)]
public void NonInitializedCallbacks_Test09() {
EnsureSplashScreenContainer(true);
DXSplashScreen.NotInitializedStateMethodCallPolicy = NotInitializedStateMethodCallPolicy.Exception;
DXSplashScreen.UIThreadDelay = 0;
DXSplashScreen.Show<SplashScreenTestWindow>();
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.SetState("state");
});
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.Progress(1, 2);
});
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.Close();
});
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreen.CallSplashScreenMethod<Window>(x => { });
});
var info = DXSplashScreen.SplashContainer.ActiveInfo;
info.WaitEvent.Set();
EnqueueWait(() => SplashScreenTestWindow.Instance != null);
SplashScreenTestWindow.DoEvents();
}
static Window CreateDefaultWindow(object parameter) {
return new Window() { Width = 160, Height = 180 };
}
static object CreateDefaultContent(object parameter) {
return new SplashScreenTestUserControl();
}
void EnsureSplashScreenContainer(bool waitForMainThread) {
if(DXSplashScreen.SplashContainer == null)
DXSplashScreen.SplashContainer = new DXSplashScreen.SplashScreenContainer();
if(waitForMainThread)
DXSplashScreen.SplashContainer.ActiveInfo.WaitEvent = new AutoResetEvent(false);
}
}
[TestFixture]
public class DXSplashScreenServiceTests : DXSplashScreenBaseTestFixture {
public class ContainerVM {
public virtual double Progress { get; set; }
public virtual double MaxProgress { get; set; }
public virtual object State { get; set; }
}
[Test]
public void TestB238799() {
DXSplashScreenService s = new DXSplashScreenService();
((ISplashScreenService)s).HideSplashScreen();
((ISplashScreenService)s).HideSplashScreen();
}
[Test]
public void ShowWindowISplashScreen() {
ISplashScreenService service = new DXSplashScreenService() {
SplashScreenType = typeof(SplashScreenTestWindow),
};
service.ShowSplashScreen();
SplashScreenTestWindow.DoEvents();
Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(double.NaN, SplashScreenTestWindow.Instance.Progress);
service.SetSplashScreenProgress(100, 100);
SplashScreenTestWindow.DoEvents();
Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress);
service.SetSplashScreenProgress(100, 200);
SplashScreenTestWindow.DoEvents();
Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress);
DXSplashScreen.CallSplashScreenMethod<SplashScreenTestWindow>(x => x.Text("test"));
SplashScreenTestWindow.DoEvents();
Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress);
Assert.AreEqual("test", ((SplashScreenTestWindow)SplashScreenTestWindow.Instance).TextProp);
DXSplashScreen.SetState("test");
service.SetSplashScreenState("test");
SplashScreenTestWindow.DoEvents();
service.HideSplashScreen();
}
[Test]
public void ShowWindowNotISplashScreen2() {
ISplashScreenService service = new DXSplashScreenService() {
SplashScreenType = typeof(Window),
};
Assert.Throws<InvalidOperationException>(() => {
service.ShowSplashScreen();
});
}
[Test]
public void ShowUserControl() {
ISplashScreenService service = SplashScreenTestsHelper.CreateDefaultService();
ShowUserControlCore(service);
}
[Test]
public void BindServiceProperties() {
var service = SplashScreenTestsHelper.CreateDefaultService();
ISplashScreenService iService = service;
Border container = new Border();
ContainerVM vm = ViewModelSource.Create(() => new ContainerVM());
container.DataContext = vm;
vm.State = "Loading2";
BindingOperations.SetBinding(service, DXSplashScreenService.ProgressProperty, new Binding("Progress"));
BindingOperations.SetBinding(service, DXSplashScreenService.MaxProgressProperty, new Binding("MaxProgress"));
BindingOperations.SetBinding(service, DXSplashScreenService.StateProperty, new Binding("State"));
Interaction.GetBehaviors(container).Add(service);
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(0, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(0, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading2", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
vm.Progress = 50; vm.MaxProgress = 100;
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(50, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading2", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
vm.Progress = 100; vm.MaxProgress = 200;
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading2", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
vm.State = "Test";
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Test", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
iService.HideSplashScreen();
}
[Test]
public void ShowUserControlViaSplashScreenType() {
ISplashScreenService service = new DXSplashScreenService() {
SplashScreenType = typeof(SplashScreenTestUserControl),
};
ShowUserControlCore(service);
}
void ShowUserControlCore(ISplashScreenService service) {
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(0, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(true, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
service.SetSplashScreenProgress(50, 100);
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(50, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
service.SetSplashScreenProgress(100, 200);
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
service.SetSplashScreenState("Test");
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(200, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Test", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
service.HideSplashScreen();
}
[Test]
public void ShowUserControlAndCheckWindowProperties() {
ISplashScreenService service = SplashScreenTestsHelper.CreateDefaultService();
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
Window wnd = SplashScreenTestUserControl.Window;
AutoResetEvent SyncEvent = new AutoResetEvent(false);
bool hasError = true;
wnd.Dispatcher.BeginInvoke(new Action(() => {
hasError = false;
hasError = hasError | !(WindowStartupLocation.CenterScreen == wnd.WindowStartupLocation);
hasError = hasError | !(true == HasFadeAnimation(wnd));
hasError = hasError | !(null == wnd.Style);
hasError = hasError | !(WindowStyle.None == wnd.WindowStyle);
hasError = hasError | !(ResizeMode.NoResize == wnd.ResizeMode);
hasError = hasError | !(true == wnd.AllowsTransparency);
hasError = hasError | !(Colors.Transparent == ((SolidColorBrush)wnd.Background).Color);
hasError = hasError | !(false == wnd.ShowInTaskbar);
hasError = hasError | !(true == wnd.Topmost);
hasError = hasError | !(false == wnd.IsActive);
hasError = hasError | !(SizeToContent.WidthAndHeight == wnd.SizeToContent);
SyncEvent.Set();
}));
SyncEvent.WaitOne(TimeSpan.FromSeconds(2));
Assert.IsFalse(hasError);
service.HideSplashScreen();
}
[Test]
public void ShowUserControlAndCheckWindowProperties2() {
Style wndStyle = new Style();
ISplashScreenService service = new DXSplashScreenService() {
ViewTemplate = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(SplashScreenTestUserControl)) },
SplashScreenWindowStyle = wndStyle,
SplashScreenStartupLocation = WindowStartupLocation.Manual,
};
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
CheckWindowStyle(wndStyle, SplashScreenTestUserControl.Window);
service.HideSplashScreen();
}
[Test]
public void ShowUserControlAndCheckWindowProperties3() {
Style wndStyle = new Style();
ISplashScreenService service = new DXSplashScreenService() {
SplashScreenType = typeof(SplashScreenTestUserControl),
SplashScreenWindowStyle = wndStyle,
SplashScreenStartupLocation = WindowStartupLocation.Manual,
};
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
CheckWindowStyle(wndStyle, SplashScreenTestUserControl.Window);
service.HideSplashScreen();
}
[Test]
public void ShowUserControlAndCheckWindowProperties4() {
Style wndStyle = new Style();
wndStyle.Setters.Add(new Setter(System.Windows.Window.ShowActivatedProperty, false));
wndStyle.Setters.Add(new Setter(System.Windows.Window.ShowInTaskbarProperty, true));
ISplashScreenService service = new DXSplashScreenService() {
SplashScreenType = typeof(SplashScreenTestWindow),
SplashScreenWindowStyle = wndStyle,
SplashScreenStartupLocation = WindowStartupLocation.Manual,
};
service.ShowSplashScreen();
SplashScreenTestWindow.DoEvents();
CheckWindowStyle(wndStyle, SplashScreenTestWindow.Instance);
service.HideSplashScreen();
}
void CheckWindowStyle(Style style, Window wnd) {
AutoResetEvent SyncEvent = new AutoResetEvent(false);
bool hasError = true;
wnd.Dispatcher.BeginInvoke(new Action(() => {
hasError = false;
hasError = hasError | !(WindowStartupLocation.Manual == wnd.WindowStartupLocation);
hasError = hasError | !(true == HasFadeAnimation(wnd));
hasError = hasError | !(style == wnd.Style);
hasError = hasError | !(WindowStyle.SingleBorderWindow == wnd.WindowStyle);
hasError = hasError | !(ResizeMode.CanResize == wnd.ResizeMode);
hasError = hasError | !(false == wnd.AllowsTransparency);
hasError = hasError | !(true == wnd.ShowInTaskbar);
hasError = hasError | !(false == wnd.Topmost);
hasError = hasError | !(false == wnd.IsActive);
hasError = hasError | !(SizeToContent.Manual == wnd.SizeToContent);
SyncEvent.Set();
}));
SyncEvent.WaitOne(TimeSpan.FromSeconds(2));
Assert.IsFalse(hasError);
}
[Test]
public void ViewTemplateShouldBeSealed() {
DataTemplate temp = SplashScreenTestsHelper.CreateDefaultTemplate();
Assert.IsFalse(temp.IsSealed);
DXSplashScreenService service = new DXSplashScreenService() {
ViewTemplate = temp,
};
Assert.IsTrue(temp.IsSealed);
}
[Test]
public void ViewTemplateSelectorIsNotSupported() {
Assert.Throws<InvalidOperationException>(() => {
DXSplashScreenService service = new DXSplashScreenService() {
ViewTemplateSelector = new DataTemplateSelector(),
};
});
}
#if !DXCORE3
[Test]
#endif
public void WindowShouldBeActivatedOnCloseSplashScreen_Test() {
DXSplashScreenService service = CreateDefaultSplashScreenAndShow();
var wnd = SplashScreenTestUserControl.Window;
Assert.IsTrue(RealWindow.IsActive);
wnd.Dispatcher.BeginInvoke(new Action(() => {
wnd.Activate();
}));
SplashScreenTestUserControl.DoEvents();
Assert.IsFalse(RealWindow.IsActive, "RealWindow - !IsActive");
wnd.Dispatcher.BeginInvoke(new Action(() => {
Assert.IsTrue(wnd.IsActive, "SplashScreen - IsActive");
}));
CloseDXSplashScreen();
DispatcherHelper.DoEvents();
Assert.IsTrue(RealWindow.IsActive, "RealWindow - IsActive");
}
[Test]
public void SplashScreenOwnerPriority_Test00() {
var fakeOwner = new Border();
DXSplashScreenService service = CreateDefaultSplashScreenAndShow(fakeOwner, activateWindow:false);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.AreEqual(fakeOwner, info.Owner.WindowObject);
Assert.IsFalse(info.Owner.IsInitialized);
Assert.IsNull(info.Owner.Window);
}
[Test]
public void SplashScreenOwnerPriority_Test01() {
var fakeOwner = new Border();
DXSplashScreenService service = CreateDefaultSplashScreenAndShow(RealWindow, activateWindow: false, windowContent:fakeOwner);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.AreEqual(RealWindow, info.Owner.WindowObject);
Assert.IsTrue(info.Owner.IsInitialized);
Assert.AreEqual(RealWindow, info.Owner.Window);
Assert.AreEqual(new WindowInteropHelper(RealWindow).Handle, info.Owner.Handle);
}
[Test]
public void SplashScreenOwnerPriority_Test02() {
var fakeOwner = new Border();
DXSplashScreenService service = CreateDefaultSplashScreenAndShow(null, activateWindow: false, windowContent: fakeOwner);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.AreEqual(fakeOwner, info.Owner.WindowObject);
Assert.IsTrue(info.Owner.IsInitialized);
Assert.AreEqual(RealWindow, info.Owner.Window);
}
[Test]
public void SplashScreenOwnerPriority_Test03() {
var fakeOwner = new Border();
DXSplashScreenService service = CreateDefaultSplashScreenAndShow(RealWindow, SplashScreenOwnerSearchMode.IgnoreAssociatedObject, false, fakeOwner);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.AreEqual(RealWindow, info.Owner.WindowObject);
Assert.IsTrue(info.Owner.IsInitialized);
Assert.AreEqual(RealWindow, info.Owner.Window);
}
[Test]
public void SplashScreenOwnerPriority_Test04() {
var service = CreateDefaultSplashScreenAndShow(null, SplashScreenOwnerSearchMode.OwnerOnly);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.IsNull(info.Owner);
Assert.IsNull(info.RelationInfo);
}
[Test]
public void SplashScreenOwnerPriority_Test05() {
var service = CreateDefaultSplashScreenAndShow(RealWindow, SplashScreenOwnerSearchMode.OwnerOnly);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.AreEqual(RealWindow, info.Owner.WindowObject);
Assert.IsTrue(info.Owner.IsInitialized);
Assert.AreEqual(RealWindow, info.Owner.Window);
}
[Test]
public void SplashScreenClosingMode_Test00() {
var service = CreateDefaultSplashScreenAndShow(null);
Assert.IsTrue(DXSplashScreen.IsActive);
RealWindow.Close();
SplashScreenTestUserControl.DoEvents();
DispatcherHelper.DoEvents();
Assert.IsFalse(DXSplashScreen.IsActive);
}
[Test]
public void SplashScreenClosingMode_Test01() {
var service = CreateDefaultSplashScreenAndShow(null, SplashScreenOwnerSearchMode.Full, true, null, SplashScreenClosingMode.OnParentClosed);
Assert.IsTrue(DXSplashScreen.IsActive);
RealWindow.Close();
SplashScreenTestUserControl.DoEvents();
DispatcherHelper.DoEvents();
Assert.IsFalse(DXSplashScreen.IsActive);
}
[Test]
public void SplashScreenClosingMode_Test02() {
var service = CreateDefaultSplashScreenAndShow(null, SplashScreenOwnerSearchMode.Full, true, null, SplashScreenClosingMode.ManualOnly);
Assert.IsTrue(DXSplashScreen.IsActive);
RealWindow.Close();
SplashScreenTestUserControl.DoEvents();
DispatcherHelper.DoEvents();
Assert.IsTrue(DXSplashScreen.IsActive);
CloseDXSplashScreen();
}
[Test]
public void ShowSplashScreenImmediatelAfterClose_Test00_T186338() {
ISplashScreenService service = SplashScreenTestsHelper.CreateDefaultService();
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
Assert.IsTrue(service.IsSplashScreenActive);
service.HideSplashScreen();
Assert.IsFalse(service.IsSplashScreenActive);
service.ShowSplashScreen();
Assert.IsTrue(service.IsSplashScreenActive);
SplashScreenTestUserControl.DoEvents();
service.HideSplashScreen();
Assert.IsFalse(service.IsSplashScreenActive);
}
[Test]
public void ShowSplashScreenImmediatelAfterClose_Test01_T186338() {
ISplashScreenService service = SplashScreenTestsHelper.CreateDefaultService();
ISplashScreenService service1 = SplashScreenTestsHelper.CreateDefaultService();
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
service.HideSplashScreen();
Assert.IsFalse(service.IsSplashScreenActive);
service1.ShowSplashScreen();
Assert.IsTrue(service1.IsSplashScreenActive);
SplashScreenTestUserControl.DoEvents();
service1.HideSplashScreen();
}
[Test]
public void SplashScreenStartupLocationCenterOwner_Test00() {
var service = SplashScreenTestsHelper.CreateDefaultService();
var windowStyle = new Style(typeof(Window));
windowStyle.Setters.Add(new Setter(FrameworkElement.WidthProperty, 180d));
windowStyle.Setters.Add(new Setter(FrameworkElement.HeightProperty, 160d));
service.SplashScreenWindowStyle = windowStyle;
service.SplashScreenOwner = RealWindow;
service.SplashScreenStartupLocation = WindowStartupLocation.CenterOwner;
RealWindow.WindowStartupLocation = WindowStartupLocation.Manual;
RealWindow.Left = 400;
RealWindow.Width = 200;
RealWindow.Top = 200;
RealWindow.Height = 300;
RealWindow.Show();
DispatcherHelper.DoEvents();
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
Rect pos = GetSplashScreenBounds();
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(true, AreRectsClose(new Rect(410, 270, 180, 160), pos));
CloseDXSplashScreen();
}
[Test]
public void SplashScreenStartupLocationCenterOwner_Test01() {
SplashScreenTestUserControl.TemplateCreator = SplashScreenTestsHelper.CreateControlTemplate;
var service = SplashScreenTestsHelper.CreateDefaultService();
service.SplashScreenStartupLocation = WindowStartupLocation.CenterOwner;
service.SplashScreenOwner = RealWindow;
RealWindow.WindowStartupLocation = WindowStartupLocation.Manual;
RealWindow.Left = 200;
RealWindow.Width = 300;
RealWindow.Top = 100;
RealWindow.Height = 240;
RealWindow.Show();
DispatcherHelper.DoEvents();
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
Rect pos = GetSplashScreenBounds();
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(true, AreRectsClose(new Rect(290, 150, 120, 140), pos));
CloseDXSplashScreen();
}
[Test]
public void SplashScreenStartupLocationCenterOwner_Test02() {
var service = SplashScreenTestsHelper.CreateDefaultService();
service.SplashScreenStartupLocation = WindowStartupLocation.CenterOwner;
RealWindow.Show();
DispatcherHelper.DoEvents();
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
var pos = GetSplashScreenStartupLocation();
Assert.AreEqual(WindowStartupLocation.CenterOwner, pos.Value);
CloseDXSplashScreen();
}
[Test]
public void FadeDuration_Test00() {
var service = SplashScreenTestsHelper.CreateDefaultService();
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
WindowFadeAnimationBehavior fb = null;
var spScr = DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen;
SplashScreenHelper.InvokeAsync(spScr, () => fb = Interaction.GetBehaviors(spScr).OfType<WindowFadeAnimationBehavior>().First());
SplashScreenTestUserControl.DoEvents();
Assert.IsNotNull(fb);
}
[Test]
public void FadeDuration_Test01() {
var service = SplashScreenTestsHelper.CreateDefaultService();
service.FadeInDuration = TimeSpan.FromMilliseconds(150);
service.FadeOutDuration = TimeSpan.FromMilliseconds(100);
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
double fid = 0;
double fod = 0;
var spScr = DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen;
SplashScreenHelper.InvokeAsync(spScr, () => {
var wfab = Interaction.GetBehaviors(spScr).OfType<WindowFadeAnimationBehavior>().First();
fod = wfab.FadeOutDuration.TotalMilliseconds;
fid = wfab.FadeInDuration.TotalMilliseconds;
});
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(fid, 150);
Assert.AreEqual(fod, 100);
}
[Test]
public void FadeDuration_Test02() {
var service = SplashScreenTestsHelper.CreateDefaultService();
service.FadeInDuration = TimeSpan.FromMilliseconds(150);
service.FadeOutDuration = TimeSpan.FromMilliseconds(0);
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
double fid = 0;
double fod = 0;
var spScr = DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen;
SplashScreenHelper.InvokeAsync(spScr, () => {
var wfab = Interaction.GetBehaviors(spScr).OfType<WindowFadeAnimationBehavior>().First();
fod = wfab.FadeOutDuration.TotalMilliseconds;
fid = wfab.FadeInDuration.TotalMilliseconds;
});
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(fid, 150);
Assert.AreEqual(fod, 0);
}
[Test]
public void FadeDuration_Test03() {
var service = SplashScreenTestsHelper.CreateDefaultService();
service.FadeInDuration = TimeSpan.FromMilliseconds(0);
service.FadeOutDuration = TimeSpan.FromMilliseconds(100);
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
double fid = 0;
double fod = 0;
var spScr = DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen;
SplashScreenHelper.InvokeAsync(spScr, () => {
var wfab = Interaction.GetBehaviors(spScr).OfType<WindowFadeAnimationBehavior>().First();
fod = wfab.FadeOutDuration.TotalMilliseconds;
fid = wfab.FadeInDuration.TotalMilliseconds;
});
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(fid, 0);
Assert.AreEqual(fod, 100);
}
[Test]
public void FadeDuration_Test04() {
var service = SplashScreenTestsHelper.CreateDefaultService();
service.FadeInDuration = TimeSpan.FromMilliseconds(0);
service.FadeOutDuration = TimeSpan.FromMilliseconds(0);
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
WindowFadeAnimationBehavior fb = null;
var spScr = DXSplashScreen.SplashContainer.ActiveInfo.SplashScreen;
SplashScreenHelper.InvokeAsync(spScr, () => fb = Interaction.GetBehaviors(spScr).OfType<WindowFadeAnimationBehavior>().FirstOrDefault());
SplashScreenTestUserControl.DoEvents();
Assert.IsNull(fb);
}
[Test]
public void UseIndependentWindow_Test00() {
var service = SplashScreenTestsHelper.CreateDefaultService();
service.ShowSplashScreen();
Assert.IsNull(service.GetSplashContainer(false));
AssertIsActive(service, true);
Assert.IsTrue(DXSplashScreen.IsActive);
SplashScreenTestsHelper.CloseSplashScreenService(service);
}
[Test]
public void UseIndependentWindow_Test01() {
var service = SplashScreenTestsHelper.CreateDefaultService();
service.UseIndependentWindow = true;
service.ShowSplashScreen();
Assert.IsNotNull(service.GetSplashContainer(false));
AssertIsActive(service, true);
Assert.IsFalse(DXSplashScreen.IsActive);
SplashScreenTestsHelper.CloseSplashScreenService(service);
}
[Test]
public void UseIndependentWindow_Test02() {
var service = SplashScreenTestsHelper.CreateDefaultService();
service.ShowSplashScreen();
AssertHelper.AssertThrows<InvalidOperationException>(() => service.UseIndependentWindow = true);
SplashScreenTestsHelper.CloseSplashScreenService(service);
}
[Test]
public void UseIndependentWindow_Test03() {
var service = SplashScreenTestsHelper.CreateDefaultService();
var service1 = SplashScreenTestsHelper.CreateDefaultService();
service.ShowSplashScreen();
AssertIsActive(service, true);
AssertIsActive(service1, true);
service1.UseIndependentWindow = true;
AssertIsActive(service1, false);
service1.ShowSplashScreen();
AssertIsActive(service1, true);
SplashScreenTestsHelper.CloseSplashScreenService(service);
AssertIsActive(service, false);
AssertIsActive(service1, true);
SplashScreenTestsHelper.CloseSplashScreenService(service1);
AssertIsActive(service1, false);
}
[Test]
public void UseIndependentWindow_Test04() {
var service = SplashScreenTestsHelper.CreateDefaultService();
var service1 = SplashScreenTestsHelper.CreateDefaultService();
service.ShowSplashScreen();
AssertIsActive(service, true);
AssertIsActive(service1, true);
service1.UseIndependentWindow = true;
AssertIsActive(service1, false);
service1.ShowSplashScreen();
AssertIsActive(service1, true);
SplashScreenTestsHelper.CloseSplashScreenService(service1);
AssertIsActive(service, true);
AssertIsActive(service1, false);
SplashScreenTestsHelper.CloseSplashScreenService(service);
AssertIsActive(service, false);
}
[Test]
public void UseIndependentWindow_Test05() {
var service = SplashScreenTestsHelper.CreateDefaultService();
var service1 = SplashScreenTestsHelper.CreateDefaultService();
var service2 = SplashScreenTestsHelper.CreateDefaultService();
service.UseIndependentWindow = true;
service1.UseIndependentWindow = true;
service2.UseIndependentWindow = true;
service.ShowSplashScreen();
AssertIsActive(service, true);
AssertIsActive(service1, false);
AssertIsActive(service2, false);
service1.ShowSplashScreen();
AssertIsActive(service, true);
AssertIsActive(service1, true);
AssertIsActive(service2, false);
service2.ShowSplashScreen();
AssertIsActive(service, true);
AssertIsActive(service1, true);
AssertIsActive(service2, true);
Assert.IsFalse(DXSplashScreen.IsActive);
SplashScreenTestsHelper.CloseSplashScreenService(service);
SplashScreenTestsHelper.CloseSplashScreenService(service1);
AssertIsActive(service, false);
AssertIsActive(service1, false);
AssertIsActive(service2, true);
SplashScreenTestsHelper.CloseSplashScreenService(service2);
AssertIsActive(service2, false);
}
[Test]
public void UseIndependentWindow_Test06() {
ISplashScreenService service = new DXSplashScreenService() {
SplashScreenType = typeof(SplashScreenTestWindow),
UseIndependentWindow = true
};
service.ShowSplashScreen();
SplashScreenTestWindow.DoEvents();
Assert.IsTrue(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(double.NaN, SplashScreenTestWindow.Instance.Progress);
service.SetSplashScreenProgress(100, 100);
SplashScreenTestWindow.DoEvents();
Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress);
service.SetSplashScreenProgress(100, 200);
SplashScreenTestWindow.DoEvents();
Assert.IsFalse(SplashScreenTestWindow.Instance.IsIndeterminate);
Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress);
AssertHelper.AssertThrows<InvalidOperationException>(() => DXSplashScreen.Progress(10, 20));
SplashScreenTestWindow.DoEvents();
Assert.AreEqual(100, SplashScreenTestWindow.Instance.Progress);
SplashScreenTestsHelper.CloseSplashScreenService(service);
}
[Test, Ignore("Ignore")]
public void UseIndependentWindow_Test07() {
ISplashScreenService service = new DXSplashScreenService() {
ViewTemplate = SplashScreenTestsHelper.CreateDefaultTemplate(),
UseIndependentWindow = true
};
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(0, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(true, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
DXSplashScreen.Progress(50);
DXSplashScreen.SetState("Test");
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(0, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Loading...", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(true, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
service.SetSplashScreenProgress(50, 100);
service.SetSplashScreenState("Test");
SplashScreenTestUserControl.DoEvents();
Assert.AreEqual(50, SplashScreenTestUserControl.ViewModel.Progress);
Assert.AreEqual(100, SplashScreenTestUserControl.ViewModel.MaxProgress);
Assert.AreEqual("Test", SplashScreenTestUserControl.ViewModel.State);
Assert.AreEqual(false, SplashScreenTestUserControl.ViewModel.IsIndeterminate);
}
[Test]
public void SplashScreenStyleShouldBePatched_T257139_Test00() {
var fakeOwner = new Border();
DXSplashScreenService service = CreateDefaultSplashScreenAndShow(fakeOwner, activateWindow: false);
Assert.AreEqual(SplashScreenHelper.WS_EX_TRANSPARENT, SplashScreenHelper.Test_WindowStyleModifier);
}
[Test]
public void SplashScreenStyleShouldBePatched_T257139_Test01() {
DXSplashScreen.UseDefaultAltTabBehavior = true;
DXSplashScreenService service = CreateDefaultSplashScreenAndShow(null, activateWindow: false, ownerSearchMode: SplashScreenOwnerSearchMode.OwnerOnly);
Assert.AreEqual(0, SplashScreenHelper.Test_WindowStyleModifier);
DXSplashScreen.UseDefaultAltTabBehavior = false;
}
[Test]
public void SplashScreenStyleShouldBePatched_T257139_T335564_Test02() {
DXSplashScreenService service = CreateDefaultSplashScreenAndShow(null, activateWindow: false, ownerSearchMode: SplashScreenOwnerSearchMode.OwnerOnly);
Assert.AreEqual(SplashScreenHelper.WS_EX_TOOLWINDOW, SplashScreenHelper.Test_WindowStyleModifier);
}
[Test]
public void IsSplashScreenActiveDep_Test01_T728696() {
ISplashScreenService s = new DXSplashScreenService { UseIndependentWindow = false, SplashScreenType = typeof(SplashScreenTestUserControl) };
Assert.IsFalse(s.IsSplashScreenActive);
var task = new Task(() => DXSplashScreen.Show(typeof(SplashScreenTestUserControl)));
task.Start();
EnqueueWait(() => task.IsCompleted);
SplashScreenTestUserControl.DoEvents();
Assert.IsTrue(s.IsSplashScreenActive);
DXSplashScreen.Close();
Assert.IsFalse(s.IsSplashScreenActive);
}
[Test, Ignore("Unstable")]
public void UpdateIsSplashScreenActiveOnHiddenWindow_Test00() {
UpdateIsSplashScreenActiveOnHiddenWindow_TestBase(false);
}
[Test, Ignore("Unstable")]
public void UpdateIsSplashScreenActiveOnHiddenWindow_Test01() {
UpdateIsSplashScreenActiveOnHiddenWindow_TestBase(true);
}
void UpdateIsSplashScreenActiveOnHiddenWindow_TestBase(bool useIndependentWindow) {
SplashScreenTestWindow1.StartVisibility = Visibility.Hidden;
ISplashScreenService s = new DXSplashScreenService { UseIndependentWindow = useIndependentWindow, SplashScreenType = typeof(SplashScreenTestWindow1) };
var descriptor = DependencyPropertyDescriptor.FromProperty(DXSplashScreenService.IsSplashScreenActiveProperty, typeof(DXSplashScreenService));
List<bool> eventValues = new List<bool>();
var handler = new EventHandler((o, e) => eventValues.Add(s.IsSplashScreenActive));
descriptor.AddValueChanged(s, handler);
try {
s.ShowSplashScreen();
EnqueueWait(() => eventValues.Count == 2);
Assert.IsTrue(eventValues[0]);
Assert.IsFalse(eventValues[1]);
} finally {
descriptor.RemoveValueChanged(s, handler);
}
}
[Test]
public void UpdateIsSplashScreenActiveOnHiddenWindow_Test02() {
SplashScreenTestWindow1.StartVisibility = Visibility.Collapsed;
ISplashScreenService s = new DXSplashScreenService { UseIndependentWindow = false, SplashScreenType = typeof(SplashScreenTestWindow1) };
s.ShowSplashScreen();
SplashScreenTestWindow.DoEvents();
Assert.IsTrue(s.IsSplashScreenActive);
s.HideSplashScreen();
EnqueueWait(() => !s.IsSplashScreenActive);
Assert.IsFalse(s.IsSplashScreenActive);
}
[Test]
public void UpdateIsSplashScreenActiveOnHiddenWindow_Test03() {
SplashScreenTestWindow1.StartVisibility = Visibility.Collapsed;
ISplashScreenService s = new DXSplashScreenService { UseIndependentWindow = true, SplashScreenType = typeof(SplashScreenTestWindow1) };
s.ShowSplashScreen();
SplashScreenTestWindow.DoEvents();
Assert.IsTrue(s.IsSplashScreenActive);
s.HideSplashScreen();
EnqueueWait(() => !s.IsSplashScreenActive);
Assert.IsFalse(s.IsSplashScreenActive);
}
[Test]
public void UpdateIsSplashScreenActiveOnHiddenWindow_Test04() {
ISplashScreenService s = new DXSplashScreenService { UseIndependentWindow = false, SplashScreenType = typeof(SplashScreenTestWindow) };
s.ShowSplashScreen();
SplashScreenTestWindow.DoEvents();
Assert.IsTrue(s.IsSplashScreenActive);
SplashScreenTestWindow.Instance.Dispatcher.BeginInvoke(new Action(() => SplashScreenTestWindow.Instance.Close()));
EnqueueWait(() => !s.IsSplashScreenActive);
Assert.IsFalse(s.IsSplashScreenActive);
}
[Test]
public void UpdateIsSplashScreenActiveOnHiddenWindow_Test05() {
ISplashScreenService s = new DXSplashScreenService { UseIndependentWindow = true, SplashScreenType = typeof(SplashScreenTestWindow) };
s.ShowSplashScreen();
SplashScreenTestWindow.DoEvents();
Assert.IsTrue(s.IsSplashScreenActive);
SplashScreenTestWindow.Instance.Dispatcher.BeginInvoke(new Action(() => SplashScreenTestWindow.Instance.Close()));
EnqueueWait(() => !s.IsSplashScreenActive);
Assert.IsFalse(s.IsSplashScreenActive);
}
class SplashScreenTestWindow1 : SplashScreenTestWindow {
internal static Visibility StartVisibility { get; set; } = Visibility.Hidden;
public SplashScreenTestWindow1() {
Visibility = StartVisibility;
}
}
void AssertIsActive(DXSplashScreenService service, bool checkValue) {
Assert.AreEqual(checkValue, ((ISplashScreenService)service).IsSplashScreenActive);
}
DXSplashScreenService CreateDefaultSplashScreenAndShow(FrameworkElement owner = null, SplashScreenOwnerSearchMode ownerSearchMode = SplashScreenOwnerSearchMode.Full,
bool activateWindow = true, FrameworkElement windowContent = null, SplashScreenClosingMode? closingMode = null) {
return SplashScreenTestsHelper.CreateDefaultSplashScreenAndShow(RealWindow, owner, ownerSearchMode, activateWindow, windowContent, closingMode);
}
}
#if !DXCORE3
[TestFixture, Platform("NET")]
public class DXSplashScreenServiceIsolatedAppDomainTests {
Window RealWindow { get; set; }
[Test]
public void SplashScreenOwnerPriority_Test04() {
IsolatedDomainTestHelper.RunTest(() => {
Application app = new Application();
var window = new Window();
app.MainWindow = window;
app.Startup += (o, e) => {
RealWindow = new Window();
window.Show();
DispatcherHelper.UpdateLayoutAndDoEvents(window);
RealWindow.Show();
if(!RealWindow.IsActive)
RealWindow.Activate();
DispatcherHelper.UpdateLayoutAndDoEvents(RealWindow);
var fakeOwner = new Border();
DXSplashScreenService service = SplashScreenTestsHelper.CreateDefaultSplashScreenAndShow(null, null, SplashScreenOwnerSearchMode.IgnoreAssociatedObject, true, fakeOwner);
var info = DXSplashScreen.SplashContainer.ActiveInfo;
Assert.IsNotNull(info.Owner.WindowObject);
Assert.AreEqual(SplashScreenHelper.GetApplicationActiveWindow(true), info.Owner.WindowObject);
Assert.IsTrue(info.Owner.IsInitialized);
Assert.AreEqual(RealWindow, info.Owner.Window);
SplashScreenTestsHelper.CloseDXSplashScreen();
RealWindow.Close();
RealWindow.Content = null;
DispatcherHelper.UpdateLayoutAndDoEvents(RealWindow);
RealWindow = null;
window.Close();
DispatcherHelper.UpdateLayoutAndDoEvents(window);
};
app.Run();
});
}
[Test]
public void CloseOnAppUnhandledException_Test_T149746() {
IsolatedDomainTestHelper.RunTest(() => {
Assert.IsNull(DXSplashScreen.SplashContainer);
try {
Application app = new Application();
app.Startup += (o, e) => {
var service = new DXSplashScreenService() {
ViewTemplate = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(SplashScreenTestUserControl)) },
};
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
Assert.IsNotNull(DXSplashScreen.SplashContainer);
Assert.IsTrue(DXSplashScreen.IsActive);
throw new NotImplementedException();
};
app.Run();
} catch(NotImplementedException) { }
DispatcherHelper.DoEvents();
Assert.IsNotNull(DXSplashScreen.SplashContainer);
Assert.IsFalse(DXSplashScreen.IsActive);
var thread = DXSplashScreen.SplashContainer.OldInfo.InternalThread;
if(thread != null)
thread.Join();
});
}
}
#endif
static class SplashScreenTestsHelper {
public static void CloseDXSplashScreen() {
JoinThread(DXSplashScreen.SplashContainer.With(x => x.OldInfo));
if(!DXSplashScreen.IsActive)
return;
DXSplashScreen.Close();
JoinThread(DXSplashScreen.SplashContainer.With(x => x.OldInfo));
}
public static void CloseSplashScreenService(ISplashScreenService service) {
var dxservice = service as DXSplashScreenService;
bool useDefaultClose = dxservice == null || dxservice.GetSplashContainer(false).Return(x => !x.IsActive, () => true);
if(useDefaultClose) {
CloseDXSplashScreen();
return;
}
var container = dxservice.GetSplashContainer(false);
service.HideSplashScreen();
JoinThread(container.OldInfo);
}
internal static void JoinThread(DXSplashScreen.SplashScreenContainer.SplashScreenInfo info) {
if(info == null)
return;
var t = info.InternalThread;
if(t != null && t.IsAlive)
t.Join();
}
public static ControlTemplate CreateControlTemplate() {
var border = new FrameworkElementFactory(typeof(Border));
border.SetValue(Border.WidthProperty, 120d);
border.SetValue(Border.HeightProperty, 140d);
return new ControlTemplate(typeof(SplashScreenTestUserControl)) {
VisualTree = border
};
}
public static DataTemplate CreateDefaultTemplate() {
return new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(SplashScreenTestUserControl)) };
}
public static DXSplashScreenService CreateDefaultService() {
return new DXSplashScreenService() { ViewTemplate = CreateDefaultTemplate() };
}
public static DXSplashScreenService CreateDefaultSplashScreenAndShow(Window window, FrameworkElement owner = null, SplashScreenOwnerSearchMode ownerSearchMode = SplashScreenOwnerSearchMode.Full
, bool activateWindow = true, FrameworkElement windowContent = null, SplashScreenClosingMode? closingMode = null) {
DXSplashScreenService service = CreateDefaultService();
service.SplashScreenOwner = owner;
if(closingMode.HasValue)
service.SplashScreenClosingMode = closingMode.Value;
service.OwnerSearchMode = ownerSearchMode;
if(windowContent == null)
Interaction.GetBehaviors(window).Add(service);
else {
window.Do(x => x.Content = windowContent);
Interaction.GetBehaviors(windowContent).Add(service);
}
if(window != null) {
window.Show();
if(activateWindow && !window.IsActive)
window.Activate();
DispatcherHelper.UpdateLayoutAndDoEvents(window);
}
service.ShowSplashScreen();
SplashScreenTestUserControl.DoEvents();
return service;
}
}
}
| |
// 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 RegexCode class is internal to the regular expression package.
// It provides operator constants for use by the Builder and the Machine.
// Implementation notes:
//
// Regexps are built into RegexCodes, which contain an operation array,
// a string table, and some constants.
//
// Each operation is one of the codes below, followed by the integer
// operands specified for each op.
//
// Strings and sets are indices into a string table.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace System.Text.RegularExpressions
{
internal sealed class RegexCode
{
// The following primitive operations come directly from the parser
// lef/back operands description
internal const int Onerep = 0; // lef,back char,min,max a {n}
internal const int Notonerep = 1; // lef,back char,min,max .{n}
internal const int Setrep = 2; // lef,back set,min,max [\d]{n}
internal const int Oneloop = 3; // lef,back char,min,max a {,n}
internal const int Notoneloop = 4; // lef,back char,min,max .{,n}
internal const int Setloop = 5; // lef,back set,min,max [\d]{,n}
internal const int Onelazy = 6; // lef,back char,min,max a {,n}?
internal const int Notonelazy = 7; // lef,back char,min,max .{,n}?
internal const int Setlazy = 8; // lef,back set,min,max [\d]{,n}?
internal const int One = 9; // lef char a
internal const int Notone = 10; // lef char [^a]
internal const int Set = 11; // lef set [a-z\s] \w \s \d
internal const int Multi = 12; // lef string abcd
internal const int Ref = 13; // lef group \#
internal const int Bol = 14; // ^
internal const int Eol = 15; // $
internal const int Boundary = 16; // \b
internal const int Nonboundary = 17; // \B
internal const int Beginning = 18; // \A
internal const int Start = 19; // \G
internal const int EndZ = 20; // \Z
internal const int End = 21; // \Z
internal const int Nothing = 22; // Reject!
// Primitive control structures
internal const int Lazybranch = 23; // back jump straight first
internal const int Branchmark = 24; // back jump branch first for loop
internal const int Lazybranchmark = 25; // back jump straight first for loop
internal const int Nullcount = 26; // back val set counter, null mark
internal const int Setcount = 27; // back val set counter, make mark
internal const int Branchcount = 28; // back jump,limit branch++ if zero<=c<limit
internal const int Lazybranchcount = 29; // back jump,limit same, but straight first
internal const int Nullmark = 30; // back save position
internal const int Setmark = 31; // back save position
internal const int Capturemark = 32; // back group define group
internal const int Getmark = 33; // back recall position
internal const int Setjump = 34; // back save backtrack state
internal const int Backjump = 35; // zap back to saved state
internal const int Forejump = 36; // zap backtracking state
internal const int Testref = 37; // backtrack if ref undefined
internal const int Goto = 38; // jump just go
internal const int Prune = 39; // prune it baby
internal const int Stop = 40; // done!
internal const int ECMABoundary = 41; // \b
internal const int NonECMABoundary = 42; // \B
// Modifiers for alternate modes
internal const int Mask = 63; // Mask to get unmodified ordinary operator
internal const int Rtl = 64; // bit to indicate that we're reverse scanning.
internal const int Back = 128; // bit to indicate that we're backtracking.
internal const int Back2 = 256; // bit to indicate that we're backtracking on a second branch.
internal const int Ci = 512; // bit to indicate that we're case-insensitive.
internal readonly int[] _codes; // the code
internal readonly String[] _strings; // the string/set table
internal readonly int _trackcount; // how many instructions use backtracking
internal readonly Dictionary<Int32, Int32> _caps; // mapping of user group numbers -> impl group slots
internal readonly int _capsize; // number of impl group slots
internal readonly RegexPrefix _fcPrefix; // the set of candidate first characters (may be null)
internal readonly RegexBoyerMoore _bmPrefix; // the fixed prefix string as a Boyer-Moore machine (may be null)
internal readonly int _anchors; // the set of zero-length start anchors (RegexFCD.Bol, etc)
internal readonly bool _rightToLeft; // true if right to left
internal RegexCode(int[] codes, List<String> stringlist, int trackcount,
Dictionary<Int32, Int32> caps, int capsize,
RegexBoyerMoore bmPrefix, RegexPrefix fcPrefix,
int anchors, bool rightToLeft)
{
Debug.Assert(codes != null, "codes cannot be null.");
Debug.Assert(stringlist != null, "stringlist cannot be null.");
_codes = codes;
_strings = stringlist.ToArray();
_trackcount = trackcount;
_caps = caps;
_capsize = capsize;
_bmPrefix = bmPrefix;
_fcPrefix = fcPrefix;
_anchors = anchors;
_rightToLeft = rightToLeft;
}
internal static bool OpcodeBacktracks(int Op)
{
Op &= Mask;
switch (Op)
{
case Oneloop:
case Notoneloop:
case Setloop:
case Onelazy:
case Notonelazy:
case Setlazy:
case Lazybranch:
case Branchmark:
case Lazybranchmark:
case Nullcount:
case Setcount:
case Branchcount:
case Lazybranchcount:
case Setmark:
case Capturemark:
case Getmark:
case Setjump:
case Backjump:
case Forejump:
case Goto:
return true;
default:
return false;
}
}
#if DEBUG
internal static int OpcodeSize(int opcode)
{
opcode &= Mask;
switch (opcode)
{
case Nothing:
case Bol:
case Eol:
case Boundary:
case Nonboundary:
case ECMABoundary:
case NonECMABoundary:
case Beginning:
case Start:
case EndZ:
case End:
case Nullmark:
case Setmark:
case Getmark:
case Setjump:
case Backjump:
case Forejump:
case Stop:
return 1;
case One:
case Notone:
case Multi:
case Ref:
case Testref:
case Goto:
case Nullcount:
case Setcount:
case Lazybranch:
case Branchmark:
case Lazybranchmark:
case Prune:
case Set:
return 2;
case Capturemark:
case Branchcount:
case Lazybranchcount:
case Onerep:
case Notonerep:
case Oneloop:
case Notoneloop:
case Onelazy:
case Notonelazy:
case Setlazy:
case Setrep:
case Setloop:
return 3;
default:
throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, opcode.ToString(CultureInfo.CurrentCulture)));
}
}
private static readonly String[] CodeStr = new String[]
{
"Onerep", "Notonerep", "Setrep",
"Oneloop", "Notoneloop", "Setloop",
"Onelazy", "Notonelazy", "Setlazy",
"One", "Notone", "Set",
"Multi", "Ref",
"Bol", "Eol", "Boundary", "Nonboundary", "Beginning", "Start", "EndZ", "End",
"Nothing",
"Lazybranch", "Branchmark", "Lazybranchmark",
"Nullcount", "Setcount", "Branchcount", "Lazybranchcount",
"Nullmark", "Setmark", "Capturemark", "Getmark",
"Setjump", "Backjump", "Forejump", "Testref", "Goto",
"Prune", "Stop",
#if ECMA
"ECMABoundary", "NonECMABoundary",
#endif
};
internal static String OperatorDescription(int Opcode)
{
bool isCi = ((Opcode & Ci) != 0);
bool isRtl = ((Opcode & Rtl) != 0);
bool isBack = ((Opcode & Back) != 0);
bool isBack2 = ((Opcode & Back2) != 0);
return CodeStr[Opcode & Mask] +
(isCi ? "-Ci" : "") + (isRtl ? "-Rtl" : "") + (isBack ? "-Back" : "") + (isBack2 ? "-Back2" : "");
}
internal String OpcodeDescription(int offset)
{
StringBuilder sb = new StringBuilder();
int opcode = _codes[offset];
sb.AppendFormat("{0:D6} ", offset);
sb.Append(OpcodeBacktracks(opcode & Mask) ? '*' : ' ');
sb.Append(OperatorDescription(opcode));
sb.Append('(');
opcode &= Mask;
switch (opcode)
{
case One:
case Notone:
case Onerep:
case Notonerep:
case Oneloop:
case Notoneloop:
case Onelazy:
case Notonelazy:
sb.Append("Ch = ");
sb.Append(RegexCharClass.CharDescription((char)_codes[offset + 1]));
break;
case Set:
case Setrep:
case Setloop:
case Setlazy:
sb.Append("Set = ");
sb.Append(RegexCharClass.SetDescription(_strings[_codes[offset + 1]]));
break;
case Multi:
sb.Append("String = ");
sb.Append(_strings[_codes[offset + 1]]);
break;
case Ref:
case Testref:
sb.Append("Index = ");
sb.Append(_codes[offset + 1]);
break;
case Capturemark:
sb.Append("Index = ");
sb.Append(_codes[offset + 1]);
if (_codes[offset + 2] != -1)
{
sb.Append(", Unindex = ");
sb.Append(_codes[offset + 2]);
}
break;
case Nullcount:
case Setcount:
sb.Append("Value = ");
sb.Append(_codes[offset + 1]);
break;
case Goto:
case Lazybranch:
case Branchmark:
case Lazybranchmark:
case Branchcount:
case Lazybranchcount:
sb.Append("Addr = ");
sb.Append(_codes[offset + 1]);
break;
}
switch (opcode)
{
case Onerep:
case Notonerep:
case Oneloop:
case Notoneloop:
case Onelazy:
case Notonelazy:
case Setrep:
case Setloop:
case Setlazy:
sb.Append(", Rep = ");
if (_codes[offset + 2] == Int32.MaxValue)
sb.Append("inf");
else
sb.Append(_codes[offset + 2]);
break;
case Branchcount:
case Lazybranchcount:
sb.Append(", Limit = ");
if (_codes[offset + 2] == Int32.MaxValue)
sb.Append("inf");
else
sb.Append(_codes[offset + 2]);
break;
}
sb.Append(')');
return sb.ToString();
}
internal void Dump()
{
int i;
Debug.WriteLine("Direction: " + (_rightToLeft ? "right-to-left" : "left-to-right"));
Debug.WriteLine("Firstchars: " + (_fcPrefix == null ? "n/a" : RegexCharClass.SetDescription(_fcPrefix.Prefix)));
Debug.WriteLine("Prefix: " + (_bmPrefix == null ? "n/a" : Regex.Escape(_bmPrefix.ToString())));
Debug.WriteLine("Anchors: " + RegexFCD.AnchorDescription(_anchors));
Debug.WriteLine("");
if (_bmPrefix != null)
{
Debug.WriteLine("BoyerMoore:");
Debug.WriteLine(_bmPrefix.Dump(" "));
}
for (i = 0; i < _codes.Length;)
{
Debug.WriteLine(OpcodeDescription(i));
i += OpcodeSize(_codes[i]);
}
Debug.WriteLine("");
}
#endif
}
}
| |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects.GuiControls
{
public unsafe class GuiListBoxCtrl : GuiControl
{
public GuiListBoxCtrl()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiListBoxCtrlCreateInstance());
}
public GuiListBoxCtrl(uint pId) : base(pId)
{
}
public GuiListBoxCtrl(string pName) : base(pName)
{
}
public GuiListBoxCtrl(IntPtr pObjPtr) : base(pObjPtr)
{
}
public GuiListBoxCtrl(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
{
}
public GuiListBoxCtrl(SimObject pObj) : base(pObj)
{
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _GuiListBoxCtrlGetAllowMultipleSelections(IntPtr ctrl);
private static _GuiListBoxCtrlGetAllowMultipleSelections _GuiListBoxCtrlGetAllowMultipleSelectionsFunc;
internal static bool GuiListBoxCtrlGetAllowMultipleSelections(IntPtr ctrl)
{
if (_GuiListBoxCtrlGetAllowMultipleSelectionsFunc == null)
{
_GuiListBoxCtrlGetAllowMultipleSelectionsFunc =
(_GuiListBoxCtrlGetAllowMultipleSelections)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlGetAllowMultipleSelections"), typeof(_GuiListBoxCtrlGetAllowMultipleSelections));
}
return _GuiListBoxCtrlGetAllowMultipleSelectionsFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlSetAllowMultipleSelections(IntPtr ctrl, bool allow);
private static _GuiListBoxCtrlSetAllowMultipleSelections _GuiListBoxCtrlSetAllowMultipleSelectionsFunc;
internal static void GuiListBoxCtrlSetAllowMultipleSelections(IntPtr ctrl, bool allow)
{
if (_GuiListBoxCtrlSetAllowMultipleSelectionsFunc == null)
{
_GuiListBoxCtrlSetAllowMultipleSelectionsFunc =
(_GuiListBoxCtrlSetAllowMultipleSelections)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlSetAllowMultipleSelections"), typeof(_GuiListBoxCtrlSetAllowMultipleSelections));
}
_GuiListBoxCtrlSetAllowMultipleSelectionsFunc(ctrl, allow);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _GuiListBoxCtrlGetFitParentWidth(IntPtr ctrl);
private static _GuiListBoxCtrlGetFitParentWidth _GuiListBoxCtrlGetFitParentWidthFunc;
internal static bool GuiListBoxCtrlGetFitParentWidth(IntPtr ctrl)
{
if (_GuiListBoxCtrlGetFitParentWidthFunc == null)
{
_GuiListBoxCtrlGetFitParentWidthFunc =
(_GuiListBoxCtrlGetFitParentWidth)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlGetFitParentWidth"), typeof(_GuiListBoxCtrlGetFitParentWidth));
}
return _GuiListBoxCtrlGetFitParentWidthFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlSetFitParentWidth(IntPtr ctrl, bool fit);
private static _GuiListBoxCtrlSetFitParentWidth _GuiListBoxCtrlSetFitParentWidthFunc;
internal static void GuiListBoxCtrlSetFitParentWidth(IntPtr ctrl, bool fit)
{
if (_GuiListBoxCtrlSetFitParentWidthFunc == null)
{
_GuiListBoxCtrlSetFitParentWidthFunc =
(_GuiListBoxCtrlSetFitParentWidth)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlSetFitParentWidth"), typeof(_GuiListBoxCtrlSetFitParentWidth));
}
_GuiListBoxCtrlSetFitParentWidthFunc(ctrl, fit);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _GuiListBoxCtrlCreateInstance();
private static _GuiListBoxCtrlCreateInstance _GuiListBoxCtrlCreateInstanceFunc;
internal static IntPtr GuiListBoxCtrlCreateInstance()
{
if (_GuiListBoxCtrlCreateInstanceFunc == null)
{
_GuiListBoxCtrlCreateInstanceFunc =
(_GuiListBoxCtrlCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlCreateInstance"), typeof(_GuiListBoxCtrlCreateInstance));
}
return _GuiListBoxCtrlCreateInstanceFunc();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlSetMultipleSelection(IntPtr ctrl, bool enable);
private static _GuiListBoxCtrlSetMultipleSelection _GuiListBoxCtrlSetMultipleSelectionFunc;
internal static void GuiListBoxCtrlSetMultipleSelection(IntPtr ctrl, bool enable)
{
if (_GuiListBoxCtrlSetMultipleSelectionFunc == null)
{
_GuiListBoxCtrlSetMultipleSelectionFunc =
(_GuiListBoxCtrlSetMultipleSelection)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlSetMultipleSelection"), typeof(_GuiListBoxCtrlSetMultipleSelection));
}
_GuiListBoxCtrlSetMultipleSelectionFunc(ctrl, enable);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlClearItems(IntPtr ctrl);
private static _GuiListBoxCtrlClearItems _GuiListBoxCtrlClearItemsFunc;
internal static void GuiListBoxCtrlClearItems(IntPtr ctrl)
{
if (_GuiListBoxCtrlClearItemsFunc == null)
{
_GuiListBoxCtrlClearItemsFunc =
(_GuiListBoxCtrlClearItems)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlClearItems"), typeof(_GuiListBoxCtrlClearItems));
}
_GuiListBoxCtrlClearItemsFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlClearSelection(IntPtr ctrl);
private static _GuiListBoxCtrlClearSelection _GuiListBoxCtrlClearSelectionFunc;
internal static void GuiListBoxCtrlClearSelection(IntPtr ctrl)
{
if (_GuiListBoxCtrlClearSelectionFunc == null)
{
_GuiListBoxCtrlClearSelectionFunc =
(_GuiListBoxCtrlClearSelection)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlClearSelection"), typeof(_GuiListBoxCtrlClearSelection));
}
_GuiListBoxCtrlClearSelectionFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlSetSelected(IntPtr ctrl, int index, bool setting);
private static _GuiListBoxCtrlSetSelected _GuiListBoxCtrlSetSelectedFunc;
internal static void GuiListBoxCtrlSetSelected(IntPtr ctrl, int index, bool setting)
{
if (_GuiListBoxCtrlSetSelectedFunc == null)
{
_GuiListBoxCtrlSetSelectedFunc =
(_GuiListBoxCtrlSetSelected)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlSetSelected"), typeof(_GuiListBoxCtrlSetSelected));
}
_GuiListBoxCtrlSetSelectedFunc(ctrl, index, setting);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiListBoxCtrlGetItemCount(IntPtr ctrl);
private static _GuiListBoxCtrlGetItemCount _GuiListBoxCtrlGetItemCountFunc;
internal static int GuiListBoxCtrlGetItemCount(IntPtr ctrl)
{
if (_GuiListBoxCtrlGetItemCountFunc == null)
{
_GuiListBoxCtrlGetItemCountFunc =
(_GuiListBoxCtrlGetItemCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlGetItemCount"), typeof(_GuiListBoxCtrlGetItemCount));
}
return _GuiListBoxCtrlGetItemCountFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiListBoxCtrlGetSelCount(IntPtr ctrl);
private static _GuiListBoxCtrlGetSelCount _GuiListBoxCtrlGetSelCountFunc;
internal static int GuiListBoxCtrlGetSelCount(IntPtr ctrl)
{
if (_GuiListBoxCtrlGetSelCountFunc == null)
{
_GuiListBoxCtrlGetSelCountFunc =
(_GuiListBoxCtrlGetSelCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlGetSelCount"), typeof(_GuiListBoxCtrlGetSelCount));
}
return _GuiListBoxCtrlGetSelCountFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiListBoxCtrlGetSelectedItem(IntPtr ctrl);
private static _GuiListBoxCtrlGetSelectedItem _GuiListBoxCtrlGetSelectedItemFunc;
internal static int GuiListBoxCtrlGetSelectedItem(IntPtr ctrl)
{
if (_GuiListBoxCtrlGetSelectedItemFunc == null)
{
_GuiListBoxCtrlGetSelectedItemFunc =
(_GuiListBoxCtrlGetSelectedItem)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlGetSelectedItem"), typeof(_GuiListBoxCtrlGetSelectedItem));
}
return _GuiListBoxCtrlGetSelectedItemFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int[] _GuiListBoxCtrlGetSelectedItems(IntPtr ctrl);
private static _GuiListBoxCtrlGetSelectedItems _GuiListBoxCtrlGetSelectedItemsFunc;
internal static int[] GuiListBoxCtrlGetSelectedItems(IntPtr ctrl)
{
if (_GuiListBoxCtrlGetSelectedItemsFunc == null)
{
_GuiListBoxCtrlGetSelectedItemsFunc =
(_GuiListBoxCtrlGetSelectedItems)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlGetSelectedItems"), typeof(_GuiListBoxCtrlGetSelectedItems));
}
return _GuiListBoxCtrlGetSelectedItemsFunc(ctrl);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int _GuiListBoxCtrlFindItemText(IntPtr ctrl, string itemText, bool caseSensitive);
private static _GuiListBoxCtrlFindItemText _GuiListBoxCtrlFindItemTextFunc;
internal static int GuiListBoxCtrlFindItemText(IntPtr ctrl, string itemText, bool caseSensitive)
{
if (_GuiListBoxCtrlFindItemTextFunc == null)
{
_GuiListBoxCtrlFindItemTextFunc =
(_GuiListBoxCtrlFindItemText)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlFindItemText"), typeof(_GuiListBoxCtrlFindItemText));
}
return _GuiListBoxCtrlFindItemTextFunc(ctrl, itemText, caseSensitive);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlSetCurSel(IntPtr ctrl, int index);
private static _GuiListBoxCtrlSetCurSel _GuiListBoxCtrlSetCurSelFunc;
internal static void GuiListBoxCtrlSetCurSel(IntPtr ctrl, int index)
{
if (_GuiListBoxCtrlSetCurSelFunc == null)
{
_GuiListBoxCtrlSetCurSelFunc =
(_GuiListBoxCtrlSetCurSel)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlSetCurSel"), typeof(_GuiListBoxCtrlSetCurSel));
}
_GuiListBoxCtrlSetCurSelFunc(ctrl, index);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlSetCurSelRange(IntPtr ctrl, int start, int stop);
private static _GuiListBoxCtrlSetCurSelRange _GuiListBoxCtrlSetCurSelRangeFunc;
internal static void GuiListBoxCtrlSetCurSelRange(IntPtr ctrl, int start, int stop)
{
if (_GuiListBoxCtrlSetCurSelRangeFunc == null)
{
_GuiListBoxCtrlSetCurSelRangeFunc =
(_GuiListBoxCtrlSetCurSelRange)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlSetCurSelRange"), typeof(_GuiListBoxCtrlSetCurSelRange));
}
_GuiListBoxCtrlSetCurSelRangeFunc(ctrl, start, stop);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlAddItem(IntPtr ctrl, string text, Color color);
private static _GuiListBoxCtrlAddItem _GuiListBoxCtrlAddItemFunc;
internal static void GuiListBoxCtrlAddItem(IntPtr ctrl, string text, Color color)
{
if (_GuiListBoxCtrlAddItemFunc == null)
{
_GuiListBoxCtrlAddItemFunc =
(_GuiListBoxCtrlAddItem)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlAddItem"), typeof(_GuiListBoxCtrlAddItem));
}
_GuiListBoxCtrlAddItemFunc(ctrl, text, color);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlSetItemColor(IntPtr ctrl, int index, Color color);
private static _GuiListBoxCtrlSetItemColor _GuiListBoxCtrlSetItemColorFunc;
internal static void GuiListBoxCtrlSetItemColor(IntPtr ctrl, int index, Color color)
{
if (_GuiListBoxCtrlSetItemColorFunc == null)
{
_GuiListBoxCtrlSetItemColorFunc =
(_GuiListBoxCtrlSetItemColor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlSetItemColor"), typeof(_GuiListBoxCtrlSetItemColor));
}
_GuiListBoxCtrlSetItemColorFunc(ctrl, index, color);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlClearItemColor(IntPtr ctrl, int index);
private static _GuiListBoxCtrlClearItemColor _GuiListBoxCtrlClearItemColorFunc;
internal static void GuiListBoxCtrlClearItemColor(IntPtr ctrl, int index)
{
if (_GuiListBoxCtrlClearItemColorFunc == null)
{
_GuiListBoxCtrlClearItemColorFunc =
(_GuiListBoxCtrlClearItemColor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlClearItemColor"), typeof(_GuiListBoxCtrlClearItemColor));
}
_GuiListBoxCtrlClearItemColorFunc(ctrl, index);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlInsertItem(IntPtr ctrl, string text, int index);
private static _GuiListBoxCtrlInsertItem _GuiListBoxCtrlInsertItemFunc;
internal static void GuiListBoxCtrlInsertItem(IntPtr ctrl, string text, int index)
{
if (_GuiListBoxCtrlInsertItemFunc == null)
{
_GuiListBoxCtrlInsertItemFunc =
(_GuiListBoxCtrlInsertItem)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlInsertItem"), typeof(_GuiListBoxCtrlInsertItem));
}
_GuiListBoxCtrlInsertItemFunc(ctrl, text, index);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlDeleteItem(IntPtr ctrl, int index);
private static _GuiListBoxCtrlDeleteItem _GuiListBoxCtrlDeleteItemFunc;
internal static void GuiListBoxCtrlDeleteItem(IntPtr ctrl, int index)
{
if (_GuiListBoxCtrlDeleteItemFunc == null)
{
_GuiListBoxCtrlDeleteItemFunc =
(_GuiListBoxCtrlDeleteItem)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlDeleteItem"), typeof(_GuiListBoxCtrlDeleteItem));
}
_GuiListBoxCtrlDeleteItemFunc(ctrl, index);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _GuiListBoxCtrlSetItemtext(IntPtr ctrl, int index, string newText);
private static _GuiListBoxCtrlSetItemtext _GuiListBoxCtrlSetItemtextFunc;
internal static void GuiListBoxCtrlSetItemtext(IntPtr ctrl, int index, string newText)
{
if (_GuiListBoxCtrlSetItemtextFunc == null)
{
_GuiListBoxCtrlSetItemtextFunc =
(_GuiListBoxCtrlSetItemtext)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlSetItemtext"), typeof(_GuiListBoxCtrlSetItemtext));
}
_GuiListBoxCtrlSetItemtextFunc(ctrl, index, newText);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _GuiListBoxCtrlGetItemtext(IntPtr ctrl, int index);
private static _GuiListBoxCtrlGetItemtext _GuiListBoxCtrlGetItemtextFunc;
internal static IntPtr GuiListBoxCtrlGetItemtext(IntPtr ctrl, int index)
{
if (_GuiListBoxCtrlGetItemtextFunc == null)
{
_GuiListBoxCtrlGetItemtextFunc =
(_GuiListBoxCtrlGetItemtext)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"GuiListBoxCtrlGetItemtext"), typeof(_GuiListBoxCtrlGetItemtext));
}
return _GuiListBoxCtrlGetItemtextFunc(ctrl, index);
}
}
#endregion
#region Properties
public bool AllowMultipleSelections
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiListBoxCtrlGetAllowMultipleSelections(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlSetAllowMultipleSelections(ObjectPtr->ObjPtr, value);
}
}
public bool FitParentWidth
{
get
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiListBoxCtrlGetFitParentWidth(ObjectPtr->ObjPtr);
}
set
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlSetFitParentWidth(ObjectPtr->ObjPtr, value);
}
}
#endregion
#region Methods
public void SetMultipleSelection(bool enable)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlSetMultipleSelection(ObjectPtr->ObjPtr, enable);
}
public void ClearItems()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlClearItems(ObjectPtr->ObjPtr);
}
public void ClearSelection()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlClearSelection(ObjectPtr->ObjPtr);
}
public void SetSelected(int index, bool setting)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlSetSelected(ObjectPtr->ObjPtr, index, setting);
}
public int GetItemCount()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiListBoxCtrlGetItemCount(ObjectPtr->ObjPtr);
}
public int GetSelCount()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiListBoxCtrlGetSelCount(ObjectPtr->ObjPtr);
}
public int GetSelectedItem()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiListBoxCtrlGetSelectedItem(ObjectPtr->ObjPtr);
}
public int[] GetSelectedItems()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiListBoxCtrlGetSelectedItems(ObjectPtr->ObjPtr);
}
public int FindItemText(string itemText, bool caseSensitive)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.GuiListBoxCtrlFindItemText(ObjectPtr->ObjPtr, itemText, caseSensitive);
}
public void SetCurSel(int index)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlSetCurSel(ObjectPtr->ObjPtr, index);
}
public void SetCurSelRange(int start, int stop)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlSetCurSelRange(ObjectPtr->ObjPtr, start, stop);
}
public void AddItem(string text, Color color)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlAddItem(ObjectPtr->ObjPtr, text, color);
}
public void SetItemColor(int index, Color color)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlSetItemColor(ObjectPtr->ObjPtr, index, color);
}
public void ClearItemColor(int index)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlClearItemColor(ObjectPtr->ObjPtr, index);
}
public void InsertItem(string text, int index)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlInsertItem(ObjectPtr->ObjPtr, text, index);
}
public void DeleteItem(int index)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlDeleteItem(ObjectPtr->ObjPtr, index);
}
public void SetItemtext(int index, string newText)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.GuiListBoxCtrlSetItemtext(ObjectPtr->ObjPtr, index, newText);
}
public string GetItemtext(int index)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.GuiListBoxCtrlGetItemtext(ObjectPtr->ObjPtr, index));
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Threading;
using System.Xml;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
namespace OpenSim.Region.CoreModules.Avatar.Attachments
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AttachmentsModule")]
public class AttachmentsModule : IAttachmentsModule, INonSharedRegionModule
{
#region INonSharedRegionModule
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public int DebugLevel { get; set; }
/// <summary>
/// Period to sleep per 100 prims in order to avoid CPU spikes when an avatar with many attachments logs in/changes
/// outfit or many avatars with a medium levels of attachments login/change outfit simultaneously.
/// </summary>
/// <remarks>
/// A value of 0 will apply no pause. The pause is specified in milliseconds.
/// </remarks>
public int ThrottlePer100PrimsRezzed { get; set; }
private Scene m_scene;
private IInventoryAccessModule m_invAccessModule;
/// <summary>
/// Are attachments enabled?
/// </summary>
public bool Enabled { get; private set; }
public string Name { get { return "Attachments Module"; } }
public Type ReplaceableInterface { get { return null; } }
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["Attachments"];
if (config != null)
{
Enabled = config.GetBoolean("Enabled", true);
ThrottlePer100PrimsRezzed = config.GetInt("ThrottlePer100PrimsRezzed", 0);
}
else
{
Enabled = true;
}
}
public void AddRegion(Scene scene)
{
m_scene = scene;
if (Enabled)
{
// Only register module with scene if it is enabled. All callers check for a null attachments module.
// Ideally, there should be a null attachments module for when this core attachments module has been
// disabled. Registering only when enabled allows for other attachments module implementations.
m_scene.RegisterModuleInterface<IAttachmentsModule>(this);
m_scene.EventManager.OnNewClient += SubscribeToClientEvents;
m_scene.EventManager.OnStartScript += (localID, itemID) => HandleScriptStateChange(localID, true);
m_scene.EventManager.OnStopScript += (localID, itemID) => HandleScriptStateChange(localID, false);
MainConsole.Instance.Commands.AddCommand(
"Debug",
false,
"debug attachments log",
"debug attachments log [0|1]",
"Turn on attachments debug logging",
" <= 0 - turns off debug logging\n"
+ " >= 1 - turns on attachment message debug logging",
HandleDebugAttachmentsLog);
MainConsole.Instance.Commands.AddCommand(
"Debug",
false,
"debug attachments throttle",
"debug attachments throttle <ms>",
"Turn on attachments throttling.",
"This requires a millisecond value. " +
" == 0 - disable throttling.\n"
+ " > 0 - sleeps for this number of milliseconds per 100 prims rezzed.",
HandleDebugAttachmentsThrottle);
MainConsole.Instance.Commands.AddCommand(
"Debug",
false,
"debug attachments status",
"debug attachments status",
"Show current attachments debug status",
HandleDebugAttachmentsStatus);
}
// TODO: Should probably be subscribing to CloseClient too, but this doesn't yet give us IClientAPI
}
private void HandleDebugAttachmentsLog(string module, string[] args)
{
int debugLevel;
if (!(args.Length == 4 && int.TryParse(args[3], out debugLevel)))
{
MainConsole.Instance.OutputFormat("Usage: debug attachments log [0|1]");
}
else
{
DebugLevel = debugLevel;
MainConsole.Instance.OutputFormat(
"Set attachments debug level to {0} in {1}", DebugLevel, m_scene.Name);
}
}
private void HandleDebugAttachmentsThrottle(string module, string[] args)
{
int ms;
if (args.Length == 4 && int.TryParse(args[3], out ms))
{
ThrottlePer100PrimsRezzed = ms;
MainConsole.Instance.OutputFormat(
"Attachments rez throttle per 100 prims is now {0} in {1}", ThrottlePer100PrimsRezzed, m_scene.Name);
return;
}
MainConsole.Instance.OutputFormat("Usage: debug attachments throttle <ms>");
}
private void HandleDebugAttachmentsStatus(string module, string[] args)
{
MainConsole.Instance.OutputFormat("Settings for {0}", m_scene.Name);
MainConsole.Instance.OutputFormat("Debug logging level: {0}", DebugLevel);
MainConsole.Instance.OutputFormat("Throttle per 100 prims: {0}ms", ThrottlePer100PrimsRezzed);
}
/// <summary>
/// Listen for client triggered running state changes so that we can persist the script's object if necessary.
/// </summary>
/// <param name='localID'></param>
/// <param name='itemID'></param>
private void HandleScriptStateChange(uint localID, bool started)
{
SceneObjectGroup sog = m_scene.GetGroupByPrim(localID);
if (sog != null && sog.IsAttachment)
{
if (!started)
{
// FIXME: This is a convoluted way for working out whether the script state has changed to stop
// because it has been manually stopped or because the stop was called in UpdateDetachedObject() below
// This needs to be handled in a less tangled way.
ScenePresence sp = m_scene.GetScenePresence(sog.AttachedAvatar);
if (sp.ControllingClient.IsActive)
sog.HasGroupChanged = true;
}
else
{
sog.HasGroupChanged = true;
}
}
}
public void RemoveRegion(Scene scene)
{
m_scene.UnregisterModuleInterface<IAttachmentsModule>(this);
if (Enabled)
m_scene.EventManager.OnNewClient -= SubscribeToClientEvents;
}
public void RegionLoaded(Scene scene)
{
m_invAccessModule = m_scene.RequestModuleInterface<IInventoryAccessModule>();
}
public void Close()
{
RemoveRegion(m_scene);
}
#endregion
#region IAttachmentsModule
public void CopyAttachments(IScenePresence sp, AgentData ad)
{
lock (sp.AttachmentsSyncLock)
{
// Attachment objects
List<SceneObjectGroup> attachments = sp.GetAttachments();
if (attachments.Count > 0)
{
ad.AttachmentObjects = new List<ISceneObject>();
ad.AttachmentObjectStates = new List<string>();
// IScriptModule se = m_scene.RequestModuleInterface<IScriptModule>();
sp.InTransitScriptStates.Clear();
foreach (SceneObjectGroup sog in attachments)
{
// We need to make a copy and pass that copy
// because of transfers withn the same sim
ISceneObject clone = sog.CloneForNewScene();
// Attachment module assumes that GroupPosition holds the offsets...!
((SceneObjectGroup)clone).RootPart.GroupPosition = sog.RootPart.AttachedPos;
((SceneObjectGroup)clone).IsAttachment = false;
ad.AttachmentObjects.Add(clone);
string state = sog.GetStateSnapshot();
ad.AttachmentObjectStates.Add(state);
sp.InTransitScriptStates.Add(state);
// Scripts of the originals will be removed when the Agent is successfully removed.
// sog.RemoveScriptInstances(true);
}
}
}
}
public void CopyAttachments(AgentData ad, IScenePresence sp)
{
// m_log.DebugFormat("[ATTACHMENTS MODULE]: Copying attachment data into {0} in {1}", sp.Name, m_scene.Name);
if (ad.AttachmentObjects != null && ad.AttachmentObjects.Count > 0)
{
lock (sp.AttachmentsSyncLock)
sp.ClearAttachments();
int i = 0;
foreach (ISceneObject so in ad.AttachmentObjects)
{
((SceneObjectGroup)so).LocalId = 0;
((SceneObjectGroup)so).RootPart.ClearUpdateSchedule();
// m_log.DebugFormat(
// "[ATTACHMENTS MODULE]: Copying script state with {0} bytes for object {1} for {2} in {3}",
// ad.AttachmentObjectStates[i].Length, so.Name, sp.Name, m_scene.Name);
so.SetState(ad.AttachmentObjectStates[i++], m_scene);
m_scene.IncomingCreateObject(Vector3.Zero, so);
}
}
}
public void RezAttachments(IScenePresence sp)
{
if (!Enabled)
return;
if (null == sp.Appearance)
{
m_log.WarnFormat("[ATTACHMENTS MODULE]: Appearance has not been initialized for agent {0}", sp.UUID);
return;
}
if (sp.GetAttachments().Count > 0)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Not doing simulator-side attachment rez for {0} in {1} as their viewer has already rezzed attachments",
m_scene.Name, sp.Name);
return;
}
if (DebugLevel > 0)
m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing any attachments for {0} from simulator-side", sp.Name);
List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
foreach (AvatarAttachment attach in attachments)
{
uint attachmentPt = (uint)attach.AttachPoint;
// m_log.DebugFormat(
// "[ATTACHMENTS MODULE]: Doing initial rez of attachment with itemID {0}, assetID {1}, point {2} for {3} in {4}",
// attach.ItemID, attach.AssetID, p, sp.Name, m_scene.RegionInfo.RegionName);
// For some reason assetIDs are being written as Zero's in the DB -- need to track tat down
// But they're not used anyway, the item is being looked up for now, so let's proceed.
//if (UUID.Zero == assetID)
//{
// m_log.DebugFormat("[ATTACHMENT]: Cannot rez attachment in point {0} with itemID {1}", p, itemID);
// continue;
//}
try
{
// If we're an NPC then skip all the item checks and manipulations since we don't have an
// inventory right now.
RezSingleAttachmentFromInventoryInternal(
sp, sp.PresenceType == PresenceType.Npc ? UUID.Zero : attach.ItemID, attach.AssetID, attachmentPt, true);
}
catch (Exception e)
{
UUID agentId = (sp.ControllingClient == null) ? default(UUID) : sp.ControllingClient.AgentId;
m_log.ErrorFormat("[ATTACHMENTS MODULE]: Unable to rez attachment with itemID {0}, assetID {1}, point {2} for {3}: {4}\n{5}",
attach.ItemID, attach.AssetID, attachmentPt, agentId, e.Message, e.StackTrace);
}
}
}
public void DeRezAttachments(IScenePresence sp)
{
if (!Enabled)
return;
List<SceneObjectGroup> attachments = sp.GetAttachments();
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Saving for {0} attachments for {1} in {2}",
attachments.Count, sp.Name, m_scene.Name);
if (attachments.Count <= 0)
return;
Dictionary<SceneObjectGroup, string> scriptStates = new Dictionary<SceneObjectGroup, string>();
foreach (SceneObjectGroup so in attachments)
{
// Scripts MUST be snapshotted before the object is
// removed from the scene because doing otherwise will
// clobber the run flag
// This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from
// scripts performing attachment operations at the same time. Getting object states stops the scripts.
scriptStates[so] = PrepareScriptInstanceForSave(so, false);
// m_log.DebugFormat(
// "[ATTACHMENTS MODULE]: For object {0} for {1} in {2} got saved state {3}",
// so.Name, sp.Name, m_scene.Name, scriptStates[so]);
}
lock (sp.AttachmentsSyncLock)
{
foreach (SceneObjectGroup so in attachments)
UpdateDetachedObject(sp, so, scriptStates[so]);
sp.ClearAttachments();
}
}
public void DeleteAttachmentsFromScene(IScenePresence sp, bool silent)
{
if (!Enabled)
return;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Deleting attachments from scene {0} for {1}, silent = {2}",
m_scene.RegionInfo.RegionName, sp.Name, silent);
foreach (SceneObjectGroup sop in sp.GetAttachments())
{
sop.Scene.DeleteSceneObject(sop, silent);
}
sp.ClearAttachments();
}
public bool AttachObject(
IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool append)
{
if (!Enabled)
return false;
group.DetachFromBackup();
bool success = AttachObjectInternal(sp, group, attachmentPt, silent, addToInventory, false, append);
if (!success)
group.AttachToBackup();
return success;
}
/// <summary>
/// Internal method which actually does all the work for attaching an object.
/// </summary>
/// <returns>The object attached.</returns>
/// <param name='sp'></param>
/// <param name='group'>The object to attach.</param>
/// <param name='attachmentPt'></param>
/// <param name='silent'></param>
/// <param name='addToInventory'>If true then add object to user inventory.</param>
/// <param name='resumeScripts'>If true then scripts are resumed on the attached object.</param>
/// <param name='append'>Append to attachment point rather than replace.</param>
private bool AttachObjectInternal(
IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool resumeScripts, bool append)
{
if (group.GetSittingAvatarsCount() != 0)
{
if (DebugLevel > 0)
m_log.WarnFormat(
"[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since {4} avatars are still sitting on it",
group.Name, group.LocalId, sp.Name, attachmentPt, group.GetSittingAvatarsCount());
return false;
}
Vector3 attachPos = group.AbsolutePosition;
// If the attachment point isn't the same as the one previously used
// set it's offset position = 0 so that it appears on the attachment point
// and not in a weird location somewhere unknown.
if (attachmentPt != (uint)AttachmentPoint.Default && attachmentPt != group.AttachmentPoint)
{
attachPos = Vector3.Zero;
}
// if the attachment point is the same as previous, make sure we get the saved
// position info.
if (attachmentPt != 0 && attachmentPt == group.RootPart.Shape.LastAttachPoint)
{
attachPos = group.RootPart.AttachedPos;
}
// AttachmentPt 0 means the client chose to 'wear' the attachment.
if (attachmentPt == (uint)AttachmentPoint.Default)
{
// Check object for stored attachment point
attachmentPt = group.AttachmentPoint;
}
// if we didn't find an attach point, look for where it was last attached
if (attachmentPt == 0)
{
attachmentPt = (uint)group.RootPart.Shape.LastAttachPoint;
attachPos = group.RootPart.AttachedPos;
group.HasGroupChanged = true;
}
// if we still didn't find a suitable attachment point.......
if (attachmentPt == 0)
{
// Stick it on left hand with Zero Offset from the attachment point.
attachmentPt = (uint)AttachmentPoint.LeftHand;
attachPos = Vector3.Zero;
}
group.AttachmentPoint = attachmentPt;
group.AbsolutePosition = attachPos;
List<SceneObjectGroup> attachments = sp.GetAttachments(attachmentPt);
if (attachments.Contains(group))
{
if (DebugLevel > 0)
m_log.WarnFormat(
"[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached",
group.Name, group.LocalId, sp.Name, attachmentPt);
return false;
}
// If we already have 5, remove the oldest until only 4 are left. Skip over temp ones
while (attachments.Count >= 5)
{
if (attachments[0].FromItemID != UUID.Zero)
DetachSingleAttachmentToInv(sp, attachments[0]);
attachments.RemoveAt(0);
}
// If we're not appending, remove the rest as well
if (attachments.Count != 0 && !append)
{
foreach (SceneObjectGroup g in attachments)
{
if (g.FromItemID != UUID.Zero)
DetachSingleAttachmentToInv(sp, g);
}
}
lock (sp.AttachmentsSyncLock)
{
if (addToInventory && sp.PresenceType != PresenceType.Npc)
UpdateUserInventoryWithAttachment(sp, group, attachmentPt, append);
AttachToAgent(sp, group, attachmentPt, attachPos, silent);
if (resumeScripts)
{
// Fire after attach, so we don't get messy perms dialogs
// 4 == AttachedRez
group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4);
group.ResumeScripts();
}
// Do this last so that event listeners have access to all the effects of the attachment
m_scene.EventManager.TriggerOnAttach(group.LocalId, group.FromItemID, sp.UUID);
}
return true;
}
private void UpdateUserInventoryWithAttachment(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool append)
{
// Add the new attachment to inventory if we don't already have it.
UUID newAttachmentItemID = group.FromItemID;
if (newAttachmentItemID == UUID.Zero)
newAttachmentItemID = AddSceneObjectAsNewAttachmentInInv(sp, group).ID;
ShowAttachInUserInventory(sp, attachmentPt, newAttachmentItemID, group, append);
}
public SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt)
{
if (!Enabled)
return null;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: RezSingleAttachmentFromInventory to point {0} from item {1} for {2} in {3}",
(AttachmentPoint)AttachmentPt, itemID, sp.Name, m_scene.Name);
// We check the attachments in the avatar appearance here rather than the objects attached to the
// ScenePresence itself so that we can ignore calls by viewer 2/3 to attach objects on startup. We are
// already doing this in ScenePresence.MakeRootAgent(). Simulator-side attaching needs to be done
// because pre-outfit folder viewers (most version 1 viewers) require it.
bool alreadyOn = false;
List<AvatarAttachment> existingAttachments = sp.Appearance.GetAttachments();
foreach (AvatarAttachment existingAttachment in existingAttachments)
{
if (existingAttachment.ItemID == itemID)
{
alreadyOn = true;
break;
}
}
if (alreadyOn)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Ignoring request by {0} to wear item {1} at {2} since it is already worn",
sp.Name, itemID, AttachmentPt);
return null;
}
bool append = (AttachmentPt & 0x80) != 0;
AttachmentPt &= 0x7f;
return RezSingleAttachmentFromInventoryInternal(sp, itemID, UUID.Zero, AttachmentPt, append);
}
public void RezMultipleAttachmentsFromInventory(IScenePresence sp, List<KeyValuePair<UUID, uint>> rezlist)
{
if (!Enabled)
return;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Rezzing {0} attachments from inventory for {1} in {2}",
rezlist.Count, sp.Name, m_scene.Name);
foreach (KeyValuePair<UUID, uint> rez in rezlist)
{
RezSingleAttachmentFromInventory(sp, rez.Key, rez.Value);
}
}
public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId)
{
DetachSingleAttachmentToGround(sp, soLocalId, sp.AbsolutePosition, Quaternion.Identity);
}
public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId, Vector3 absolutePos, Quaternion absoluteRot)
{
if (!Enabled)
return;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: DetachSingleAttachmentToGround() for {0}, object {1}",
sp.UUID, soLocalId);
SceneObjectGroup so = m_scene.GetGroupByPrim(soLocalId);
if (so == null)
return;
if (so.AttachedAvatar != sp.UUID)
return;
UUID inventoryID = so.FromItemID;
// As per Linden spec, drop is disabled for temp attachs
if (inventoryID == UUID.Zero)
return;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: In DetachSingleAttachmentToGround(), object is {0} {1}, associated item is {2}",
so.Name, so.LocalId, inventoryID);
lock (sp.AttachmentsSyncLock)
{
if (!m_scene.Permissions.CanRezObject(
so.PrimCount, sp.UUID, sp.AbsolutePosition))
return;
bool changed = false;
if (inventoryID != UUID.Zero)
changed = sp.Appearance.DetachAttachment(inventoryID);
if (changed && m_scene.AvatarFactory != null)
m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
sp.RemoveAttachment(so);
so.FromItemID = UUID.Zero;
SceneObjectPart rootPart = so.RootPart;
so.AbsolutePosition = absolutePos;
if (absoluteRot != Quaternion.Identity)
{
so.UpdateGroupRotationR(absoluteRot);
}
so.AttachedAvatar = UUID.Zero;
rootPart.SetParentLocalId(0);
so.ClearPartAttachmentData();
rootPart.ApplyPhysics(rootPart.GetEffectiveObjectFlags(), rootPart.VolumeDetectActive);
so.HasGroupChanged = true;
so.RootPart.Shape.LastAttachPoint = (byte)so.AttachmentPoint;
rootPart.Rezzed = DateTime.Now;
rootPart.RemFlag(PrimFlags.TemporaryOnRez);
so.AttachToBackup();
m_scene.EventManager.TriggerParcelPrimCountTainted();
rootPart.ScheduleFullUpdate();
rootPart.ClearUndoState();
List<UUID> uuids = new List<UUID>();
uuids.Add(inventoryID);
m_scene.InventoryService.DeleteItems(sp.UUID, uuids);
sp.ControllingClient.SendRemoveInventoryItem(inventoryID);
}
m_scene.EventManager.TriggerOnAttach(so.LocalId, so.UUID, UUID.Zero);
}
public void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup so)
{
if (so.AttachedAvatar != sp.UUID)
{
m_log.WarnFormat(
"[ATTACHMENTS MODULE]: Tried to detach object {0} from {1} {2} but attached avatar id was {3} in {4}",
so.Name, sp.Name, sp.UUID, so.AttachedAvatar, m_scene.RegionInfo.RegionName);
return;
}
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Detaching object {0} {1} (FromItemID {2}) for {3} in {4}",
so.Name, so.LocalId, so.FromItemID, sp.Name, m_scene.Name);
// Scripts MUST be snapshotted before the object is
// removed from the scene because doing otherwise will
// clobber the run flag
// This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from
// scripts performing attachment operations at the same time. Getting object states stops the scripts.
string scriptedState = PrepareScriptInstanceForSave(so, true);
lock (sp.AttachmentsSyncLock)
{
// Save avatar attachment information
// m_log.Debug("[ATTACHMENTS MODULE]: Detaching from UserID: " + sp.UUID + ", ItemID: " + itemID);
bool changed = sp.Appearance.DetachAttachment(so.FromItemID);
if (changed && m_scene.AvatarFactory != null)
m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
sp.RemoveAttachment(so);
UpdateDetachedObject(sp, so, scriptedState);
}
}
public void UpdateAttachmentPosition(SceneObjectGroup sog, Vector3 pos)
{
if (!Enabled)
return;
sog.UpdateGroupPosition(pos);
sog.HasGroupChanged = true;
}
#endregion
#region AttachmentModule private methods
// This is public but is not part of the IAttachmentsModule interface.
// RegionCombiner module needs to poke at it to deliver client events.
// This breaks the encapsulation of the module and should get fixed somehow.
public void SubscribeToClientEvents(IClientAPI client)
{
client.OnRezSingleAttachmentFromInv += Client_OnRezSingleAttachmentFromInv;
client.OnRezMultipleAttachmentsFromInv += Client_OnRezMultipleAttachmentsFromInv;
client.OnObjectAttach += Client_OnObjectAttach;
client.OnObjectDetach += Client_OnObjectDetach;
client.OnDetachAttachmentIntoInv += Client_OnDetachAttachmentIntoInv;
client.OnObjectDrop += Client_OnObjectDrop;
}
// This is public but is not part of the IAttachmentsModule interface.
// RegionCombiner module needs to poke at it to deliver client events.
// This breaks the encapsulation of the module and should get fixed somehow.
public void UnsubscribeFromClientEvents(IClientAPI client)
{
client.OnRezSingleAttachmentFromInv -= Client_OnRezSingleAttachmentFromInv;
client.OnRezMultipleAttachmentsFromInv -= Client_OnRezMultipleAttachmentsFromInv;
client.OnObjectAttach -= Client_OnObjectAttach;
client.OnObjectDetach -= Client_OnObjectDetach;
client.OnDetachAttachmentIntoInv -= Client_OnDetachAttachmentIntoInv;
client.OnObjectDrop -= Client_OnObjectDrop;
}
/// <summary>
/// Update the attachment asset for the new sog details if they have changed.
/// </summary>
/// <remarks>
/// This is essential for preserving attachment attributes such as permission. Unlike normal scene objects,
/// these details are not stored on the region.
/// </remarks>
/// <param name="sp"></param>
/// <param name="grp"></param>
/// <param name="saveAllScripted"></param>
private void UpdateKnownItem(IScenePresence sp, SceneObjectGroup grp, string scriptedState)
{
if (grp.FromItemID == UUID.Zero)
{
// We can't save temp attachments
grp.HasGroupChanged = false;
return;
}
// Saving attachments for NPCs messes them up for the real owner!
INPCModule module = m_scene.RequestModuleInterface<INPCModule>();
if (module != null)
{
if (module.IsNPC(sp.UUID, m_scene))
return;
}
if (grp.HasGroupChanged)
{
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}",
grp.UUID, grp.AttachmentPoint);
string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp, scriptedState);
InventoryItemBase item = new InventoryItemBase(grp.FromItemID, sp.UUID);
item = m_scene.InventoryService.GetItem(item);
if (item != null)
{
AssetBase asset = m_scene.CreateAsset(
grp.GetPartName(grp.LocalId),
grp.GetPartDescription(grp.LocalId),
(sbyte)AssetType.Object,
Utils.StringToBytes(sceneObjectXml),
sp.UUID);
if (m_invAccessModule != null)
m_invAccessModule.UpdateInventoryItemAsset(sp.UUID, item, asset);
// If the name of the object has been changed whilst attached then we want to update the inventory
// item in the viewer.
if (sp.ControllingClient != null)
sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
}
grp.HasGroupChanged = false; // Prevent it being saved over and over
}
else if (DebugLevel > 0)
{
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Don't need to update asset for unchanged attachment {0}, attachpoint {1}",
grp.UUID, grp.AttachmentPoint);
}
}
/// <summary>
/// Attach this scene object to the given avatar.
/// </summary>
/// <remarks>
/// This isn't publicly available since attachments should always perform the corresponding inventory
/// operation (to show the attach in user inventory and update the asset with positional information).
/// </remarks>
/// <param name="sp"></param>
/// <param name="so"></param>
/// <param name="attachmentpoint"></param>
/// <param name="attachOffset"></param>
/// <param name="silent"></param>
private void AttachToAgent(
IScenePresence sp, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Adding attachment {0} to avatar {1} at pt {2} pos {3} {4} in {5}",
so.Name, sp.Name, attachmentpoint, attachOffset, so.RootPart.AttachedPos, m_scene.Name);
// Remove from database and parcel prim count
m_scene.DeleteFromStorage(so.UUID);
m_scene.EventManager.TriggerParcelPrimCountTainted();
so.AttachedAvatar = sp.UUID;
if (so.RootPart.PhysActor != null)
so.RootPart.RemoveFromPhysics();
so.AbsolutePosition = attachOffset;
so.RootPart.AttachedPos = attachOffset;
so.IsAttachment = true;
so.RootPart.SetParentLocalId(sp.LocalId);
so.AttachmentPoint = attachmentpoint;
sp.AddAttachment(so);
if (!silent)
{
if (so.HasPrivateAttachmentPoint)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Killing private HUD {0} for avatars other than {1} at attachment point {2}",
so.Name, sp.Name, so.AttachmentPoint);
// As this scene object can now only be seen by the attaching avatar, tell everybody else in the
// scene that it's no longer in their awareness.
m_scene.ForEachClient(
client =>
{ if (client.AgentId != so.AttachedAvatar)
client.SendKillObject(new List<uint>() { so.LocalId });
});
}
// Fudge below is an extremely unhelpful comment. It's probably here so that the scheduled full update
// will succeed, as that will not update if an attachment is selected.
so.IsSelected = false; // fudge....
so.ScheduleGroupForFullUpdate();
}
// In case it is later dropped again, don't let
// it get cleaned up
so.RootPart.RemFlag(PrimFlags.TemporaryOnRez);
}
/// <summary>
/// Add a scene object as a new attachment in the user inventory.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="grp"></param>
/// <returns>The user inventory item created that holds the attachment.</returns>
private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp)
{
if (m_invAccessModule == null)
return null;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}",
grp.Name, grp.LocalId, sp.Name);
InventoryItemBase newItem
= m_invAccessModule.CopyToInventory(
DeRezAction.TakeCopy,
m_scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object).ID,
new List<SceneObjectGroup> { grp },
sp.ControllingClient, true)[0];
// sets itemID so client can show item as 'attached' in inventory
grp.FromItemID = newItem.ID;
return newItem;
}
/// <summary>
/// Prepares the script instance for save.
/// </summary>
/// <remarks>
/// This involves triggering the detach event and getting the script state (which also stops the script)
/// This MUST be done outside sp.AttachmentsSyncLock, since otherwise there is a chance of deadlock if a
/// running script is performing attachment operations.
/// </remarks>
/// <returns>
/// The script state ready for persistence.
/// </returns>
/// <param name='grp'>
/// </param>
/// <param name='fireDetachEvent'>
/// If true, then fire the script event before we save its state.
/// </param>
private string PrepareScriptInstanceForSave(SceneObjectGroup grp, bool fireDetachEvent)
{
if (fireDetachEvent)
m_scene.EventManager.TriggerOnAttach(grp.LocalId, grp.FromItemID, UUID.Zero);
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
grp.SaveScriptedState(writer);
}
return sw.ToString();
}
}
private void UpdateDetachedObject(IScenePresence sp, SceneObjectGroup so, string scriptedState)
{
// Don't save attachments for HG visitors, it
// messes up their inventory. When a HG visitor logs
// out on a foreign grid, their attachments will be
// reloaded in the state they were in when they left
// the home grid. This is best anyway as the visited
// grid may use an incompatible script engine.
bool saveChanged
= sp.PresenceType != PresenceType.Npc
&& (m_scene.UserManagementModule == null
|| m_scene.UserManagementModule.IsLocalGridUser(sp.UUID));
// Remove the object from the scene so no more updates
// are sent. Doing this before the below changes will ensure
// updates can't cause "HUD artefacts"
m_scene.DeleteSceneObject(so, false, false);
// Prepare sog for storage
so.AttachedAvatar = UUID.Zero;
so.RootPart.SetParentLocalId(0);
so.IsAttachment = false;
if (saveChanged)
{
// We cannot use AbsolutePosition here because that would
// attempt to cross the prim as it is detached
so.ForEachPart(x => { x.GroupPosition = so.RootPart.AttachedPos; });
UpdateKnownItem(sp, so, scriptedState);
}
// Now, remove the scripts
so.RemoveScriptInstances(true);
}
protected SceneObjectGroup RezSingleAttachmentFromInventoryInternal(
IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt, bool append)
{
if (m_invAccessModule == null)
return null;
SceneObjectGroup objatt;
if (itemID != UUID.Zero)
objatt = m_invAccessModule.RezObject(sp.ControllingClient,
itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
false, false, sp.UUID, true);
else
objatt = m_invAccessModule.RezObject(sp.ControllingClient,
null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
false, false, sp.UUID, true);
if (objatt == null)
{
m_log.WarnFormat(
"[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}",
itemID, sp.Name, attachmentPt);
return null;
}
else if (itemID == UUID.Zero)
{
// We need to have a FromItemID for multiple attachments on a single attach point to appear. This is
// true on Singularity 1.8.5 and quite possibly other viewers as well. As NPCs don't have an inventory
// we will satisfy this requirement by inserting a random UUID.
objatt.FromItemID = UUID.Random();
}
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Rezzed single object {0} with {1} prims for attachment to {2} on point {3} in {4}",
objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name);
// HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller.
objatt.HasGroupChanged = false;
bool tainted = false;
if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint)
tainted = true;
// FIXME: Detect whether it's really likely for AttachObject to throw an exception in the normal
// course of events. If not, then it's probably not worth trying to recover the situation
// since this is more likely to trigger further exceptions and confuse later debugging. If
// exceptions can be thrown in expected error conditions (not NREs) then make this consistent
// since other normal error conditions will simply return false instead.
// This will throw if the attachment fails
try
{
AttachObjectInternal(sp, objatt, attachmentPt, false, true, true, append);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}",
objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace);
// Make sure the object doesn't stick around and bail
sp.RemoveAttachment(objatt);
m_scene.DeleteSceneObject(objatt, false);
return null;
}
if (tainted)
objatt.HasGroupChanged = true;
if (ThrottlePer100PrimsRezzed > 0)
{
int throttleMs = (int)Math.Round((float)objatt.PrimCount / 100 * ThrottlePer100PrimsRezzed);
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Throttling by {0}ms after rez of {1} with {2} prims for attachment to {3} on point {4} in {5}",
throttleMs, objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name);
Thread.Sleep(throttleMs);
}
return objatt;
}
/// <summary>
/// Update the user inventory to reflect an attachment
/// </summary>
/// <param name="sp"></param>
/// <param name="AttachmentPt"></param>
/// <param name="itemID"></param>
/// <param name="att"></param>
private void ShowAttachInUserInventory(IScenePresence sp, uint AttachmentPt, UUID itemID, SceneObjectGroup att, bool append)
{
// m_log.DebugFormat(
// "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}",
// att.Name, sp.Name, AttachmentPt, itemID);
if (UUID.Zero == itemID)
{
m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID.");
return;
}
if (0 == AttachmentPt)
{
m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error attachment point.");
return;
}
InventoryItemBase item = new InventoryItemBase(itemID, sp.UUID);
item = m_scene.InventoryService.GetItem(item);
if (item == null)
return;
int attFlag = append ? 0x80 : 0;
bool changed = sp.Appearance.SetAttachment((int)AttachmentPt | attFlag, itemID, item.AssetID);
if (changed && m_scene.AvatarFactory != null)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Queueing appearance save for {0}, attachment {1} point {2} in ShowAttachInUserInventory()",
sp.Name, att.Name, AttachmentPt);
m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
}
}
#endregion
#region Client Event Handlers
private ISceneEntity Client_OnRezSingleAttachmentFromInv(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
{
if (!Enabled)
return null;
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Rezzing attachment to point {0} from item {1} for {2}",
(AttachmentPoint)AttachmentPt, itemID, remoteClient.Name);
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
if (sp == null)
{
m_log.ErrorFormat(
"[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezSingleAttachmentFromInventory()",
remoteClient.Name, remoteClient.AgentId);
return null;
}
return RezSingleAttachmentFromInventory(sp, itemID, AttachmentPt);
}
private void Client_OnRezMultipleAttachmentsFromInv(IClientAPI remoteClient, List<KeyValuePair<UUID, uint>> rezlist)
{
if (!Enabled)
return;
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
if (sp != null)
RezMultipleAttachmentsFromInventory(sp, rezlist);
else
m_log.ErrorFormat(
"[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezMultipleAttachmentsFromInventory()",
remoteClient.Name, remoteClient.AgentId);
}
private void Client_OnObjectAttach(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent)
{
if (DebugLevel > 0)
m_log.DebugFormat(
"[ATTACHMENTS MODULE]: Attaching object local id {0} to {1} point {2} from ground (silent = {3})",
objectLocalID, remoteClient.Name, AttachmentPt, silent);
if (!Enabled)
return;
try
{
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
if (sp == null)
{
m_log.ErrorFormat(
"[ATTACHMENTS MODULE]: Could not find presence for client {0} {1}", remoteClient.Name, remoteClient.AgentId);
return;
}
// If we can't take it, we can't attach it!
SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID);
if (part == null)
return;
if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage(
"You don't have sufficient permissions to attach this object", false);
return;
}
bool append = (AttachmentPt & 0x80) != 0;
AttachmentPt &= 0x7f;
// Calls attach with a Zero position
if (AttachObject(sp, part.ParentGroup, AttachmentPt, false, true, append))
{
if (DebugLevel > 0)
m_log.Debug(
"[ATTACHMENTS MODULE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId
+ ", AttachmentPoint: " + AttachmentPt);
// Save avatar attachment information
m_scene.EventManager.TriggerOnAttach(objectLocalID, part.ParentGroup.FromItemID, remoteClient.AgentId);
}
}
catch (Exception e)
{
m_log.ErrorFormat("[ATTACHMENTS MODULE]: exception upon Attach Object {0}{1}", e.Message, e.StackTrace);
}
}
private void Client_OnObjectDetach(uint objectLocalID, IClientAPI remoteClient)
{
if (!Enabled)
return;
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID);
if (sp != null && group != null && group.FromItemID != UUID.Zero)
DetachSingleAttachmentToInv(sp, group);
}
private void Client_OnDetachAttachmentIntoInv(UUID itemID, IClientAPI remoteClient)
{
if (!Enabled)
return;
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
if (sp != null)
{
List<SceneObjectGroup> attachments = sp.GetAttachments();
foreach (SceneObjectGroup group in attachments)
{
if (group.FromItemID == itemID && group.FromItemID != UUID.Zero)
{
DetachSingleAttachmentToInv(sp, group);
return;
}
}
}
}
private void Client_OnObjectDrop(uint soLocalId, IClientAPI remoteClient)
{
if (!Enabled)
return;
ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
if (sp != null)
DetachSingleAttachmentToGround(sp, soLocalId);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
namespace System.Globalization
{
#if CORECLR
using IntList = List<int>;
using StringList = List<string>;
#else
using IntList = LowLevelList<int>;
using StringList = LowLevelList<string>;
#endif
internal partial class CalendarData
{
private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId)
{
bool ret = true;
uint useOverrides = this.bUseUserOverrides ? 0 : CAL_NOUSEROVERRIDE;
//
// Windows doesn't support some calendars right now, so remap those.
//
switch (calendarId)
{
case CalendarId.JAPANESELUNISOLAR: // Data looks like Japanese
calendarId = CalendarId.JAPAN;
break;
case CalendarId.JULIAN: // Data looks like gregorian US
case CalendarId.CHINESELUNISOLAR: // Algorithmic, so actual data is irrelevent
case CalendarId.SAKA: // reserved to match Office but not implemented in our code, so data is irrelevent
case CalendarId.LUNAR_ETO_CHN: // reserved to match Office but not implemented in our code, so data is irrelevent
case CalendarId.LUNAR_ETO_KOR: // reserved to match Office but not implemented in our code, so data is irrelevent
case CalendarId.LUNAR_ETO_ROKUYOU: // reserved to match Office but not implemented in our code, so data is irrelevent
case CalendarId.KOREANLUNISOLAR: // Algorithmic, so actual data is irrelevent
case CalendarId.TAIWANLUNISOLAR: // Algorithmic, so actual data is irrelevent
calendarId = CalendarId.GREGORIAN_US;
break;
}
//
// Special handling for some special calendar due to OS limitation.
// This includes calendar like Taiwan calendar, UmAlQura calendar, etc.
//
CheckSpecialCalendar(ref calendarId, ref localeName);
// Numbers
ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_ITWODIGITYEARMAX | useOverrides, out this.iTwoDigitYearMax);
// Strings
ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SCALNAME, out this.sNativeName);
ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SMONTHDAY | useOverrides, out this.sMonthDay);
// String Arrays
// Formats
ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SSHORTDATE, LOCALE_SSHORTDATE | useOverrides, out this.saShortDates);
ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SLONGDATE, LOCALE_SLONGDATE | useOverrides, out this.saLongDates);
// Get the YearMonth pattern.
ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SYEARMONTH, LOCALE_SYEARMONTH, out this.saYearMonths);
// Day & Month Names
// These are all single calType entries, 1 per day, so we have to make 7 or 13 calls to collect all the names
// Day
// Note that we're off-by-one since managed starts on sunday and windows starts on monday
ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SDAYNAME7, out this.saDayNames);
ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SABBREVDAYNAME7, out this.saAbbrevDayNames);
// Month names
ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1, out this.saMonthNames);
ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1, out this.saAbbrevMonthNames);
//
// The following LCTYPE are not supported in some platforms. If the call fails,
// don't return a failure.
//
GetCalendarDayInfo(localeName, calendarId, CAL_SSHORTESTDAYNAME7, out this.saSuperShortDayNames);
// Gregorian may have genitive month names
if (calendarId == CalendarId.GREGORIAN)
{
GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saMonthGenitiveNames);
GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saAbbrevMonthGenitiveNames);
}
// Calendar Parts Names
// This doesn't get always get localized names for gregorian (not available in windows < 7)
// so: eg: coreclr on win < 7 won't get these
CallEnumCalendarInfo(localeName, calendarId, CAL_SERASTRING, 0, out this.saEraNames);
CallEnumCalendarInfo(localeName, calendarId, CAL_SABBREVERASTRING, 0, out this.saAbbrevEraNames);
//
// Calendar Era Info
// Note that calendar era data (offsets, etc) is hard coded for each calendar since this
// data is implementation specific and not dynamic (except perhaps Japanese)
//
// Clean up the escaping of the formats
this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates);
this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates);
this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths);
this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay);
return ret;
}
// Get native two digit year max
internal static int GetTwoDigitYearMax(CalendarId calendarId)
{
int twoDigitYearMax = -1;
if (!CallGetCalendarInfoEx(null, calendarId, (uint)CAL_ITWODIGITYEARMAX, out twoDigitYearMax))
{
twoDigitYearMax = -1;
}
return twoDigitYearMax;
}
// Call native side to figure out which calendars are allowed
internal static int GetCalendars(String localeName, bool useUserOverride, CalendarId[] calendars)
{
EnumCalendarsData data = new EnumCalendarsData();
data.userOverride = 0;
data.calendars = new IntList();
// First call GetLocaleInfo if necessary
if (useUserOverride)
{
// They want user overrides, see if the user calendar matches the input calendar
int userCalendar = CultureData.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE);
// If we got a default, then use it as the first calendar
if (userCalendar != 0)
{
data.userOverride = userCalendar;
data.calendars.Add(userCalendar);
}
}
GCHandle contextHandle = GCHandle.Alloc(data);
try
{
// Now call the enumeration API. Work is done by our callback function
#if CORECLR
Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarsCallback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, (IntPtr)contextHandle);
#else
IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, IntPtr, Interop.BOOL>>(EnumCalendarsCallback);
Interop.Kernel32.EnumCalendarInfoExEx(callback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, (IntPtr)contextHandle);
#endif
}
finally
{
contextHandle.Free();
}
// Copy to the output array
for (int i = 0; i < Math.Min(calendars.Length, data.calendars.Count); i++)
calendars[i] = (CalendarId)data.calendars[i];
// Now we have a list of data, return the count
return data.calendars.Count;
}
private static bool SystemSupportsTaiwaneseCalendar()
{
string data;
// Taiwanese calendar get listed as one of the optional zh-TW calendars only when having zh-TW UI
return CallGetCalendarInfoEx("zh-TW", CalendarId.TAIWAN, CAL_SCALNAME, out data);
}
// PAL Layer ends here
private const uint CAL_RETURN_NUMBER = 0x20000000;
private const uint CAL_RETURN_GENITIVE_NAMES = 0x10000000;
private const uint CAL_NOUSEROVERRIDE = 0x80000000;
private const uint CAL_SCALNAME = 0x00000002;
private const uint CAL_SMONTHDAY = 0x00000038;
private const uint CAL_SSHORTDATE = 0x00000005;
private const uint CAL_SLONGDATE = 0x00000006;
private const uint CAL_SYEARMONTH = 0x0000002f;
private const uint CAL_SDAYNAME7 = 0x0000000d;
private const uint CAL_SABBREVDAYNAME7 = 0x00000014;
private const uint CAL_SMONTHNAME1 = 0x00000015;
private const uint CAL_SABBREVMONTHNAME1 = 0x00000022;
private const uint CAL_SSHORTESTDAYNAME7 = 0x00000037;
private const uint CAL_SERASTRING = 0x00000004;
private const uint CAL_SABBREVERASTRING = 0x00000039;
private const uint CAL_ICALINTVALUE = 0x00000001;
private const uint CAL_ITWODIGITYEARMAX = 0x00000030;
private const uint ENUM_ALL_CALENDARS = 0xffffffff;
private const uint LOCALE_SSHORTDATE = 0x0000001F;
private const uint LOCALE_SLONGDATE = 0x00000020;
private const uint LOCALE_SYEARMONTH = 0x00001006;
private const uint LOCALE_ICALENDARTYPE = 0x00001009;
////////////////////////////////////////////////////////////////////////
//
// For calendars like Gregorain US/Taiwan/UmAlQura, they are not available
// in all OS or all localized versions of OS.
// If OS does not support these calendars, we will fallback by using the
// appropriate fallback calendar and locale combination to retrieve data from OS.
//
// Parameters:
// __deref_inout pCalendarInt:
// Pointer to the calendar ID. This will be updated to new fallback calendar ID if needed.
// __in_out pLocaleNameStackBuffer
// Pointer to the StackSString object which holds the locale name to be checked.
// This will be updated to new fallback locale name if needed.
//
////////////////////////////////////////////////////////////////////////
private static void CheckSpecialCalendar(ref CalendarId calendar, ref string localeName)
{
string data;
// Gregorian-US isn't always available in the OS, however it is the same for all locales
switch (calendar)
{
case CalendarId.GREGORIAN_US:
// See if this works
if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out data))
{
// Failed, set it to a locale (fa-IR) that's alway has Gregorian US available in the OS
localeName = "fa-IR";
}
// See if that works
if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out data))
{
// Failed again, just use en-US with the gregorian calendar
localeName = "en-US";
calendar = CalendarId.GREGORIAN;
}
break;
case CalendarId.TAIWAN:
// Taiwan calendar data is not always in all language version of OS due to Geopolical reasons.
// It is only available in zh-TW localized versions of Windows.
// Let's check if OS supports it. If not, fallback to Greogrian localized for Taiwan calendar.
if (!SystemSupportsTaiwaneseCalendar())
{
calendar = CalendarId.GREGORIAN;
}
break;
}
}
private static bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out int data)
{
return (Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType | CAL_RETURN_NUMBER, IntPtr.Zero, 0, out data) != 0);
}
private static unsafe bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out string data)
{
const int BUFFER_LENGTH = 80;
// The maximum size for values returned from GetCalendarInfoEx is 80 characters.
char* buffer = stackalloc char[BUFFER_LENGTH];
int ret = Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType, (IntPtr)buffer, BUFFER_LENGTH, IntPtr.Zero);
if (ret > 0)
{
if (buffer[ret - 1] == '\0')
{
ret--; // don't include the null termination in the string
}
data = new string(buffer, 0, ret);
return true;
}
data = "";
return false;
}
// Context for EnumCalendarInfoExEx callback.
private class EnumData
{
public string userOverride;
public StringList strings;
}
// EnumCalendarInfoExEx callback itself.
#if !CORECLR
[NativeCallable(CallingConvention = CallingConvention.StdCall)]
#endif
private static unsafe Interop.BOOL EnumCalendarInfoCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr pReserved, IntPtr lParam)
{
EnumData context = (EnumData)((GCHandle)lParam).Target;
try
{
string calendarInfo = new string((char*)lpCalendarInfoString);
// If we had a user override, check to make sure this differs
if (context.userOverride != calendarInfo)
context.strings.Add(calendarInfo);
return Interop.BOOL.TRUE;
}
catch (Exception)
{
return Interop.BOOL.FALSE;
}
}
private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId calendar, uint calType, uint lcType, out string[] data)
{
EnumData context = new EnumData();
context.userOverride = null;
context.strings = new StringList();
// First call GetLocaleInfo if necessary
if (((lcType != 0) && ((lcType & CAL_NOUSEROVERRIDE) == 0)) &&
// Get user locale, see if it matches localeName.
// Note that they should match exactly, including letter case
GetUserDefaultLocaleName() == localeName)
{
// They want user overrides, see if the user calendar matches the input calendar
CalendarId userCalendar = (CalendarId)CultureData.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE);
// If the calendars were the same, see if the locales were the same
if (userCalendar == calendar)
{
// They matched, get the user override since locale & calendar match
string res = CultureData.GetLocaleInfoEx(localeName, lcType);
// if it succeeded remember the override for the later callers
if (res != "")
{
// Remember this was the override (so we can look for duplicates later in the enum function)
context.userOverride = res;
// Add to the result strings.
context.strings.Add(res);
}
}
}
GCHandle contextHandle = GCHandle.Alloc(context);
try
{
#if CORECLR
Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, (IntPtr)contextHandle);
#else
// Now call the enumeration API. Work is done by our callback function
IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, IntPtr, Interop.BOOL>>(EnumCalendarInfoCallback);
Interop.Kernel32.EnumCalendarInfoExEx(callback, localeName, (uint)calendar, null, calType, (IntPtr)contextHandle);
#endif // CORECLR
}
finally
{
contextHandle.Free();
}
// Now we have a list of data, fail if we didn't find anything.
if (context.strings.Count == 0)
{
data = null;
return false;
}
string[] output = context.strings.ToArray();
if (calType == CAL_SABBREVERASTRING || calType == CAL_SERASTRING)
{
// Eras are enumerated backwards. (oldest era name first, but
// Japanese calendar has newest era first in array, and is only
// calendar with multiple eras)
Array.Reverse(output, 0, output.Length);
}
data = output;
return true;
}
////////////////////////////////////////////////////////////////////////
//
// Get the native day names
//
// NOTE: There's a disparity between .Net & windows day orders, the input day should
// start with Sunday
//
// Parameters:
// OUT pOutputStrings The output string[] value.
//
////////////////////////////////////////////////////////////////////////
private static bool GetCalendarDayInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings)
{
bool result = true;
//
// We'll need a new array of 7 items
//
string[] results = new string[7];
// Get each one of them
for (int i = 0; i < 7; i++, calType++)
{
result &= CallGetCalendarInfoEx(localeName, calendar, calType, out results[i]);
// On the first iteration we need to go from CAL_SDAYNAME7 to CAL_SDAYNAME1, so subtract 7 before the ++ happens
// This is because the framework starts on sunday and windows starts on monday when counting days
if (i == 0)
calType -= 7;
}
outputStrings = results;
return result;
}
////////////////////////////////////////////////////////////////////////
//
// Get the native month names
//
// Parameters:
// OUT pOutputStrings The output string[] value.
//
////////////////////////////////////////////////////////////////////////
private static bool GetCalendarMonthInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings)
{
//
// We'll need a new array of 13 items
//
string[] results = new string[13];
// Get each one of them
for (int i = 0; i < 13; i++, calType++)
{
if (!CallGetCalendarInfoEx(localeName, calendar, calType, out results[i]))
results[i] = "";
}
outputStrings = results;
return true;
}
//
// struct to help our calendar data enumaration callback
//
private class EnumCalendarsData
{
public int userOverride; // user override value (if found)
public IntList calendars; // list of calendars found so far
}
#if !CORECLR
[NativeCallable(CallingConvention = CallingConvention.StdCall)]
#endif
private static Interop.BOOL EnumCalendarsCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr reserved, IntPtr lParam)
{
EnumCalendarsData context = (EnumCalendarsData)((GCHandle)lParam).Target;
try
{
// If we had a user override, check to make sure this differs
if (context.userOverride != calendar)
context.calendars.Add((int)calendar);
return Interop.BOOL.TRUE;
}
catch (Exception)
{
return Interop.BOOL.FALSE;
}
}
private static unsafe String GetUserDefaultLocaleName()
{
const int LOCALE_NAME_MAX_LENGTH = 85;
const uint LOCALE_SNAME = 0x0000005c;
const string LOCALE_NAME_USER_DEFAULT = null;
int result;
char* localeName = stackalloc char[LOCALE_NAME_MAX_LENGTH];
result = CultureData.GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME, localeName, LOCALE_NAME_MAX_LENGTH);
return result <= 0 ? "" : new String(localeName, 0, result - 1); // exclude the null termination
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.DocumentationComments;
using Microsoft.CodeAnalysis.MetadataAsSource;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.DocumentationComments;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource
{
public class DocCommentFormatterTests
{
private CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService();
private VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService();
private void TestFormat(string docCommentXmlFragment, string expected)
{
TestFormat(docCommentXmlFragment, expected, expected);
}
private void TestFormat(string docCommentXmlFragment, string expectedCSharp, string expectedVB)
{
var docComment = DocumentationComment.FromXmlFragment(docCommentXmlFragment);
var csharpFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_csharpService, docComment));
var vbFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_vbService, docComment));
Assert.Equal(expectedCSharp, csharpFormattedComment);
Assert.Equal(expectedVB, vbFormattedComment);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void Summary()
{
var comment = "<summary>This is a summary.</summary>";
var expected =
$@"{FeaturesResources.Summary_colon}
This is a summary.";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void Wrapping1()
{
var comment = "<summary>I am the very model of a modern major general. This is a very long comment. And getting longer by the minute.</summary>";
var expected =
$@"{FeaturesResources.Summary_colon}
I am the very model of a modern major general. This is a very long comment. And
getting longer by the minute.";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void Wrapping2()
{
var comment = "<summary>I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute.</summary>";
var expected =
$@"{FeaturesResources.Summary_colon}
I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe
minute.";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void Exception()
{
var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception>";
var expected =
$@"{FeaturesResources.Exceptions_colon}
T:System.NotImplementedException:
throws NotImplementedException";
TestFormat(comment, expected);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void MultipleExceptionTags()
{
var comment =
@"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception>
<exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception>";
var expected =
$@"{FeaturesResources.Exceptions_colon}
T:System.NotImplementedException:
throws NotImplementedException
T:System.InvalidOperationException:
throws InvalidOperationException";
TestFormat(comment, expected);
}
[Fact, WorkItem(530760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530760")]
[Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void MultipleExceptionTagsWithSameType()
{
var comment =
@"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException for reason X</exception>
<exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception>
<exception cref=""T:System.NotImplementedException"">also throws NotImplementedException for reason Y</exception>";
var expected =
$@"{FeaturesResources.Exceptions_colon}
T:System.NotImplementedException:
throws NotImplementedException for reason X
T:System.NotImplementedException:
also throws NotImplementedException for reason Y
T:System.InvalidOperationException:
throws InvalidOperationException";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void Returns()
{
var comment = @"<returns>A string is returned</returns>";
var expected =
$@"{FeaturesResources.Returns_colon}
A string is returned";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void SummaryAndParams()
{
var comment =
@"<summary>This is the summary.</summary>
<param name=""a"">The param named 'a'</param>
<param name=""b"">The param named 'b'</param>";
var expected =
$@"{FeaturesResources.Summary_colon}
This is the summary.
{FeaturesResources.Parameters_colon}
a:
The param named 'a'
b:
The param named 'b'";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TypeParameters()
{
var comment =
@"<typeparam name=""T"">The type param named 'T'</typeparam>
<typeparam name=""U"">The type param named 'U'</typeparam>";
var expected =
$@"{FeaturesResources.Type_parameters_colon}
T:
The type param named 'T'
U:
The type param named 'U'";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void FormatEverything()
{
var comment =
@"<summary>
This is a summary of something.
</summary>
<param name=""a"">The param named 'a'.</param>
<param name=""b""></param>
<param name=""c"">The param named 'c'.</param>
<typeparam name=""T"">A type parameter.</typeparam>
<typeparam name=""U""></typeparam>
<typeparam name=""V"">Another type parameter.</typeparam>
<returns>This returns nothing.</returns>
<exception cref=""System.FooException"">Thrown for an unknown reason</exception>
<exception cref=""System.BarException""></exception>
<exception cref=""System.BlahException"">Thrown when blah blah blah</exception>
<remarks>This doc comment is really not very remarkable.</remarks>";
var expected =
$@"{FeaturesResources.Summary_colon}
This is a summary of something.
{FeaturesResources.Parameters_colon}
a:
The param named 'a'.
b:
c:
The param named 'c'.
{FeaturesResources.Type_parameters_colon}
T:
A type parameter.
U:
V:
Another type parameter.
{FeaturesResources.Returns_colon}
This returns nothing.
{FeaturesResources.Exceptions_colon}
System.FooException:
Thrown for an unknown reason
System.BarException:
System.BlahException:
Thrown when blah blah blah
{FeaturesResources.Remarks_colon}
This doc comment is really not very remarkable.";
TestFormat(comment, expected);
}
}
}
| |
using System.Linq;
using FluentNHibernate.MappingModel;
using FluentNHibernate.Testing.DomainModel.Mapping;
using NUnit.Framework;
namespace FluentNHibernate.Testing.FluentInterfaceTests
{
[TestFixture]
public class ManyToOneMutablePropertyModelGenerationTests : BaseModelFixture
{
[Test]
public void AccessShouldSetModelAccessPropertyToValue()
{
ManyToOne()
.Mapping(m => m.Access.Field())
.ModelShouldMatch(x => x.Access.ShouldEqual("field"));
}
[Test]
public void CascadeShouldSetModelCascadePropertyToValue()
{
ManyToOne()
.Mapping(m => m.Cascade.All())
.ModelShouldMatch(x => x.Cascade.ShouldEqual("all"));
}
[Test]
public void ShouldSetModelClassPropertyToPropertyType()
{
ManyToOne()
.Mapping(m => {})
.ModelShouldMatch(x => x.Class.ShouldEqual(new TypeReference(typeof(PropertyReferenceTarget))));
}
[Test]
public void ClassShouldSetModelClassPropertyToValue()
{
ManyToOne()
.Mapping(m => m.Class(typeof(int)))
.ModelShouldMatch(x => x.Class.ShouldEqual(new TypeReference(typeof(int))));
}
[Test]
public void ColumnNameShouldAddModelColumnsCollection()
{
ManyToOne()
.Mapping(m => m.Column("col"))
.ModelShouldMatch(x => x.Columns.Count().ShouldEqual(1));
}
[Test]
public void FetchShouldSetFetchModelProperty()
{
ManyToOne()
.Mapping(m => m.Fetch.Select())
.ModelShouldMatch(x => x.Fetch.ShouldEqual("select"));
}
[Test]
public void WithForeignKeyShouldSetForeignKeyModelProperty()
{
ManyToOne()
.Mapping(m => m.ForeignKey("fk"))
.ModelShouldMatch(x => x.ForeignKey.ShouldEqual("fk"));
}
[Test]
public void InsertShouldSetInsertModelPropertyToTrue()
{
ManyToOne()
.Mapping(m => m.Insert())
.ModelShouldMatch(x => x.Insert.ShouldBeTrue());
}
[Test]
public void NotInsertShouldSetInsertModelPropertyToFalse()
{
ManyToOne()
.Mapping(m => m.Not.Insert())
.ModelShouldMatch(x => x.Insert.ShouldBeFalse());
}
[Test]
public void UpdateShouldSetUpdateModelPropertyToTrue()
{
ManyToOne()
.Mapping(m => m.Update())
.ModelShouldMatch(x => x.Update.ShouldBeTrue());
}
[Test]
public void NotUpdateShouldSetUpdateModelPropertyToFalse()
{
ManyToOne()
.Mapping(m => m.Not.Update())
.ModelShouldMatch(x => x.Update.ShouldBeFalse());
}
[Test]
public void ReadOnlyShouldSetInsertModelPropertyToFalse()
{
ManyToOne()
.Mapping(m => m.ReadOnly())
.ModelShouldMatch(x => x.Insert.ShouldBeFalse());
}
[Test]
public void NotReadOnlyShouldSetInsertModelPropertyToTrue()
{
ManyToOne()
.Mapping(m => m.Not.ReadOnly())
.ModelShouldMatch(x => x.Insert.ShouldBeTrue());
}
[Test]
public void ReadOnlyShouldSetUpdateModelPropertyToFalse()
{
ManyToOne()
.Mapping(m => m.ReadOnly())
.ModelShouldMatch(x => x.Update.ShouldBeFalse());
}
[Test]
public void NotReadOnlyShouldSetUpdateModelPropertyToTrue()
{
ManyToOne()
.Mapping(m => m.Not.ReadOnly())
.ModelShouldMatch(x => x.Update.ShouldBeTrue());
}
[Test]
public void LazyShouldSetLazyModelPropertyToTrue()
{
ManyToOne()
.Mapping(m => m.LazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldEqual(true));
}
[Test]
public void NotLazyShouldSetLazyModelPropertyToFalse()
{
ManyToOne()
.Mapping(m => m.Not.LazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldEqual(false));
}
[Test]
public void ShouldSetNameModelPropertyToPropertyName()
{
ManyToOne()
.Mapping(m => {})
.ModelShouldMatch(x => x.Name.ShouldEqual("Reference"));
}
[Test]
public void NotFoundShouldSetNotFoundModelProperty()
{
ManyToOne()
.Mapping(m => m.NotFound.Ignore())
.ModelShouldMatch(x => x.NotFound.ShouldEqual("ignore"));
}
[Test]
public void PropertyShouldSetPropertyRefModelProperty()
{
ManyToOne()
.Mapping(m => m.PropertyRef("Name"))
.ModelShouldMatch(x => x.PropertyRef.ShouldEqual("Name"));
}
[Test]
public void NullableShouldSetColumnNotNullPropertyToFalse()
{
ManyToOne()
.Mapping(m => m.Nullable())
.ModelShouldMatch(x => x.Columns.First().NotNull.ShouldBeFalse());
}
[Test]
public void NotNullableShouldSetColumnNotNullPropertyToTrue()
{
ManyToOne()
.Mapping(m => m.Not.Nullable())
.ModelShouldMatch(x => x.Columns.First().NotNull.ShouldBeTrue());
}
[Test]
public void UniqueShouldSetColumnUniquePropertyToTrue()
{
ManyToOne()
.Mapping(m => m.Unique())
.ModelShouldMatch(x => x.Columns.First().Unique.ShouldBeTrue());
}
[Test]
public void NotUniqueShouldSetColumnUniquePropertyToFalse()
{
ManyToOne()
.Mapping(m => m.Not.Unique())
.ModelShouldMatch(x => x.Columns.First().Unique.ShouldBeFalse());
}
[Test]
public void UniqueKeyShouldSetColumnUniqueKeyPropertyToValue()
{
ManyToOne()
.Mapping(m => m.UniqueKey("uk"))
.ModelShouldMatch(x => x.Columns.First().UniqueKey.ShouldEqual("uk"));
}
[Test]
public void IndexShouldSetColumnIndexPropertyToValue()
{
ManyToOne()
.Mapping(m => m.Index("ix"))
.ModelShouldMatch(x => x.Columns.First().Index.ShouldEqual("ix"));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Serilog;
using Thinktecture.Relay.Server.Config;
using Thinktecture.Relay.Server.Dto;
using Thinktecture.Relay.Server.Repository.DbModels;
using Thinktecture.Relay.Server.Security;
namespace Thinktecture.Relay.Server.Repository
{
public class LinkRepository : ILinkRepository
{
private static readonly Dictionary<string, PasswordInformation> _successfullyValidatedUsernamesAndPasswords = new Dictionary<string, PasswordInformation>();
private readonly ILogger _logger;
private readonly IPasswordHash _passwordHash;
private readonly IConfiguration _configuration;
private DateTime ActiveLinkTimeout => DateTime.UtcNow - _configuration.ActiveConnectionTimeout;
public LinkRepository(ILogger logger, IPasswordHash passwordHash, IConfiguration configuration)
{
_logger = logger;
_passwordHash = passwordHash ?? throw new ArgumentNullException(nameof(passwordHash));
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
public PageResult<LinkDetails> GetLinkDetails(PageRequest paging)
{
using (var context = new RelayContext())
{
var linksQuery = context.Links.AsQueryable();
if (!String.IsNullOrWhiteSpace(paging.SearchText))
{
var searchText = paging.SearchText.ToLower();
linksQuery = linksQuery.Where(w => w.UserName.Contains(searchText) || w.SymbolicName.Contains(searchText));
}
// Default sorting must be provided
if (String.IsNullOrWhiteSpace(paging.SortField))
{
paging.SortField = "SymbolicName";
paging.SortDirection = SortDirection.Asc;
}
var numberOfLinks = linksQuery.Count();
linksQuery = linksQuery.OrderByPropertyName(paging.SortField, paging.SortDirection);
linksQuery = linksQuery.ApplyPaging(paging);
return new PageResult<LinkDetails>()
{
Items = GetLinkDetailsFromDbLink(linksQuery).ToList(),
Count = numberOfLinks,
};
}
}
public Link GetLink(Guid linkId)
{
using (var context = new RelayContext())
{
var linkQuery = context.Links
.Where(l => l.Id == linkId);
return GetLinkFromDbLink(linkQuery).FirstOrDefault();
}
}
public LinkDetails GetLinkDetails(Guid linkId)
{
using (var context = new RelayContext())
{
var linkQuery = context.Links
.Where(l => l.Id == linkId);
return GetLinkDetailsFromDbLink(linkQuery).FirstOrDefault();
}
}
public Link GetLink(string linkName)
{
using (var context = new RelayContext())
{
var linkQuery = context.Links
.Where(p => p.UserName == linkName);
return GetLinkFromDbLink(linkQuery).FirstOrDefault();
}
}
public LinkConfiguration GetLinkConfiguration(Guid linkId)
{
using (var context = new RelayContext())
{
var linkQuery = context.Links
.Where(l => l.Id == linkId);
return GetLinkConfigurationFromDbLink(linkQuery).FirstOrDefault();
}
}
private IQueryable<Link> GetLinkFromDbLink(IQueryable<DbLink> linksQuery)
{
return linksQuery
.Select(l => new
{
link = l,
ActiveConnections = l.ActiveConnections
.Where(ac => ac.ConnectorVersion == 0 || ac.LastActivity > ActiveLinkTimeout)
.Select(ac => ac.ConnectionId)
})
.Select(i => new Link()
{
Id = i.link.Id,
ForwardOnPremiseTargetErrorResponse = i.link.ForwardOnPremiseTargetErrorResponse,
IsDisabled = i.link.IsDisabled,
SymbolicName = i.link.SymbolicName,
AllowLocalClientRequestsOnly = i.link.AllowLocalClientRequestsOnly,
});
}
private IQueryable<LinkDetails> GetLinkDetailsFromDbLink(IQueryable<DbLink> linksQuery)
{
return linksQuery
.Select(link => new
{
link,
link.ActiveConnections
})
.ToList()
.Select(i => new LinkDetails()
{
Id = i.link.Id,
CreationDate = i.link.CreationDate,
ForwardOnPremiseTargetErrorResponse = i.link.ForwardOnPremiseTargetErrorResponse,
IsDisabled = i.link.IsDisabled,
MaximumLinks = i.link.MaximumLinks,
SymbolicName = i.link.SymbolicName,
UserName = i.link.UserName,
AllowLocalClientRequestsOnly = i.link.AllowLocalClientRequestsOnly,
TokenRefreshWindow = i.link.TokenRefreshWindow,
HeartbeatInterval = i.link.HeartbeatInterval,
ReconnectMinWaitTime = i.link.ReconnectMinWaitTime,
ReconnectMaxWaitTime = i.link.ReconnectMaxWaitTime,
AbsoluteConnectionLifetime = i.link.AbsoluteConnectionLifetime,
SlidingConnectionLifetime = i.link.SlidingConnectionLifetime,
Connections = i.ActiveConnections
.Select(ac => ac.ConnectionId
+ "; Versions: Connector = " + ac.ConnectorVersion + ", Assembly = " + ac.AssemblyVersion
+ "; Last Activity: " + ac.LastActivity.ToString("yyyy-MM-dd hh:mm:ss")
+ ((ac.LastActivity + _configuration.ActiveConnectionTimeout <= DateTime.UtcNow) ? " (inactive)" : "")
)
.ToList(),
})
.AsQueryable();
}
private IQueryable<LinkConfiguration> GetLinkConfigurationFromDbLink(IQueryable<DbLink> linksQuery)
{
return linksQuery
.Select(link => new
{
link,
})
.ToList()
.Select(i => new LinkConfiguration()
{
TokenRefreshWindow = i.link.TokenRefreshWindow,
HeartbeatInterval = i.link.HeartbeatInterval,
ReconnectMinWaitTime = i.link.ReconnectMinWaitTime,
ReconnectMaxWaitTime = i.link.ReconnectMaxWaitTime,
AbsoluteConnectionLifetime = i.link.AbsoluteConnectionLifetime,
SlidingConnectionLifetime = i.link.SlidingConnectionLifetime,
})
.AsQueryable();
}
public CreateLinkResult CreateLink(string symbolicName, string userName)
{
using (var context = new RelayContext())
{
var password = _passwordHash.GeneratePassword(_configuration.LinkPasswordLength);
var passwordInformation = _passwordHash.CreatePasswordInformation(password);
var link = new DbLink()
{
Id = Guid.NewGuid(),
Password = passwordInformation.Hash,
Salt = passwordInformation.Salt,
Iterations = passwordInformation.Iterations,
SymbolicName = symbolicName,
UserName = userName,
CreationDate = DateTime.UtcNow,
};
context.Links.Add(link);
context.SaveChanges();
var result = new CreateLinkResult()
{
Id = link.Id,
Password = Convert.ToBase64String(password),
};
return result;
}
}
public bool UpdateLink(LinkDetails link)
{
using (var context = new RelayContext())
{
var linkEntity = context.Links.SingleOrDefault(p => p.Id == link.Id);
if (linkEntity == null)
return false;
linkEntity.CreationDate = link.CreationDate;
linkEntity.AllowLocalClientRequestsOnly = link.AllowLocalClientRequestsOnly;
linkEntity.ForwardOnPremiseTargetErrorResponse = link.ForwardOnPremiseTargetErrorResponse;
linkEntity.IsDisabled = link.IsDisabled;
linkEntity.MaximumLinks = link.MaximumLinks;
linkEntity.SymbolicName = link.SymbolicName;
linkEntity.UserName = link.UserName;
linkEntity.TokenRefreshWindow = link.TokenRefreshWindow;
linkEntity.HeartbeatInterval = link.HeartbeatInterval;
linkEntity.ReconnectMinWaitTime = link.ReconnectMinWaitTime;
linkEntity.ReconnectMaxWaitTime = link.ReconnectMaxWaitTime;
linkEntity.AbsoluteConnectionLifetime = link.AbsoluteConnectionLifetime;
linkEntity.SlidingConnectionLifetime = link.SlidingConnectionLifetime;
context.Entry(linkEntity).State = EntityState.Modified;
return context.SaveChanges() == 1;
}
}
public void DeleteLink(Guid linkId)
{
using (var context = new RelayContext())
{
var itemToDelete = new DbLink
{
Id = linkId,
};
context.Links.Attach(itemToDelete);
context.Links.Remove(itemToDelete);
context.SaveChanges();
}
}
public IEnumerable<LinkDetails> GetLinkDetails()
{
using (var context = new RelayContext())
{
return GetLinkDetailsFromDbLink(context.Links).ToList();
}
}
public bool Authenticate(string userName, string password, out Guid linkId)
{
linkId = Guid.Empty;
using (var context = new RelayContext())
{
byte[] passwordBytes;
try
{
passwordBytes = Convert.FromBase64String(password);
}
catch
{
return false;
}
var link = context.Links.Where(p => p.UserName == userName).Select(p => new
{
p.Id,
p.Password,
p.Iterations,
p.Salt,
}).FirstOrDefault();
if (link == null)
{
return false;
}
var passwordInformation = new PasswordInformation()
{
Hash = link.Password,
Iterations = link.Iterations,
Salt = link.Salt,
};
var cacheKey = userName + "/" + password;
PasswordInformation previousInfo;
lock (_successfullyValidatedUsernamesAndPasswords)
{
_successfullyValidatedUsernamesAndPasswords.TryGetValue(cacheKey, out previousInfo);
}
// found in cache (NOTE: cache only contains successfully validated passwords to prevent DOS attacks!)
if (previousInfo != null)
{
if (previousInfo.Hash == passwordInformation.Hash
&& previousInfo.Iterations == passwordInformation.Iterations
&& previousInfo.Salt == passwordInformation.Salt)
{
linkId = link.Id;
return true;
}
}
// ELSE: calculate and cache
if (!_passwordHash.ValidatePassword(passwordBytes, passwordInformation))
{
return false;
}
lock (_successfullyValidatedUsernamesAndPasswords)
{
{
_successfullyValidatedUsernamesAndPasswords[cacheKey] = passwordInformation;
}
}
linkId = link.Id;
return true;
}
}
public bool IsUserNameAvailable(string userName)
{
using (var context = new RelayContext())
{
return !context.Links.Any(p => p.UserName == userName);
}
}
public async Task AddOrRenewActiveConnectionAsync(Guid linkId, Guid originId, string connectionId, int connectorVersion, string assemblyVersion)
{
_logger?.Verbose("Adding or updating connection. connection-id={ConnectionId}, link-id={LinkId}, connector-version={ConnectorVersion}, connector-assembly-version={ConnectorAssemblyVersion}", connectionId, linkId, connectorVersion, assemblyVersion);
try
{
using (var context = new RelayContext())
{
var activeConnection = await context.ActiveConnections
.FirstOrDefaultAsync(ac => ac.LinkId == linkId && ac.OriginId == originId && ac.ConnectionId == connectionId).ConfigureAwait(false);
if (activeConnection != null)
{
activeConnection.LastActivity = DateTime.UtcNow;
activeConnection.ConnectorVersion = connectorVersion;
activeConnection.AssemblyVersion = assemblyVersion;
context.Entry(activeConnection).State = EntityState.Modified;
}
else
{
context.ActiveConnections.Add(new DbActiveConnection()
{
LinkId = linkId,
OriginId = originId,
ConnectionId = connectionId,
ConnectorVersion = connectorVersion,
AssemblyVersion = assemblyVersion,
LastActivity = DateTime.UtcNow,
});
}
await context.SaveChangesAsync().ConfigureAwait(false);
}
}
catch (Exception ex)
{
_logger?.Error(ex, "Error during adding or renewing an active connection. link-id={LinkId}, connection-id={ConnectionId}, connector-version={ConnectorVersion}, connector-assembly-version={ConnectorAssemblyVersion}", linkId, connectionId, connectorVersion, assemblyVersion);
}
}
public async Task RenewActiveConnectionAsync(string connectionId)
{
_logger?.Verbose("Renewing last activity. connection-id={ConnectionId}", connectionId);
try
{
using (var context = new RelayContext())
{
var activeConnection = await context.ActiveConnections.FirstOrDefaultAsync(ac => ac.ConnectionId == connectionId).ConfigureAwait(false);
if (activeConnection != null)
{
activeConnection.LastActivity = DateTime.UtcNow;
context.Entry(activeConnection).State = EntityState.Modified;
await context.SaveChangesAsync().ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
_logger?.Error(ex, "Error during renewing an active connection. connection-id={ConnectionId}", connectionId);
}
}
public async Task RemoveActiveConnectionAsync(string connectionId)
{
_logger?.Verbose("Deleting active connection. connection-id={ConnectionId}", connectionId);
try
{
using (var context = new RelayContext())
{
var activeConnection = await context.ActiveConnections.FirstOrDefaultAsync(ac => ac.ConnectionId == connectionId).ConfigureAwait(false);
if (activeConnection != null)
{
context.ActiveConnections.Remove(activeConnection);
await context.SaveChangesAsync().ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
_logger?.Error(ex, "Error during removing an active connection. connection-id={ConnectionId}", connectionId);
}
}
public void DeleteAllConnectionsForOrigin(Guid originId)
{
_logger?.Verbose("Deleting all active connections");
try
{
using (var context = new RelayContext())
{
var invalidConnections = context.ActiveConnections.Where(ac => ac.OriginId == originId).ToList();
context.ActiveConnections.RemoveRange(invalidConnections);
context.SaveChanges();
}
}
catch (Exception ex)
{
_logger?.Error(ex, "Error during deleting of all active connections");
}
}
}
}
| |
//
// Copyright 2011-2013, Xamarin 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.IO;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.Storage.Pickers;
using Plugin.Media.Abstractions;
using Windows.UI.Xaml.Controls;
using Windows.Media.MediaProperties;
using Windows.UI.Xaml;
using System.Threading;
using System.Linq;
using Windows.ApplicationModel.Activation;
using DMX.Helper;
using System.Diagnostics;
namespace Plugin.Media
{
/// <summary>
/// Implementation for Media
/// </summary>
public class MediaImplementation : IMedia
{
private static TaskCompletionSource<MediaFile> completionSource;
private static readonly IEnumerable<string> SupportedVideoFileTypes = new List<string> { ".mp4", ".wmv", ".avi" };
private static readonly IEnumerable<string> SupportedImageFileTypes = new List<string> { ".jpeg", ".jpg", ".png", ".gif", ".bmp" };
/// <summary>
/// Implementation
/// </summary>
public MediaImplementation()
{
watcher = DeviceInformation.CreateWatcher(DeviceClass.VideoCapture);
watcher.Added += OnDeviceAdded;
watcher.Updated += OnDeviceUpdated;
watcher.Removed += OnDeviceRemoved;
watcher.Start();
}
bool initialized = false;
public async Task<bool> Initialize()
{
try
{
var info = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture).AsTask().ConfigureAwait(false);
lock (devices)
{
foreach (var device in info)
{
if (device.IsEnabled)
devices.Add(device.Id);
}
isCameraAvailable = (devices.Count > 0);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Unable to detect cameras: " + ex);
}
initialized = true;
return true;
}
/// <inheritdoc/>
public bool IsCameraAvailable
{
get
{
if (!initialized)
Initialize().Wait();
return isCameraAvailable;
}
}
/// <inheritdoc/>
public bool IsTakePhotoSupported
{
get { return true; }
}
/// <inheritdoc/>
public bool IsPickPhotoSupported
{
get { return true; }
}
/// <inheritdoc/>
public bool IsTakeVideoSupported
{
get { return false; }
}
/// <inheritdoc/>
public bool IsPickVideoSupported
{
get { return true; }
}
/// <summary>
/// Take a photo async with specified options
/// </summary>
/// <param name="options">Camera Media Options</param>
/// <returns>Media file of photo or null if canceled</returns>
public async Task<MediaFile> TakePhotoAsync(StoreCameraMediaOptions options)
{
if (!initialized)
await Initialize();
if (!IsCameraAvailable)
throw new NotSupportedException();
options.VerifyOptions();
var capture = new CameraCaptureUI();
var result = await capture.CaptureFileAsync(CameraCaptureUIMode.Photo, options);
if (result == null)
return null;
StorageFolder folder = ApplicationData.Current.LocalFolder;
string path = options.GetFilePath(folder.Path);
var directoryFull = Path.GetDirectoryName(path);
var newFolder = directoryFull.Replace(folder.Path, string.Empty);
if (!string.IsNullOrWhiteSpace(newFolder))
await folder.CreateFolderAsync(newFolder, CreationCollisionOption.OpenIfExists);
folder = await StorageFolder.GetFolderFromPathAsync(directoryFull);
string filename = Path.GetFileName(path);
string aPath = null;
if (options?.SaveToAlbum ?? false)
{
try
{
string fileNameNoEx = Path.GetFileNameWithoutExtension(path);
var copy = await result.CopyAsync(KnownFolders.PicturesLibrary, fileNameNoEx + result.FileType, NameCollisionOption.GenerateUniqueName);
aPath = copy.Path;
}
catch (Exception ex)
{
Debug.WriteLine("unable to save to album:" + ex);
}
}
var file = await result.CopyAsync(folder, filename, NameCollisionOption.GenerateUniqueName).AsTask();
return new MediaFile(file.Path, () => file.OpenStreamForReadAsync().Result, albumPath: aPath);
}
/// <summary>
/// Picks a photo from the default gallery
/// </summary>
/// <returns>Media file or null if canceled</returns>
public Task<MediaFile> PickPhotoAsync()
{
var ntcs = new TaskCompletionSource<MediaFile>();
if (Interlocked.CompareExchange(ref completionSource, ntcs, null) != null)
throw new InvalidOperationException("Only one operation can be active at at time");
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.ViewMode = PickerViewMode.Thumbnail;
foreach (var filter in SupportedImageFileTypes)
picker.FileTypeFilter.Add(filter);
picker.PickSingleFileAndContinue();
return ntcs.Task;
}
/// <summary>
/// Take a video with specified options
/// </summary>
/// <param name="options">Video Media Options</param>
/// <returns>Media file of new video or null if canceled</returns>
public Task<MediaFile> TakeVideoAsync(StoreVideoOptions options)
{
throw new NotSupportedException();
}
/// <summary>
/// Picks a video from the default gallery
/// </summary>
/// <returns>Media file of video or null if canceled</returns>
public Task<MediaFile> PickVideoAsync()
{
var ntcs = new TaskCompletionSource<MediaFile>();
if (Interlocked.CompareExchange(ref completionSource, ntcs, null) != null)
throw new InvalidOperationException("Only one operation can be active at at time");
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
picker.ViewMode = PickerViewMode.Thumbnail;
foreach (var filter in SupportedVideoFileTypes)
picker.FileTypeFilter.Add(filter);
picker.PickSingleFileAndContinue();
return ntcs.Task;
}
private readonly HashSet<string> devices = new HashSet<string>();
private readonly DeviceWatcher watcher;
private bool isCameraAvailable;
/// <summary>
/// OnFilesPicked
/// </summary>
/// <param name="args"></param>
public static void OnFilesPicked(IActivatedEventArgs args)
{
var tcs = Interlocked.Exchange(ref completionSource, null);
IReadOnlyList<StorageFile> files;
var fopArgs = args as FileOpenPickerContinuationEventArgs;
if (fopArgs != null)
{
// Pass the picked files to the subscribed event handlers
// In a real world app you could also use a Messenger, Listener or any other subscriber-based model
if (fopArgs.Files.Any())
{
files = fopArgs.Files;
}
else
{
tcs.SetResult(null);
return;
}
}
else
{
tcs.SetResult(null);
return;
}
// Check if video or image and pick first file to show
var imageFile = files.FirstOrDefault(f => SupportedImageFileTypes.Contains(f.FileType.ToLower()));
if (imageFile != null)
{
tcs.SetResult(new MediaFile(imageFile.Path, () => imageFile.OpenStreamForReadAsync().Result));
return;
}
var videoFile = files.FirstOrDefault(f => SupportedVideoFileTypes.Contains(f.FileType.ToLower()));
if (videoFile != null)
{
tcs.SetResult(new MediaFile(videoFile.Path, () => videoFile.OpenStreamForReadAsync().Result));
return;
}
tcs.SetResult(null);
}
private void OnDeviceUpdated(DeviceWatcher sender, DeviceInformationUpdate update)
{
object value;
if (!update.Properties.TryGetValue("System.Devices.InterfaceEnabled", out value))
return;
lock (devices)
{
if ((bool)value)
devices.Add(update.Id);
else
devices.Remove(update.Id);
isCameraAvailable = devices.Count > 0;
}
}
private void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate update)
{
lock (devices)
{
devices.Remove(update.Id);
if (devices.Count == 0)
isCameraAvailable = false;
}
}
private void OnDeviceAdded(DeviceWatcher sender, DeviceInformation device)
{
if (!device.IsEnabled)
return;
lock (devices)
{
devices.Add(device.Id);
isCameraAvailable = true;
}
}
}
}
| |
// 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.
/**************************************************************
/* a test case based on DoubLinkStay. Instead of delete all of
/* the reference to a Cyclic Double linked list, it creats one
/* reference to the first node of the linked list, then delete all old
/* reference. This test trys to make fake leak for GC.
/**************************************************************/
namespace DoubLink {
using System;
public class DoubLinkNoLeak2
{
internal DoubLink[] Mv_Doub;
internal DLinkNode[] Mv_DLink;
internal int n_count = 0;
public static int Main(System.String [] Args)
{
int iRep = 0;
int iObj = 0;
switch( Args.Length )
{
case 1:
if (!Int32.TryParse( Args[0], out iRep ))
{
iRep = 5;
}
iObj = 10;
break;
case 2:
if (!Int32.TryParse( Args[0], out iRep ))
{
iRep = 5;
}
if (!Int32.TryParse( Args[1], out iObj ))
{
iObj = 10;
}
break;
default:
iRep = 5;
iObj = 10;
break;
}
DoubLinkNoLeak2 Mv_Leak = new DoubLinkNoLeak2();
if(Mv_Leak.runTest(iRep, iObj ))
{
Console.WriteLine("Test Passed");
return 100;
}
Console.WriteLine("Test Failed");
return 1;
}
public bool runTest(int iRep, int iObj)
{
Mv_DLink = new DLinkNode[iRep*10];
for(int i=0; i <10; i++)
{
SetLink(iRep, iObj);
MakeLeak(iRep);
}
Mv_DLink = null;
Mv_Doub = null;
GC.Collect();
GC.WaitForPendingFinalizers();
//do a second GC collect since some nodes may have been still alive at the time of first collect
GC.Collect();
GC.WaitForPendingFinalizers();
int totalNodes = iRep * iObj * 10;
Console.Write(DLinkNode.FinalCount);
Console.Write(" DLinkNodes finalized out of ");
Console.WriteLine(totalNodes);
return (DLinkNode.FinalCount == totalNodes);
}
public void SetLink(int iRep, int iObj)
{
Mv_Doub = new DoubLink[iRep];
for(int i=0; i<iRep; i++)
{
Mv_Doub[i] = new DoubLink(iObj);
Mv_DLink[n_count] = Mv_Doub[i][0];
n_count++;
}
}
public void MakeLeak(int iRep)
{
for(int i=0; i<iRep; i++)
{
Mv_Doub[i] = null;
}
}
}
public class DoubLink
{
internal DLinkNode[] Mv_DLink;
public DoubLink(int Num)
: this(Num, false)
{
}
public DoubLink(int Num, bool large)
{
Mv_DLink = new DLinkNode[Num];
if (Num == 0)
{
return;
}
if (Num == 1)
{
// only one element
Mv_DLink[0] = new DLinkNode((large ? 250 : 1), Mv_DLink[0], Mv_DLink[0]);
return;
}
// first element
Mv_DLink[0] = new DLinkNode((large ? 250 : 1), Mv_DLink[Num - 1], Mv_DLink[1]);
// all elements in between
for (int i = 1; i < Num - 1; i++)
{
Mv_DLink[i] = new DLinkNode((large ? 250 : i + 1), Mv_DLink[i - 1], Mv_DLink[i + 1]);
}
// last element
Mv_DLink[Num - 1] = new DLinkNode((large ? 250 : Num), Mv_DLink[Num - 2], Mv_DLink[0]);
}
public int NodeNum
{
get
{
return Mv_DLink.Length;
}
}
public DLinkNode this[int index]
{
get
{
return Mv_DLink[index];
}
set
{
Mv_DLink[index] = value;
}
}
}
public class DLinkNode
{
// disabling unused variable warning
#pragma warning disable 0414
internal DLinkNode Last;
internal DLinkNode Next;
internal int[] Size;
#pragma warning restore 0414
public static int FinalCount = 0;
public DLinkNode(int SizeNum, DLinkNode LastObject, DLinkNode NextObject)
{
Last = LastObject;
Next = NextObject;
Size = new int[SizeNum * 1024];
}
~DLinkNode()
{
FinalCount++;
}
}
}
| |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Universal charset detector code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Shy Shalom <shooshX@gmail.com>
* Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
namespace UniversalDetector.Core
{
public abstract class GreekModel : SequenceModel
{
// Model Table:
// total sequences: 100%
// first 512 sequences: 98.2851%
// first 1024 sequences:1.7001%
// rest sequences: 0.0359%
// negative sequences: 0.0148%
private readonly static byte[] GREEK_LANG_MODEL = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,3,2,2,3,3,3,3,3,3,3,3,1,3,3,3,0,2,2,3,3,0,3,0,3,2,0,3,3,3,0,
3,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,3,0,3,3,0,3,2,3,3,0,3,2,3,3,3,0,0,3,0,3,0,3,3,2,0,0,0,
2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,
0,2,3,2,2,3,3,3,3,3,3,3,3,0,3,3,3,3,0,2,3,3,0,3,3,3,3,2,3,3,3,0,
2,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,2,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,0,2,1,3,3,3,3,2,3,3,2,3,3,2,0,
0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,0,3,3,3,3,3,3,0,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,2,3,3,0,
2,0,1,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
0,3,3,3,3,3,2,3,0,0,0,0,3,3,0,3,1,3,3,3,0,3,3,0,3,3,3,3,0,0,0,0,
2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,3,0,3,0,3,3,3,3,3,0,3,2,2,2,3,0,2,3,3,3,3,3,2,3,3,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,3,3,2,2,2,3,3,3,3,0,3,1,3,3,3,3,2,3,3,3,3,3,3,3,2,2,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,3,2,0,3,0,0,0,3,3,2,3,3,3,3,3,0,0,3,2,3,0,2,3,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,0,3,3,3,3,0,0,3,3,0,2,3,0,3,0,3,3,3,0,0,3,0,3,0,2,2,3,3,0,0,
0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,3,2,0,3,2,3,3,3,3,0,3,3,3,3,3,0,3,3,2,3,2,3,3,2,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,2,3,2,3,3,3,3,3,3,0,2,3,2,3,2,2,2,3,2,3,3,2,3,0,2,2,2,3,0,
2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,3,0,0,0,3,3,3,2,3,3,0,0,3,0,3,0,0,0,3,2,0,3,0,3,0,0,2,0,2,0,
0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,0,3,3,3,3,3,3,0,3,3,0,3,0,0,0,3,3,0,3,3,3,0,0,1,2,3,0,
3,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,3,2,0,0,3,2,2,3,3,0,3,3,3,3,3,2,1,3,0,3,2,3,3,2,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,3,3,0,2,3,3,3,3,3,3,0,0,3,0,3,0,0,0,3,3,0,3,2,3,0,0,3,3,3,0,
3,0,0,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,0,3,3,3,3,3,3,0,0,3,0,3,0,0,0,3,2,0,3,2,3,0,0,3,2,3,0,
2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,3,1,2,2,3,3,3,3,3,3,0,2,3,0,3,0,0,0,3,3,0,3,0,2,0,0,2,3,1,0,
2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,0,3,3,3,3,0,3,0,3,3,2,3,0,3,3,3,3,3,3,0,3,3,3,0,2,3,0,0,3,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,0,3,3,3,0,0,3,0,0,0,3,3,0,3,0,2,3,3,0,0,3,0,3,0,3,3,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,3,0,0,0,3,3,3,3,3,3,0,0,3,0,2,0,0,0,3,3,0,3,0,3,0,0,2,0,2,0,
0,0,0,0,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,3,3,0,3,0,2,0,3,2,0,3,2,3,2,3,0,0,3,2,3,2,3,3,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,3,0,0,2,3,3,3,3,3,0,0,0,3,0,2,1,0,0,3,2,2,2,0,3,0,0,2,2,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,0,3,3,3,2,0,3,0,3,0,3,3,0,2,1,2,3,3,0,0,3,0,3,0,3,3,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,2,3,3,3,0,3,3,3,3,3,3,0,2,3,0,3,0,0,0,2,1,0,2,2,3,0,0,2,2,2,0,
0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,3,0,0,2,3,3,3,2,3,0,0,1,3,0,2,0,0,0,0,3,0,1,0,2,0,0,1,1,1,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,3,1,0,3,0,0,0,3,2,0,3,2,3,3,3,0,0,3,0,3,2,2,2,1,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,0,3,3,3,0,0,3,0,0,0,0,2,0,2,3,3,2,2,2,2,3,0,2,0,2,2,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,3,3,3,2,0,0,0,0,0,0,2,3,0,2,0,2,3,2,0,0,3,0,3,0,3,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,3,2,3,3,2,2,3,0,2,0,3,0,0,0,2,0,0,0,0,1,2,0,2,0,2,0,
0,2,0,2,0,2,2,0,0,1,0,2,2,2,0,2,2,2,0,2,2,2,0,0,2,0,0,1,0,0,0,0,
0,2,0,3,3,2,0,0,0,0,0,0,1,3,0,2,0,2,2,2,0,0,2,0,3,0,0,2,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,3,0,2,3,2,0,2,2,0,2,0,2,2,0,2,0,2,2,2,0,0,0,0,0,0,2,3,0,0,0,2,
0,1,2,0,0,0,0,2,2,0,0,0,2,1,0,2,2,0,0,0,0,0,0,1,0,2,0,0,0,0,0,0,
0,0,2,1,0,2,3,2,2,3,2,3,2,0,0,3,3,3,0,0,3,2,0,0,0,1,1,0,2,0,2,2,
0,2,0,2,0,2,2,0,0,2,0,2,2,2,0,2,2,2,2,0,0,2,0,0,0,2,0,1,0,0,0,0,
0,3,0,3,3,2,2,0,3,0,0,0,2,2,0,2,2,2,1,2,0,0,1,2,2,0,0,3,0,0,0,2,
0,1,2,0,0,0,1,2,0,0,0,0,0,0,0,2,2,0,1,0,0,2,0,0,0,2,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,2,3,3,2,2,0,0,0,2,0,2,3,3,0,2,0,0,0,0,0,0,2,2,2,0,2,2,0,2,0,2,
0,2,2,0,0,2,2,2,2,1,0,0,2,2,0,2,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,
0,2,0,3,2,3,0,0,0,3,0,0,2,2,0,2,0,2,2,2,0,0,2,0,0,0,0,0,0,0,0,2,
0,0,2,2,0,0,2,2,2,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,2,0,0,3,2,0,2,2,2,2,2,0,0,0,2,0,0,0,0,2,0,1,0,0,2,0,1,0,0,0,
0,2,2,2,0,2,2,0,1,2,0,2,2,2,0,2,2,2,2,1,2,2,0,0,2,0,0,0,0,0,0,0,
0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
0,2,0,2,0,2,2,0,0,0,0,1,2,1,0,0,2,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,3,2,3,0,0,2,0,0,0,2,2,0,2,0,0,0,1,0,0,2,0,2,0,2,2,0,0,0,0,
0,0,2,0,0,0,0,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,
0,2,2,3,2,2,0,0,0,0,0,0,1,3,0,2,0,2,2,0,0,0,1,0,2,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,2,0,2,0,3,2,0,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
0,0,2,0,0,0,0,1,1,0,0,2,1,2,0,2,2,0,1,0,0,1,0,0,0,2,0,0,0,0,0,0,
0,3,0,2,2,2,0,0,2,0,0,0,2,0,0,0,2,3,0,2,0,0,0,0,0,0,2,2,0,0,0,2,
0,1,2,0,0,0,1,2,2,1,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,2,1,2,0,2,2,0,2,0,0,2,0,0,0,0,1,2,1,0,2,1,0,0,0,0,0,0,0,0,0,0,
0,0,2,0,0,0,3,1,2,2,0,2,0,0,0,0,2,0,0,0,2,0,0,3,0,0,0,0,2,2,2,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,2,1,0,2,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0,2,
0,2,2,0,0,2,2,2,2,2,0,1,2,0,0,0,2,2,0,1,0,2,0,0,2,2,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,0,3,0,0,2,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,2,
0,1,2,0,0,0,0,2,2,1,0,1,0,1,0,2,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,
0,2,0,1,2,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,0,0,0,0,1,0,0,0,0,0,0,2,
0,2,2,0,0,0,0,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0,0,
0,2,2,2,2,0,0,0,3,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,1,
0,0,2,0,0,0,0,1,2,0,0,0,0,0,0,2,2,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,
0,2,0,2,2,2,0,0,2,0,0,0,0,0,0,0,2,2,2,0,0,0,2,0,0,0,0,0,0,0,0,2,
0,0,1,0,0,0,0,2,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,
0,3,0,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,2,
0,0,2,0,0,0,0,2,2,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,2,0,2,2,1,0,0,0,0,0,0,2,0,0,2,0,2,2,2,0,0,0,0,0,0,2,0,0,0,0,2,
0,0,2,0,0,2,0,2,2,0,0,0,0,2,0,2,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,
0,0,3,0,0,0,2,2,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0,0,0,0,
0,2,2,2,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,
0,0,0,0,0,0,0,2,1,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
0,2,0,0,0,2,0,0,0,0,0,1,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,2,0,0,0,
0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,2,0,2,0,0,0,
0,0,0,0,0,0,0,0,2,1,0,0,0,0,0,0,2,0,0,0,1,2,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
};
public GreekModel(byte[] charToOrderMap, string name)
: base(charToOrderMap, GREEK_LANG_MODEL, 0.982851f, false, name)
{
}
}
public class Latin7Model : GreekModel
{
/****************************************************************
255: Control characters that usually does not exist in any text
254: Carriage/Return
253: symbol (punctuation) that does not belong to word
252: 0 - 9
*****************************************************************/
//Character Mapping Table:
private readonly static byte[] LATIN7_CHAR_TO_ORDER_MAP = {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
+253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253, 82,100,104, 94, 98,101,116,102,111,187,117, 92, 88,113, 85, //40
79,118,105, 83, 67,114,119, 95, 99,109,188,253,253,253,253,253, //50
253, 72, 70, 80, 81, 60, 96, 93, 89, 68,120, 97, 77, 86, 69, 55, //60
78,115, 65, 66, 58, 76,106,103, 87,107,112,253,253,253,253,253, //70
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //80
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //90
+253,233, 90,253,253,253,253,253,253,253,253,253,253, 74,253,253, //a0
253,253,253,253,247,248, 61, 36, 46, 71, 73,253, 54,253,108,123, //b0
110, 31, 51, 43, 41, 34, 91, 40, 52, 47, 44, 53, 38, 49, 59, 39, //c0
35, 48,250, 37, 33, 45, 56, 50, 84, 57,120,121, 17, 18, 22, 15, //d0
124, 1, 29, 20, 21, 3, 32, 13, 25, 5, 11, 16, 10, 6, 30, 4, //e0
9, 8, 14, 7, 2, 12, 28, 23, 42, 24, 64, 75, 19, 26, 27,253, //f0
};
public Latin7Model() : base(LATIN7_CHAR_TO_ORDER_MAP, "ISO-8859-7")
{
}
}
public class Win1253Model : GreekModel
{
private readonly static byte[] WIN1253__CHAR_TO_ORDER_MAP = {
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10
+253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30
253, 82,100,104, 94, 98,101,116,102,111,187,117, 92, 88,113, 85, //40
79,118,105, 83, 67,114,119, 95, 99,109,188,253,253,253,253,253, //50
253, 72, 70, 80, 81, 60, 96, 93, 89, 68,120, 97, 77, 86, 69, 55, //60
78,115, 65, 66, 58, 76,106,103, 87,107,112,253,253,253,253,253, //70
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //80
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //90
+253,233, 61,253,253,253,253,253,253,253,253,253,253, 74,253,253, //a0
253,253,253,253,247,253,253, 36, 46, 71, 73,253, 54,253,108,123, //b0
110, 31, 51, 43, 41, 34, 91, 40, 52, 47, 44, 53, 38, 49, 59, 39, //c0
35, 48,250, 37, 33, 45, 56, 50, 84, 57,120,121, 17, 18, 22, 15, //d0
124, 1, 29, 20, 21, 3, 32, 13, 25, 5, 11, 16, 10, 6, 30, 4, //e0
9, 8, 14, 7, 2, 12, 28, 23, 42, 24, 64, 75, 19, 26, 27,253, //f0
};
public Win1253Model() : base(WIN1253__CHAR_TO_ORDER_MAP, "windows-1253")
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.XPath;
using System.Net;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Configuration;
using System.Diagnostics;
using System.Threading;
using System.Globalization;
using DDay.Update.Utilities;
using DDay.Update.Configuration;
namespace DDay.Update
{
public class UpdateManager
{
static private ILog log = new Log4NetLogger();
static string[] _CommandLineParameters = new string[0];
static private AutoResetEvent _UpdateEvent = new AutoResetEvent(false);
const string LocalDeploymentManifestFilename = "deployment.manifest";
const string LocalApplicationManifestFilename = "application.manifest";
const string BootstrapFolder = "Bootstrap";
const string BootstrapFilesExtension = "bootstrap";
#region Static Public Events
static public event EventHandler UpdateCompleted;
static public event EventHandler UpdateCancelled;
static public event EventHandler<ExceptionEventArgs> UpdateError;
#endregion
#region Static Private Fields
static private DeploymentManifest _DeploymentManifest;
static private DeploymentManifest _LocalDeploymentManifest;
static private IUpdateNotifier _UpdateNotifier = null;
#endregion
#region Static Public Properties
/// <summary>
/// Gets/sets the remote deployment manifest.
/// </summary>
public static DeploymentManifest DeploymentManifest
{
get { return UpdateManager._DeploymentManifest; }
set { UpdateManager._DeploymentManifest = value; }
}
/// <summary>
/// Gets/sets the local deployment manifest.
/// </summary>
public static DeploymentManifest LocalDeploymentManifest
{
get { return UpdateManager._LocalDeploymentManifest; }
set { UpdateManager._LocalDeploymentManifest = value; }
}
/// <summary>
/// The 'Company' specified in the current assembly.
/// </summary>
static private string _AssemblyCompany = null;
static public string AssemblyCompany
{
get
{
if (_AssemblyCompany == null)
{
Assembly currentAssembly = Assembly.GetEntryAssembly();
object[] attrs = currentAssembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);
if (attrs.Length > 0)
_AssemblyCompany = ((AssemblyCompanyAttribute)attrs[0]).Company;
else
_AssemblyCompany = string.Empty;
}
return _AssemblyCompany;
}
}
/// <summary>
/// The 'Product' specified in the current assembly.
/// </summary>
static private string _AssemblyProduct = null;
static public string AssemblyProduct
{
get
{
if (_AssemblyProduct == null)
{
Assembly currentAssembly = Assembly.GetEntryAssembly();
object[] attrs = currentAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), true);
if (attrs.Length > 0)
_AssemblyProduct = ((AssemblyProductAttribute)attrs[0]).Product;
else
_AssemblyProduct = Path.GetFileName(currentAssembly.Location);
}
return _AssemblyProduct;
}
}
/// <summary>
/// Gets the path to the base folder of the application. This folder should
/// contain the bootstrap (launcher) files and the deployment manifest.
/// </summary>
static public string BaseApplicationFolder
{
get
{
Assembly currentAssembly = Assembly.GetEntryAssembly();
string assemblyLocation = Path.GetDirectoryName(currentAssembly.Location);
string baseLocation = assemblyLocation;
while (!File.Exists(
Path.Combine(baseLocation, LocalDeploymentManifestFilename)))
{
string oldLocation = baseLocation;
baseLocation = Path.GetFullPath(Path.Combine(baseLocation, ".."));
if (!Directory.Exists(baseLocation) ||
oldLocation.Equals(baseLocation))
{
return assemblyLocation;
}
}
return baseLocation;
}
}
static public string VersionRepositoryFolder
{
get
{
DDayUpdateConfigurationSection cfg = ConfigurationManager.GetSection("DDay.Update")
as DDayUpdateConfigurationSection;
if (cfg != null &&
(
cfg.UseUserFolder ||
cfg.UsePublicFolder
))
{
string[] parts = new string[] { AssemblyCompany, AssemblyProduct };
string appDir = string.Join(Path.DirectorySeparatorChar.ToString(), parts);
string appData = Environment.GetFolderPath(
cfg.UseUserFolder ?
Environment.SpecialFolder.ApplicationData :
Environment.SpecialFolder.CommonApplicationData
);
string appPath = Path.Combine(appData, appDir);
if (!Directory.Exists(appPath))
Directory.CreateDirectory(appPath);
return appPath;
}
return BaseApplicationFolder;
}
}
/// <summary>
/// Gets the absolute path to the local deployment manifest.
/// </summary>
static public string LocalDeploymentManifestPath
{
get
{
return Path.Combine(VersionRepositoryFolder, LocalDeploymentManifestFilename);
}
}
/// <summary>
/// Gets the relative path to the entry point (executable) of
/// the current published version of the application.
/// </summary>
static public string ApplicationRelativePath
{
get
{
if (LocalDeploymentManifest != null)
{
return
Path.Combine(
LocalDeploymentManifest.CurrentPublishedVersion.ToString(),
LocalApplicationManifestFilename
);
}
return null;
}
}
/// <summary>
/// Gets the absolute path to the entry point (executable) of
/// the current published version of the application.
/// </summary>
static public string ApplicationPath
{
get
{
string relativePath = ApplicationRelativePath;
if (relativePath != null)
{
return
Path.Combine(
VersionRepositoryFolder,
relativePath
);
}
return null;
}
}
/// <summary>
/// Gets the relative path to the entry point (executable) of
/// the new version of the application.
/// </summary>
static public string ApplicationDestinationRelativePath
{
get
{
if (DeploymentManifest != null)
{
return
Path.Combine(
DeploymentManifest.CurrentPublishedVersion.ToString(),
LocalApplicationManifestFilename
);
}
return null;
}
}
/// <summary>
/// Gets the absolute path to the entry point (executable) of
/// the new version of the application.
/// </summary>
static public string ApplicationDestinationPath
{
get
{
string relativePath = ApplicationDestinationRelativePath;
if (relativePath != null)
{
return
Path.Combine(
VersionRepositoryFolder,
relativePath
);
}
return null;
}
}
#endregion
#region Static Protected Methods
static protected void OnUpdateCompleted()
{
if (UpdateCompleted != null)
UpdateCompleted(null, EventArgs.Empty);
}
static protected void OnUpdateCancelled()
{
if (UpdateCancelled != null)
UpdateCancelled(null, EventArgs.Empty);
}
static protected void OnUpdateError(Exception ex)
{
if (UpdateError != null)
UpdateError(null, new ExceptionEventArgs(ex));
}
#endregion
#region Static Public Methods
/// <summary>
/// Sets the command-line parameters that will be
/// passed to the target application.
/// </summary>
static public void SetCommandLineParameters(string[] parameters)
{
_CommandLineParameters = parameters;
}
/// <summary>
/// Determines if an update is available by downloading the
/// deployment manifest for the application and comparing
/// the current version vs. the most recent deployment
/// version found in the deployment manifest.
/// </summary>
/// <returns>True if an update is available, false otherwise.</returns>
static public bool IsUpdateAvailable(Uri uri) { return IsUpdateAvailable(uri, null, null, null); }
static public bool IsUpdateAvailable(Uri uri, string username, string password, string domain)
{
bool retval = false;
try
{
EnsureUpdateNotifier();
if (_UpdateNotifier != null)
_UpdateNotifier.BeginVersionCheck();
// Append the deployment manifest name to the end of the
// update uri, if it isn't already provided
if (!uri.AbsoluteUri.EndsWith(".application", true, CultureInfo.CurrentCulture))
{
string applicationName = Path.GetFileNameWithoutExtension(
Assembly.GetEntryAssembly().ManifestModule.Name) + ".application";
UriBuilder uriBuilder = new UriBuilder(uri.AbsoluteUri);
uriBuilder.Path = Path.Combine(uriBuilder.Path, applicationName);
uri = uriBuilder.Uri;
}
// Try to download a deployment manifest
DeploymentManifest = new DeploymentManifest(uri, username, password, domain);
// Get the local deployment manifest
LoadLocalDeploymentManifest();
// Determine if the local version is less than the server version
Version serverVersion = new Version(1, 0);
Version localVersion = new Version(0, 0);
log.Debug("Comparing versions...");
if (DeploymentManifest != null)
serverVersion = DeploymentManifest.CurrentPublishedVersion;
if (LocalDeploymentManifest != null)
localVersion = LocalDeploymentManifest.CurrentPublishedVersion;
log.Debug("Server version is: " + serverVersion);
log.Debug("Local version is: " + localVersion);
if (localVersion < serverVersion)
{
log.Debug("An update is available!");
// If the server version is newer than our local version,
// then an update is available!
retval = true;
return retval;
}
log.Debug("No update is necessary.");
}
catch (WebException ex)
{
string s = ex.Message;
}
catch (Exception)
{
// FIXME: log information on catch
}
finally
{
if (_UpdateNotifier != null)
_UpdateNotifier.EndVersionCheck(retval);
}
return retval;
}
/// <summary>
/// Performs a synchronous update of the application.
/// </summary>
/// <returns>True if an update was started, false otherwise.</returns>
static public bool Update()
{
return Update(false);
}
/// <summary>
/// Performs a synchronous update of the application.
/// </summary>
/// <param name="doQuietUpdate">
/// True if no user-intervention should be allowed,
/// false otherwise (defaults to false).
/// </param>
/// <returns>True if an update was started, false otherwise.</returns>
static public bool Update(bool doQuietUpdate)
{
try
{
Updater updater = new Updater();
updater.UpdateNotifier = _UpdateNotifier;
AutoResetEvent updateEvent = new AutoResetEvent(false);
bool updateSuccessful = true;
updater.Error += delegate(object sender, ExceptionEventArgs errorArgs)
{
// Indicate that the update did not succeed
updateSuccessful = false;
// Notify that an error occurred
OnUpdateError(errorArgs.Exception);
// Allow the method to exit
updateEvent.Set();
};
updater.Cancelled += delegate(object sender, EventArgs cancelArgs)
{
// Indicate that the update did not succeed
updateSuccessful = false;
// Notify that the update was cancelled
OnUpdateCancelled();
// Allow the method to exit
updateEvent.Set();
};
updater.Completed += delegate(object sender, EventArgs compArgs)
{
// If the update completed successfully,
// update the local manifest files
SaveLocalManifests();
// Remove previous versions of the application,
// if setup to do so
RemovePreviousVersions();
// Notify that the update has completed
OnUpdateCompleted();
// Allow the method to exit
updateEvent.Set();
};
// Start the update process, and get the initial result
bool initialUpdateResult = updater.Update(doQuietUpdate);
// Wait for the update process to complete
if (initialUpdateResult)
updateEvent.WaitOne();
return initialUpdateResult && updateSuccessful;
}
catch
{
return false;
}
}
/// <summary>
/// Performs an asynchronous update of the application.
/// </summary>
static public void UpdateAsync()
{
new Thread(new ThreadStart(delegate { Update(); })).Start();
}
/// <summary>
/// Performs an asynchronous update of the application.
/// </summary>
/// <param name="doQuietUpdate">
/// True if no user-intervention should be allowed,
/// false otherwise (defaults to false).
/// </param>
static public void UpdateAsync(bool doQuietUpdate)
{
ThreadStart starter = delegate { Update(doQuietUpdate); };
new Thread(starter).Start();
}
/// <summary>
/// Starts the application using the deployment and
/// application manifests.
/// </summary>
/// <exception cref="ApplicationRestartException">
/// If the application could not be started automatically
/// </exception>
static public void StartApplication()
{
log.Info("Starting application...");
// Get the current application manifest
ApplicationManifest appManifest = GetCurrentApplicationManifest();
// If there is enough information to restart the application, do it now!
if (appManifest != null &&
appManifest.EntryPoint != null)
{
// NOTE: using workingDir fixes bug #1955109 - Working Directory not set
string workingDir = Path.Combine(
VersionRepositoryFolder,
appManifest.AssemblyIdentity.Version.ToString()
);
log.Debug("Executing entry point...");
appManifest.EntryPoint.Run(
workingDir,
_CommandLineParameters);
log.Debug("Done.");
}
else
{
log.Error("The application manifest could not be loaded, or the entry point was missing or invalid.");
throw new ApplicationStartException();
}
}
/// <summary>
/// Updates bootstrap files. This should be called
/// as the first line of code in the main application.
/// </summary>
static public void UpdateBootstrapFiles()
{
Assembly currentAssembly = Assembly.GetEntryAssembly();
// Ensure we aren't running from the bootstrap application
if (!currentAssembly.FullName.Contains("DDay.Update.Bootstrap"))
{
DDayUpdateConfigurationSection cfg = ConfigurationManager.GetSection("DDay.Update")
as DDayUpdateConfigurationSection;
// Determine the name of the bootstrap files folder
string bootstrapFolderName = BootstrapFolder;
if (cfg != null &&
!string.IsNullOrEmpty(cfg.BootstrapFilesFolder))
bootstrapFolderName = cfg.BootstrapFilesFolder;
string assemblyLocation = Path.GetDirectoryName(currentAssembly.Location);
string assemblyName = Path.GetFileName(currentAssembly.Location);
string bootstrapFolder = Path.Combine(assemblyLocation, bootstrapFolderName);
string baseLocation = BaseApplicationFolder;
log.Debug("Looking for bootstrap folder at '" + bootstrapFolder + "'...");
// Ensure the bootstrap folder exists
if (Directory.Exists(bootstrapFolder))
{
log.Debug("Found bootstrap folder!");
try
{
// Find all files in the bootstrap folder
string[] files = Directory.GetFiles(bootstrapFolder);
foreach (string file in files)
{
// Determine the name of the destination file
string filename = Path.GetFileName(file);
if (filename.EndsWith(BootstrapFilesExtension))
filename = filename.Substring(filename.Length - BootstrapFilesExtension.Length);
// Determine the destination path...
string destFile = Path.Combine(baseLocation, filename);
log.Debug("File destination is: '" + destFile + "'");
// Rename the previous file, if it exists
if (File.Exists(destFile))
{
log.Debug("Renaming file '" + destFile + "' to '" + destFile + ".backup'...");
File.Move(destFile, destFile + ".backup");
}
log.Debug("Copying '" + file + "' to '" + destFile + "'...");
File.Copy(file, destFile);
// If we got this far OK, then delete the backup file!
if (File.Exists(destFile + ".backup"))
{
log.Debug("Deleting '" + destFile + ".backup'...");
File.Delete(destFile + ".backup");
}
}
// Delete each file in the bootstrap folder
foreach (string file in files)
File.Delete(file);
// Delete the bootstrap folder altogether
Directory.Delete(bootstrapFolder);
}
catch (Exception ex)
{
log.Error("An error occurred while updating the bootstrap files: " + ex.Message);
log.Debug("Restoring backup files...");
string[] files = Directory.GetFiles(baseLocation, "*.backup");
foreach (string file in files)
{
string destFile = file.Substring(0, file.Length - ".backup".Length);
if (File.Exists(destFile))
File.Move(destFile, destFile + ".old");
File.Move(file, destFile);
File.Delete(destFile + ".old");
}
}
}
else
{
log.Debug("The bootstrap folder could not be found.");
}
}
}
/// <summary>
/// Loads the deployment manifest, if it exists!
/// </summary>
static public void LoadLocalDeploymentManifest()
{
DeploymentManifest manifest = null;
log.Debug("Loading local deployment manifest...");
Assembly assembly = Assembly.GetExecutingAssembly();
string pathToManifest = Path.Combine(VersionRepositoryFolder, LocalDeploymentManifestFilename);
log.Debug("Checking for deployment manifest at '" + pathToManifest + "'...");
// Check if an application manifest exists at the specified location...
if (File.Exists(pathToManifest))
{
log.Debug("Local deployment manifest found.");
// Get the uri directory for the current assembly
string baseUri = Path.GetDirectoryName(assembly.CodeBase);
// Build a Uri to the manifest
UriBuilder uriBuilder = new UriBuilder(pathToManifest);
log.Debug("Loading deployment manifest...");
// Build an ApplicationManifest from the manifest file
manifest = new DeploymentManifest(uriBuilder.Uri);
}
else log.Warn("Manifest not found at '" + pathToManifest + "'.");
LocalDeploymentManifest = manifest;
}
static public ApplicationManifest GetCurrentApplicationManifest()
{
ApplicationManifest appManifest = null;
DDayUpdateConfigurationSection cfg = ConfigurationManager.GetSection("DDay.Update")
as DDayUpdateConfigurationSection;
// Try to load a local deployment manifest
if (LocalDeploymentManifest == null)
LoadLocalDeploymentManifest();
DeploymentManifest deploymentManifest = LocalDeploymentManifest ?? DeploymentManifest;
// Try to retrieve the application manifest from the
// deployment manifest.
if (deploymentManifest != null)
{
// Load the deployment manifest, if we haven't done so already!
log.Debug("Loading application manifest from deployment manifest...");
try
{
deploymentManifest.LoadApplicationManifest();
appManifest = deploymentManifest.ApplicationManifest;
log.Debug("Loaded.");
}
catch
{
}
}
// If we haven't found an application manifest yet, then let's try to load
// it from a previous version!
if (appManifest == null)
{
log.Debug("The application manifest could not be located; searching previous versions...");
if (cfg != null)
{
Version[] localVersions = cfg.VersionManager.LocalVersions;
if (localVersions.Length > 0)
{
for (int i = 0; i < localVersions.Length; i++)
{
log.Debug("Searching version '" + localVersions[i] + "'...");
// Try to load an application manifest
// from this version!
try
{
string directory = Path.Combine(VersionRepositoryFolder, localVersions[i].ToString());
Uri uri = new Uri(
Path.Combine(
directory,
LocalApplicationManifestFilename
)
);
log.Debug("Attempting to load manifest from '" + uri.AbsolutePath + "'...");
// Get the application manifest
appManifest = new ApplicationManifest(uri);
}
catch { }
// If we found an application manifest, then check to see
// if the application name matches our bootstrap executable
// name. If it doesn't, then we're looking at a version
// of a *different* application, and should ignore it!
if (appManifest.EntryPoint != null &&
appManifest.EntryPoint.AssemblyIdentity != null &&
appManifest.EntryPoint.AssemblyIdentity.Name != null)
{
string manifestName = appManifest.EntryPoint.AssemblyIdentity.Name;
string appName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
if (!object.Equals(manifestName, appName))
{
log.Debug("The application manifest for application '" + manifestName + "' was found and ignored (looking for '" + appName + "')");
appManifest = null;
}
}
// We found an application manifest that we can use!
if (appManifest != null)
{
log.Debug("Application manifest found!");
break;
}
}
}
}
}
return appManifest;
}
#endregion
#region Static Private Methods
/// <summary>
/// Tries to determine an update notifier via the configuration file.
/// </summary>
static private void EnsureUpdateNotifier()
{
DDayUpdateConfigurationSection cfg = ConfigurationManager.GetSection("DDay.Update")
as DDayUpdateConfigurationSection;
// Determine the update notifier that will be used to handle
// update GUI display.
if (cfg != null)
{
_UpdateNotifier = cfg.UpdateNotifier;
}
}
/// <summary>
/// Saves deployment and application manifests
/// to local directories for future reference.
/// </summary>
static private void SaveLocalManifests()
{
if (DeploymentManifest != null)
{
// Get the path where the application manifest should reside...
Assembly assembly = Assembly.GetExecutingAssembly();
// Load the application manifest
DeploymentManifest.LoadApplicationManifest();
// Save the local application manifest also
DeploymentManifest.ApplicationManifest.Save(ApplicationDestinationPath);
// Update information in the deployment manifest to reflect
// the new location of the application manifest.
foreach (DependentAssembly da in DeploymentManifest.DependentAssemblies)
{
// The deployment manifest should have a single dependent assembly -
// the application manifest
// Set new information about the application manifest
FileInfo fi = new FileInfo(Path.GetFullPath(ApplicationDestinationPath));
// Set the codebase for the application to the new version
// NOTE: this fixes bug #2001838 - deployment.manifest uses absolute paths
da.CodeBase = ApplicationDestinationRelativePath;
da.Size = fi.Length;
}
// Save the deployment manifest
DeploymentManifest.Save(LocalDeploymentManifestPath);
// Get a new local deployment manifest
LoadLocalDeploymentManifest();
}
}
/// <summary>
/// Removes previous versions of the application based
/// on the bootstrap's configuration settings.
/// </summary>
static private void RemovePreviousVersions()
{
DDayUpdateConfigurationSection cfg = ConfigurationManager.GetSection("DDay.Update")
as DDayUpdateConfigurationSection;
if (cfg != null)
{
if (cfg.KeepVersions != null &&
cfg.KeepVersions.HasValue)
{
int numToKeep = cfg.KeepVersions.Value;
if (numToKeep >= 0)
{
List<Version> versions = new List<Version>();
string[] dirs = Directory.GetDirectories(VersionRepositoryFolder);
foreach (string dir in dirs)
{
try
{
Version v = new Version(Path.GetFileName(dir));
versions.Add(v);
}
catch
{
}
}
// Sort the versions in descending order
versions.Sort(delegate(Version v1, Version v2)
{
return (v2.CompareTo(v1));
});
if (versions.Count > 1)
{
// Remove the current version from the list
// (always keep the current version)
versions.RemoveAt(0);
// Remove the versions we want to keep
// from the list
while (numToKeep-- > 0 &&
versions.Count > 0)
versions.RemoveAt(0);
// We are left with a list of versions
// that need to be removed. Remove them!
foreach (Version v in versions)
cfg.VersionManager.RemoveVersion(v);
}
}
}
if (cfg.RemovePriorToVersion != null)
{
// Get the maximum version that will
// be retained.
Version version = cfg.RemovePriorToVersion;
if (version != null)
{
List<Version> versions = new List<Version>();
string[] dirs = Directory.GetDirectories(VersionRepositoryFolder);
foreach (string dir in dirs)
{
try
{
// Get all versions that are less than
// the version provided
Version v = new Version(Path.GetFileName(dir));
if (v < version)
versions.Add(v);
}
catch
{
}
}
// Remove each previous version
foreach (Version v in versions)
cfg.VersionManager.RemoveVersion(v);
}
}
}
}
#endregion
}
}
| |
using Orleans.Configuration;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Utilities class for handling configuration.
/// </summary>
public static class ConfigUtilities
{
internal static void ParseAdditionalAssemblyDirectories(IDictionary<string, SearchOption> directories, XmlElement root)
{
foreach (var node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null)
{
continue;
}
else
{
if (!grandchild.HasAttribute("Path"))
throw new FormatException("Missing 'Path' attribute on Directory element.");
// default to recursive
var recursive = true;
if (grandchild.HasAttribute("IncludeSubFolders"))
{
if (!bool.TryParse(grandchild.Attributes["IncludeSubFolders"].Value, out recursive))
throw new FormatException("Attribute 'IncludeSubFolders' has invalid value.");
directories[grandchild.Attributes["Path"].Value] = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
}
}
}
}
internal static void ParseTelemetry(XmlElement root, TelemetryConfiguration telemetryConfiguration)
{
foreach (var node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null) continue;
if (!grandchild.LocalName.Equals("TelemetryConsumer"))
{
continue;
}
else
{
string typeName = grandchild.Attributes["Type"]?.Value;
string assemblyName = grandchild.Attributes["Assembly"]?.Value;
if (string.IsNullOrWhiteSpace(typeName))
throw new FormatException("Missing 'Type' attribute on TelemetryConsumer element.");
if (string.IsNullOrWhiteSpace(assemblyName))
throw new FormatException("Missing 'Assembly' attribute on TelemetryConsumer element.");
var args = grandchild.Attributes.OfType<XmlAttribute>().Where(a => a.LocalName != "Type" && a.LocalName != "Assembly")
.Select(x => new KeyValuePair<string, object>(x.Name, x.Value)).ToArray();
telemetryConfiguration.Add(typeName, assemblyName, args);
}
}
}
internal static bool TryParsePropagateActivityId(XmlElement root, string nodeName, out bool propagateActivityId)
{
//set default value to make compiler happy, progateActivityId is only used when this method return true
propagateActivityId = MessagingOptions.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID;
if (root.HasAttribute("PropagateActivityId"))
{
propagateActivityId = ParseBool(root.GetAttribute("PropagateActivityId"),
"Invalid boolean value for PropagateActivityId attribute on Tracing element for " + nodeName);
return true;
}
return false;
}
internal static void ParseStatistics(IStatisticsConfiguration config, XmlElement root, string nodeName)
{
if (root.HasAttribute("PerfCounterWriteInterval"))
{
config.StatisticsPerfCountersWriteInterval = ParseTimeSpan(root.GetAttribute("PerfCounterWriteInterval"),
"Invalid TimeSpan value for Statistics.PerfCounterWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("LogWriteInterval"))
{
config.StatisticsLogWriteInterval = ParseTimeSpan(root.GetAttribute("LogWriteInterval"),
"Invalid TimeSpan value for Statistics.LogWriteInterval attribute on Statistics element for " + nodeName);
}
if (root.HasAttribute("StatisticsCollectionLevel"))
{
config.StatisticsCollectionLevel = ConfigUtilities.ParseEnum<StatisticsLevel>(root.GetAttribute("StatisticsCollectionLevel"),
"Invalid value of for Statistics.StatisticsCollectionLevel attribute on Statistics element for " + nodeName);
}
}
internal static void ParseLimitValues(LimitManager limitManager, XmlElement root, string nodeName)
{
foreach (XmlNode node in root.ChildNodes)
{
var grandchild = node as XmlElement;
if (grandchild == null) continue;
if (grandchild.LocalName.Equals("Limit") && grandchild.HasAttribute("Name")
&& (grandchild.HasAttribute("SoftLimit") || grandchild.HasAttribute("HardLimit")))
{
var limitName = grandchild.GetAttribute("Name");
limitManager.AddLimitValue(limitName, new LimitValue
{
Name = limitName,
SoftLimitThreshold = ParseInt(grandchild.GetAttribute("SoftLimit"),
"Invalid integer value for the SoftLimit attribute on the Limit element"),
HardLimitThreshold = grandchild.HasAttribute("HardLimit") ? ParseInt(grandchild.GetAttribute("HardLimit"),
"Invalid integer value for the HardLimit attribute on the Limit element") : 0,
});
}
}
}
internal static int ParseInt(string input, string errorMessage)
{
int p;
if (!Int32.TryParse(input, out p))
{
throw new FormatException(errorMessage);
}
return p;
}
internal static long ParseLong(string input, string errorMessage)
{
long p;
if (!Int64.TryParse(input, out p))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static bool ParseBool(string input, string errorMessage)
{
bool p;
if (Boolean.TryParse(input, out p)) return p;
switch (input)
{
case "0":
p = false;
break;
case "1":
p = true;
break;
default:
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static double ParseDouble(string input, string errorMessage)
{
double p;
if (!Double.TryParse(input, out p))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return p;
}
internal static Guid ParseGuid(string input, string errorMessage)
{
Guid p;
if (!Guid.TryParse(input, out p))
{
throw new FormatException(errorMessage);
}
return p;
}
internal static Type ParseFullyQualifiedType(string input, string errorMessage)
{
Type returnValue;
try
{
returnValue = Type.GetType(input);
}
catch (Exception e)
{
throw new FormatException(errorMessage, e);
}
if (returnValue == null)
{
throw new FormatException(errorMessage);
}
return returnValue;
}
internal static void ValidateSerializationProvider(TypeInfo type)
{
if (type.IsClass == false)
{
throw new FormatException(string.Format("The serialization provider type {0} was not a class", type.FullName));
}
if (type.IsAbstract)
{
throw new FormatException(string.Format("The serialization provider type {0} was an abstract class", type.FullName));
}
if (type.IsPublic == false)
{
throw new FormatException(string.Format("The serialization provider type {0} is not public", type.FullName));
}
if (type.IsGenericType && type.IsConstructedGenericType() == false)
{
throw new FormatException(string.Format("The serialization provider type {0} is generic and has a missing type parameter specification", type.FullName));
}
var constructor = type.GetConstructor(Type.EmptyTypes);
if (constructor == null)
{
throw new FormatException(string.Format("The serialization provider type {0} does not have a parameterless constructor", type.FullName));
}
if (constructor.IsPublic == false)
{
throw new FormatException(string.Format("The serialization provider type {0} has a non-public parameterless constructor", type.FullName));
}
}
// Time spans are entered as a string of decimal digits, optionally followed by a unit string: "ms", "s", "m", "hr"
internal static TimeSpan ParseTimeSpan(string input, string errorMessage)
{
long unitSize;
string numberInput;
var trimmedInput = input.Trim().ToLowerInvariant();
if (trimmedInput.EndsWith("ms", StringComparison.Ordinal))
{
unitSize = 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else if (trimmedInput.EndsWith("s", StringComparison.Ordinal))
{
unitSize = 1000 * 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("m", StringComparison.Ordinal))
{
unitSize = 60 * 1000 * 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("hr", StringComparison.Ordinal))
{
unitSize = 60 * 60 * 1000 * 10000L;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else
{
unitSize = 1000 * 10000; // Default is seconds
numberInput = trimmedInput;
}
decimal rawTimeSpan;
if (!decimal.TryParse(numberInput, NumberStyles.Any, CultureInfo.InvariantCulture, out rawTimeSpan))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return TimeSpan.FromTicks((long)(rawTimeSpan * unitSize));
}
internal static string ToParseableTimeSpan(TimeSpan input)
{
return $"{input.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)}ms";
}
internal static byte[] ParseSubnet(string input, string errorMessage)
{
return string.IsNullOrEmpty(input) ? null : input.Split('.').Select(s => (byte)ParseInt(s, errorMessage)).ToArray();
}
internal static T ParseEnum<T>(string input, string errorMessage)
where T : struct // really, where T : enum, but there's no way to require that in C#
{
T s;
if (!Enum.TryParse<T>(input, out s))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return s;
}
internal static Severity ParseSeverity(string input, string errorMessage)
{
Severity s;
if (!Enum.TryParse<Severity>(input, out s))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return s;
}
internal static async Task<IPEndPoint> ParseIPEndPoint(XmlElement root, byte[] subnet = null)
{
if (!root.HasAttribute("Address")) throw new FormatException("Missing Address attribute for " + root.LocalName + " element");
if (!root.HasAttribute("Port")) throw new FormatException("Missing Port attribute for " + root.LocalName + " element");
var family = AddressFamily.InterNetwork;
if (root.HasAttribute("Subnet"))
{
subnet = ParseSubnet(root.GetAttribute("Subnet"), "Invalid subnet");
}
if (root.HasAttribute("PreferredFamily"))
{
family = ParseEnum<AddressFamily>(root.GetAttribute("PreferredFamily"),
"Invalid preferred addressing family for " + root.LocalName + " element");
}
IPAddress addr = await ResolveIPAddress(root.GetAttribute("Address"), subnet, family);
int port = ParseInt(root.GetAttribute("Port"), "Invalid Port attribute for " + root.LocalName + " element");
return new IPEndPoint(addr, port);
}
internal static async Task<IPAddress> ResolveIPAddress(string addrOrHost, byte[] subnet, AddressFamily family)
{
var loopback = family == AddressFamily.InterNetwork ? IPAddress.Loopback : IPAddress.IPv6Loopback;
IList<IPAddress> nodeIps;
// if the address is an empty string, just enumerate all ip addresses available
// on this node
if (string.IsNullOrEmpty(addrOrHost))
{
nodeIps = NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(iface => iface.GetIPProperties().UnicastAddresses)
.Select(addr => addr.Address)
.Where(addr => addr.AddressFamily == family && !IPAddress.IsLoopback(addr))
.ToList();
}
else
{
// Fix StreamFilteringTests_SMS tests
if (addrOrHost.Equals("loopback", StringComparison.OrdinalIgnoreCase))
{
return loopback;
}
// check if addrOrHost is a valid IP address including loopback (127.0.0.0/8, ::1) and any (0.0.0.0/0, ::) addresses
IPAddress address;
if (IPAddress.TryParse(addrOrHost, out address))
{
return address;
}
// Get IP address from DNS. If addrOrHost is localhost will
// return loopback IPv4 address (or IPv4 and IPv6 addresses if OS is supported IPv6)
nodeIps = await Dns.GetHostAddressesAsync(addrOrHost);
}
var candidates = new List<IPAddress>();
foreach (var nodeIp in nodeIps.Where(x => x.AddressFamily == family))
{
// If the subnet does not match - we can't resolve this address.
// If subnet is not specified - pick smallest address deterministically.
if (subnet == null)
{
candidates.Add(nodeIp);
}
else
{
var ip = nodeIp;
if (subnet.Select((b, i) => ip.GetAddressBytes()[i] == b).All(x => x))
{
candidates.Add(nodeIp);
}
}
}
if (candidates.Count > 0)
{
return PickIPAddress(candidates);
}
var subnetStr = Utils.EnumerableToString(subnet, null, ".", false);
throw new ArgumentException("Hostname '" + addrOrHost + "' with subnet " + subnetStr + " and family " + family + " is not a valid IP address or DNS name");
}
internal static IPAddress PickIPAddress(IReadOnlyList<IPAddress> candidates)
{
IPAddress chosen = null;
foreach (IPAddress addr in candidates)
{
if (chosen == null)
{
chosen = addr;
}
else
{
if (CompareIPAddresses(addr, chosen)) // pick smallest address deterministically
chosen = addr;
}
}
return chosen;
}
/// <summary>
/// Gets the address of the local server.
/// If there are multiple addresses in the correct family in the server's DNS record, the first will be returned.
/// </summary>
/// <returns>The server's IPv4 address.</returns>
internal static IPAddress GetLocalIPAddress(AddressFamily family = AddressFamily.InterNetwork, string interfaceName = null)
{
var loopback = (family == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback;
// get list of all network interfaces
NetworkInterface[] netInterfaces = NetworkInterface.GetAllNetworkInterfaces();
var candidates = new List<IPAddress>();
// loop through interfaces
for (int i = 0; i < netInterfaces.Length; i++)
{
NetworkInterface netInterface = netInterfaces[i];
if (netInterface.OperationalStatus != OperationalStatus.Up)
{
// Skip network interfaces that are not operational
continue;
}
if (!string.IsNullOrWhiteSpace(interfaceName) &&
!netInterface.Name.StartsWith(interfaceName, StringComparison.Ordinal)) continue;
bool isLoopbackInterface = (netInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback);
// get list of all unicast IPs from current interface
UnicastIPAddressInformationCollection ipAddresses = netInterface.GetIPProperties().UnicastAddresses;
// loop through IP address collection
foreach (UnicastIPAddressInformation ip in ipAddresses)
{
if (ip.Address.AddressFamily == family) // Picking the first address of the requested family for now. Will need to revisit later
{
//don't pick loopback address, unless we were asked for a loopback interface
if (!(isLoopbackInterface && ip.Address.Equals(loopback)))
{
candidates.Add(ip.Address); // collect all candidates.
}
}
}
}
if (candidates.Count > 0) return PickIPAddress(candidates);
throw new OrleansException("Failed to get a local IP address.");
}
internal static string IStatisticsConfigurationToString(IStatisticsConfiguration config)
{
var sb = new StringBuilder();
sb.Append(" Statistics: ").AppendLine();
sb.Append(" PerfCounterWriteInterval: ").Append(config.StatisticsPerfCountersWriteInterval).AppendLine();
sb.Append(" LogWriteInterval: ").Append(config.StatisticsLogWriteInterval).AppendLine();
sb.Append(" StatisticsCollectionLevel: ").Append(config.StatisticsCollectionLevel).AppendLine();
#if TRACK_DETAILED_STATS
sb.Append(" TRACK_DETAILED_STATS: true").AppendLine();
#endif
return sb.ToString();
}
/// <summary>
/// Prints the the DataConnectionString,
/// without disclosing any credential info
/// such as the Azure Storage AccountKey, SqlServer password or AWS SecretKey.
/// </summary>
/// <param name="connectionString">The connection string to print.</param>
/// <returns>The string representation of the DataConnectionString with account credential info redacted.</returns>
public static string RedactConnectionStringInfo(string connectionString)
{
string[] secretKeys =
{
"AccountKey=", // Azure Storage
"SharedAccessSignature=", // Many Azure services
"SharedAccessKey=", "SharedSecretValue=", // ServiceBus
"Password=", // SQL
"SecretKey=", "SessionToken=", // DynamoDb
};
var mark = "<--SNIP-->";
if (String.IsNullOrEmpty(connectionString)) return "null";
//if connection string format doesn't contain any secretKey, then return just <--SNIP-->
if (!secretKeys.Any(key => connectionString.Contains(key))) return mark;
string connectionInfo = connectionString;
// Remove any secret keys from connection string info written to log files
foreach (var secretKey in secretKeys)
{
int keyPos = connectionInfo.IndexOf(secretKey, StringComparison.OrdinalIgnoreCase);
if (keyPos >= 0)
{
connectionInfo = connectionInfo.Remove(keyPos + secretKey.Length) + mark;
}
}
return connectionInfo;
}
public static TimeSpan ParseCollectionAgeLimit(XmlElement xmlElement)
{
if (xmlElement.LocalName != "Deactivation")
throw new ArgumentException("The XML element must be a <Deactivate/> element.");
if (!xmlElement.HasAttribute("AgeLimit"))
throw new ArgumentException("The AgeLimit attribute is required for a <Deactivate/> element.");
return ParseTimeSpan(xmlElement.GetAttribute("AgeLimit"), "Invalid TimeSpan value for Deactivation.AgeLimit");
}
private static readonly string[] defaultClientConfigFileNames = { "ClientConfiguration.xml", "OrleansClientConfiguration.xml", "Client.config", "Client.xml" };
private static readonly string[] defaultSiloConfigFileNames = { "OrleansConfiguration.xml", "orleans.config", "config.xml", "orleans.config.xml" };
private static readonly string[] defaultConfigDirs =
{
null, // Will be filled in with directory location for this executing assembly
"approot", // Azure AppRoot directory
".", // Current directory
".." // Parent directory
};
public static string FindConfigFile(bool isSilo)
{
// Add directory containing Orleans binaries to the search locations for config files
defaultConfigDirs[0] = Path.GetDirectoryName(typeof(ConfigUtilities).GetTypeInfo().Assembly.Location);
var notFound = new List<string>();
foreach (string dir in defaultConfigDirs)
{
foreach (string file in isSilo ? defaultSiloConfigFileNames : defaultClientConfigFileNames)
{
var fileName = Path.GetFullPath(Path.Combine(dir, file));
if (File.Exists(fileName)) return fileName;
notFound.Add(fileName);
}
}
var whereWeLooked = new StringBuilder();
whereWeLooked.AppendFormat("Cannot locate Orleans {0} config file.", isSilo ? "silo" : "client").AppendLine();
whereWeLooked.AppendLine("Searched locations:");
foreach (var i in notFound)
{
whereWeLooked.AppendFormat("\t- {0}", i).AppendLine();
}
throw new FileNotFoundException(whereWeLooked.ToString());
}
/// <summary>
/// Returns the Runtime Version information.
/// </summary>
/// <returns>the Runtime Version information</returns>
public static string RuntimeVersionInfo()
{
var sb = new StringBuilder();
sb.Append(" Orleans version: ").AppendLine(RuntimeVersion.Current);
sb.Append(" .NET version: ").AppendLine(Environment.Version.ToString());
sb.Append(" OS version: ").AppendLine(Environment.OSVersion.ToString());
#if BUILD_FLAVOR_LEGACY
sb.Append(" App config file: ").AppendLine(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
#endif
sb.AppendFormat(" GC Type={0} GCLatencyMode={1}",
GCSettings.IsServerGC ? "Server" : "Client",
Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode))
.AppendLine();
return sb.ToString();
}
// returns true if lhs is "less" (in some repeatable sense) than rhs
private static bool CompareIPAddresses(IPAddress lhs, IPAddress rhs)
{
byte[] lbytes = lhs.GetAddressBytes();
byte[] rbytes = rhs.GetAddressBytes();
if (lbytes.Length != rbytes.Length) return lbytes.Length < rbytes.Length;
// compare starting from most significant octet.
// 10.68.20.21 < 10.98.05.04
for (int i = 0; i < lbytes.Length; i++)
{
if (lbytes[i] != rbytes[i])
{
return lbytes[i] < rbytes[i];
}
}
// They're equal
return false;
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or 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;
using System.Data;
using System.Data.Common;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Dao;
using Spring.Threading;
namespace Spring.Data.Common
{
/// <summary>
/// Test for MultiDelegatingDbProvider
/// </summary>
/// <author>Mark Pollack (.NET)</author>
[TestFixture]
public class MultiDelegatingDbProviderTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CreationWhenNoRequiredPropertiesSet()
{
MultiDelegatingDbProvider dbProvider = new MultiDelegatingDbProvider();
dbProvider.AfterPropertiesSet();
}
[Test]
public void CreationWithWrongTypeDictionaryKeys()
{
try
{
MultiDelegatingDbProvider dbProvider = new MultiDelegatingDbProvider();
IDictionary targetDbProviders = new Hashtable();
targetDbProviders.Add(1, "bar");
dbProvider.TargetDbProviders = targetDbProviders;
dbProvider.AfterPropertiesSet();
Assert.Fail("Should have thrown ArgumentException");
}
catch (ArgumentException ex)
{
Assert.AreEqual("Key identifying target IDbProvider in TargetDbProviders dictionary property is required to be of type string. Key = [1], type = [System.Int32]", ex.Message);
}
}
[Test]
public void CreationWithWrongTypeDictionaryValues()
{
try
{
IDictionary targetDbProviders = new Hashtable();
targetDbProviders.Add("foo", 1);
//Exercise the constructor
MultiDelegatingDbProvider dbProvider = new MultiDelegatingDbProvider(targetDbProviders);
dbProvider.AfterPropertiesSet();
Assert.Fail("Should have thrown ArgumentException");
}
catch (ArgumentException ex)
{
Assert.AreEqual("Value in TargetDbProviders dictionary is not of type IDbProvider. Type = [System.Int32]", ex.Message);
}
}
[Test]
public void NoDefaultProvided()
{
IDbProvider provider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
provider.ConnectionString = "connString1";
MultiDelegatingDbProvider multiDbProvider = new MultiDelegatingDbProvider();
IDictionary targetDbProviders = new Hashtable();
targetDbProviders.Add("db1", provider);
multiDbProvider.TargetDbProviders = targetDbProviders;
multiDbProvider.AfterPropertiesSet();
try
{
Assert.AreEqual("connString1", multiDbProvider.ConnectionString);
Assert.Fail("InvalidDataAccessApiUsageException should have been thrown");
}
catch (InvalidDataAccessApiUsageException exception)
{
Assert.AreEqual("No provider name found in thread local storage. Consider setting the property DefaultDbProvider to fallback to a default value.", exception.Message);
}
finally
{
LogicalThreadContext.FreeNamedDataSlot(MultiDelegatingDbProvider.CURRENT_DBPROVIDER_SLOTNAME);
}
}
[Test]
public void NoMatchingProviderDefinedInThreadLocalStorage()
{
IDbProvider provider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
provider.ConnectionString = "connString1";
MultiDelegatingDbProvider multiDbProvider = new MultiDelegatingDbProvider();
IDictionary targetDbProviders = new Hashtable();
targetDbProviders.Add("db1", provider);
multiDbProvider.TargetDbProviders = targetDbProviders;
multiDbProvider.AfterPropertiesSet();
try
{
MultiDelegatingDbProvider.CurrentDbProviderName = "db2";
Assert.AreEqual("connString1", multiDbProvider.ConnectionString);
Assert.Fail("InvalidDataAccessApiUsageException should have been thrown");
}
catch (InvalidDataAccessApiUsageException exception)
{
Assert.AreEqual("'db2' was not under the thread local key 'dbProviderName' and no default IDbProvider was set.", exception.Message);
}
finally
{
LogicalThreadContext.FreeNamedDataSlot(MultiDelegatingDbProvider.CURRENT_DBPROVIDER_SLOTNAME);
}
}
[Test]
public void MatchingProviderDefinedInThreadLocalStorage()
{
IDbProvider provider1 = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
provider1.ConnectionString = "connString1";
IDbProvider provider2 = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
provider2.ConnectionString = "connString2";
MultiDelegatingDbProvider multiDbProvider = new MultiDelegatingDbProvider();
IDictionary targetDbProviders = new Hashtable();
targetDbProviders.Add("db1", provider1);
targetDbProviders.Add("db2", provider2);
multiDbProvider.DefaultDbProvider = provider1;
multiDbProvider.TargetDbProviders = targetDbProviders;
multiDbProvider.AfterPropertiesSet();
//an aside, set setter for connection string
multiDbProvider.ConnectionString = "connString1Reset";
Assert.AreEqual("connString1Reset", multiDbProvider.ConnectionString);
MultiDelegatingDbProvider.CurrentDbProviderName = "db2";
try
{
Assert.AreEqual("connString2", multiDbProvider.ConnectionString);
}
finally
{
LogicalThreadContext.FreeNamedDataSlot(MultiDelegatingDbProvider.CURRENT_DBPROVIDER_SLOTNAME);
}
}
[Test]
public void FallbackToDefault()
{
IDbProvider provider1 = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
provider1.ConnectionString = "connString1";
IDbProvider provider2 = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
provider2.ConnectionString = "connString2";
MultiDelegatingDbProvider multiDbProvider = new MultiDelegatingDbProvider();
IDictionary targetDbProviders = new Hashtable();
targetDbProviders.Add("db1", provider1);
targetDbProviders.Add("db2", provider2);
multiDbProvider.DefaultDbProvider = provider1;
multiDbProvider.TargetDbProviders = targetDbProviders;
multiDbProvider.AfterPropertiesSet();
MultiDelegatingDbProvider.CurrentDbProviderName = "db314";
try
{
Assert.AreEqual("connString1", multiDbProvider.ConnectionString);
}
finally
{
LogicalThreadContext.FreeNamedDataSlot(MultiDelegatingDbProvider.CURRENT_DBPROVIDER_SLOTNAME);
}
}
[Test]
public void CreateOperations()
{
IDbProvider dbProvider = (IDbProvider)mocks.CreateMock(typeof(IDbProvider));
IDbConnection mockConnection = (IDbConnection)mocks.CreateMock(typeof(IDbConnection));
Expect.Call(dbProvider.CreateConnection()).Return(mockConnection).Repeat.Once();
IDbCommand mockCommand = (IDbCommand)mocks.CreateMock(typeof(IDbCommand));
Expect.Call(dbProvider.CreateCommand()).Return(mockCommand).Repeat.Once();
IDbDataParameter mockParameter = (IDbDataParameter) mocks.CreateMock(typeof (IDbDataParameter));
Expect.Call(dbProvider.CreateParameter()).Return(mockParameter).Repeat.Once();
IDbDataAdapter mockDataAdapter = (IDbDataAdapter) mocks.CreateMock(typeof (IDbDataAdapter));
Expect.Call(dbProvider.CreateDataAdapter()).Return(mockDataAdapter).Repeat.Once();
#if !NET_1_1
DbCommandBuilder mockDbCommandBuilder = (DbCommandBuilder) mocks.CreateMock(typeof (DbCommandBuilder));
Expect.Call(dbProvider.CreateCommandBuilder()).Return(mockDbCommandBuilder).Repeat.Once();
#endif
Expect.Call(dbProvider.CreateParameterName("p1")).Return("@p1").Repeat.Once();
Expect.Call(dbProvider.CreateParameterNameForCollection("c1")).Return("cc1");
IDbMetadata mockDbMetaData = (IDbMetadata) mocks.CreateMock(typeof (IDbMetadata));
Expect.Call(dbProvider.DbMetadata).Return(mockDbMetaData);
Exception e = new Exception("foo");
Expect.Call(dbProvider.ExtractError(e)).Return("badsql").Repeat.Once();
#if !NET_1_1
DbException dbException = (DbException) mocks.CreateMock(typeof (DbException));
#endif
MultiDelegatingDbProvider multiDbProvider = new MultiDelegatingDbProvider();
IDictionary targetDbProviders = new Hashtable();
targetDbProviders.Add("db1", dbProvider);
multiDbProvider.DefaultDbProvider = dbProvider;
multiDbProvider.TargetDbProviders = targetDbProviders;
multiDbProvider.AfterPropertiesSet();
mocks.ReplayAll();
Assert.IsNotNull(multiDbProvider.CreateConnection());
Assert.IsNotNull(multiDbProvider.CreateCommand());
Assert.IsNotNull(multiDbProvider.CreateParameter());
Assert.IsNotNull(multiDbProvider.CreateDataAdapter());
#if !NET_1_1
Assert.IsNotNull(multiDbProvider.CreateCommandBuilder() as DbCommandBuilder);
#endif
Assert.AreEqual("@p1", multiDbProvider.CreateParameterName("p1"));
Assert.AreEqual("cc1", multiDbProvider.CreateParameterNameForCollection("c1"));
Assert.IsNotNull(multiDbProvider.DbMetadata);
Assert.AreEqual("badsql", multiDbProvider.ExtractError(e));
#if !NET_1_1
Assert.IsTrue(multiDbProvider.IsDataAccessException(dbException));
#endif
Assert.IsFalse(multiDbProvider.IsDataAccessException(e));
mocks.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Mono.Cecil.Rocks;
namespace N {
/// <summary>
/// ID string generated is "T:N.X".
/// </summary>
public class X : IX<KVP<string, int>> {
/// <summary>
/// ID string generated is "M:N.X.#ctor".
/// </summary>
public X () { }
/// <summary>
/// ID string generated is "M:N.X.#ctor(System.Int32)".
/// </summary>
/// <param name="i">Describe parameter.</param>
public X (int i) { }
/// <summary>
/// ID string generated is "F:N.X.q".
/// </summary>
public string q;
/// <summary>
/// ID string generated is "F:N.X.PI".
/// </summary>
public const double PI = 3.14;
/// <summary>
/// ID string generated is "M:N.X.f".
/// </summary>
public int f () { return 1; }
/// <summary>
/// ID string generated is "M:N.X.bb(System.String,System.Int32@)".
/// </summary>
public int bb (string s, ref int y) { return 1; }
/// <summary>
/// ID string generated is "M:N.X.gg(System.Int16[],System.Int32[0:,0:])".
/// </summary>
public int gg (short [] array1, int [,] array) { return 0; }
/// <summary>
/// ID string generated is "M:N.X.op_Addition(N.X,N.X)".
/// </summary>
public static X operator + (X x, X xx) { return x; }
/// <summary>
/// ID string generated is "P:N.X.prop".
/// </summary>
public int prop { get { return 1; } set { } }
/// <summary>
/// ID string generated is "E:N.X.d".
/// </summary>
#pragma warning disable 67
public event D d;
#pragma warning restore 67
/// <summary>
/// ID string generated is "P:N.X.Item(System.String)".
/// </summary>
public int this [string s] { get { return 1; } }
/// <summary>
/// ID string generated is "T:N.X.Nested".
/// </summary>
public class Nested { }
/// <summary>
/// ID string generated is "T:N.X.D".
/// </summary>
public delegate void D (int i);
/// <summary>
/// ID string generated is "M:N.X.op_Explicit(N.X)~System.Int32".
/// </summary>
public static explicit operator int (X x) { return 1; }
public static void Linq (IEnumerable<string> enumerable, Func<string> selector)
{
}
/// <summary>
/// ID string generated is "M:N.X.N#IX{N#KVP{System#String,System#Int32}}#IXA(N.KVP{System.String,System.Int32})"
/// </summary>
void IX<KVP<string, int>>.IXA (KVP<string, int> k) { }
}
public interface IX<K> {
void IXA (K k);
}
public class KVP<K, T> { }
public class GenericMethod {
/// <summary>
/// ID string generated is "M:N.GenericMethod.WithNestedType``1(N.GenericType{``0}.NestedType)".
/// </summary>
public void WithNestedType<T> (GenericType<T>.NestedType nestedType) { }
/// <summary>
/// ID string generated is "M:N.GenericMethod.WithIntOfNestedType``1(N.GenericType{System.Int32}.NestedType)".
/// </summary>
public void WithIntOfNestedType<T> (GenericType<int>.NestedType nestedType) { }
/// <summary>
/// ID string generated is "M:N.GenericMethod.WithNestedGenericType``1(N.GenericType{``0}.NestedGenericType{``0}.NestedType)".
/// </summary>
public void WithNestedGenericType<T> (GenericType<T>.NestedGenericType<T>.NestedType nestedType) { }
/// <summary>
/// ID string generated is "M:N.GenericMethod.WithIntOfNestedGenericType``1(N.GenericType{System.Int32}.NestedGenericType{System.Int32}.NestedType)".
/// </summary>
public void WithIntOfNestedGenericType<T> (GenericType<int>.NestedGenericType<int>.NestedType nestedType) { }
/// <summary>
/// ID string generated is "M:N.GenericMethod.WithMultipleTypeParameterAndNestedGenericType``2(N.GenericType{``0}.NestedGenericType{``1}.NestedType)".
/// </summary>
public void WithMultipleTypeParameterAndNestedGenericType<T1, T2> (GenericType<T1>.NestedGenericType<T2>.NestedType nestedType) { }
/// <summary>
/// ID string generated is "M:N.GenericMethod.WithMultipleTypeParameterAndIntOfNestedGenericType``2(N.GenericType{System.Int32}.NestedGenericType{System.Int32}.NestedType)".
/// </summary>
public void WithMultipleTypeParameterAndIntOfNestedGenericType<T1, T2> (GenericType<int>.NestedGenericType<int>.NestedType nestedType) { }
}
public class GenericType<T> {
public class NestedType { }
public class NestedGenericType<TNested> {
public class NestedType { }
/// <summary>
/// ID string generated is "M:N.GenericType`1.NestedGenericType`1.WithTypeParameterOfGenericMethod``1(System.Collections.Generic.List{``0})"
/// </summary>
public void WithTypeParameterOfGenericMethod<TMethod> (List<TMethod> list) { }
/// <summary>
/// ID string generated is "M:N.GenericType`1.NestedGenericType`1.WithTypeParameterOfGenericType(System.Collections.Generic.Dictionary{`0,`1})"
/// </summary>
public void WithTypeParameterOfGenericType (Dictionary<T, TNested> dict) { }
/// <summary>
/// ID string generated is "M:N.GenericType`1.NestedGenericType`1.WithTypeParameterOfGenericType``1(System.Collections.Generic.List{`1})"
/// </summary>
public void WithTypeParameterOfNestedGenericType<TMethod> (List<TNested> list) { }
/// <summary>
/// ID string generated is "M:N.GenericType`1.NestedGenericType`1.WithTypeParameterOfGenericTypeAndGenericMethod``1(System.Collections.Generic.Dictionary{`1,``0})"
/// </summary>
public void WithTypeParameterOfGenericTypeAndGenericMethod<TMethod> (Dictionary<TNested, TMethod> dict) { }
}
}
}
namespace Mono.Cecil.Tests {
[TestFixture]
public class DocCommentIdTests {
[Test]
public void TypeDef ()
{
AssertDocumentID ("T:N.X", GetTestType ());
}
[Test]
public void ParameterlessCtor ()
{
var type = GetTestType ();
var ctor = type.GetConstructors ().Single (m => m.Parameters.Count == 0);
AssertDocumentID ("M:N.X.#ctor", ctor);
}
[Test]
public void CtorWithParameters ()
{
var type = GetTestType ();
var ctor = type.GetConstructors ().Single (m => m.Parameters.Count == 1);
AssertDocumentID ("M:N.X.#ctor(System.Int32)", ctor);
}
[Test]
public void Field ()
{
var type = GetTestType ();
var field = type.Fields.Single (m => m.Name == "q");
AssertDocumentID ("F:N.X.q", field);
}
[Test]
public void ConstField ()
{
var type = GetTestType ();
var field = type.Fields.Single (m => m.Name == "PI");
AssertDocumentID ("F:N.X.PI", field);
}
[Test]
public void ParameterlessMethod ()
{
var type = GetTestType ();
var method = type.Methods.Single (m => m.Name == "f");
AssertDocumentID ("M:N.X.f", method);
}
[Test]
public void MethodWithByRefParameters ()
{
var type = GetTestType ();
var method = type.Methods.Single (m => m.Name == "bb");
AssertDocumentID ("M:N.X.bb(System.String,System.Int32@)", method);
}
[Test]
public void MethodWithArrayParameters ()
{
var type = GetTestType ();
var method = type.Methods.Single (m => m.Name == "gg");
AssertDocumentID ("M:N.X.gg(System.Int16[],System.Int32[0:,0:])", method);
}
[TestCase ("WithNestedType", "WithNestedType``1(N.GenericType{``0}.NestedType)")]
[TestCase ("WithIntOfNestedType", "WithIntOfNestedType``1(N.GenericType{System.Int32}.NestedType)")]
[TestCase ("WithNestedGenericType", "WithNestedGenericType``1(N.GenericType{``0}.NestedGenericType{``0}.NestedType)")]
[TestCase ("WithIntOfNestedGenericType", "WithIntOfNestedGenericType``1(N.GenericType{System.Int32}.NestedGenericType{System.Int32}.NestedType)")]
[TestCase ("WithMultipleTypeParameterAndNestedGenericType", "WithMultipleTypeParameterAndNestedGenericType``2(N.GenericType{``0}.NestedGenericType{``1}.NestedType)")]
[TestCase ("WithMultipleTypeParameterAndIntOfNestedGenericType", "WithMultipleTypeParameterAndIntOfNestedGenericType``2(N.GenericType{System.Int32}.NestedGenericType{System.Int32}.NestedType)")]
public void GenericMethodWithNestedTypeParameters (string methodName, string docCommentId)
{
var type = GetTestType (typeof (N.GenericMethod));
var method = type.Methods.Single (m => m.Name == methodName);
AssertDocumentID ($"M:N.GenericMethod.{docCommentId}", method);
}
[TestCase ("WithTypeParameterOfGenericMethod", "WithTypeParameterOfGenericMethod``1(System.Collections.Generic.List{``0})")]
[TestCase ("WithTypeParameterOfGenericType", "WithTypeParameterOfGenericType(System.Collections.Generic.Dictionary{`0,`1})")]
[TestCase ("WithTypeParameterOfNestedGenericType", "WithTypeParameterOfNestedGenericType``1(System.Collections.Generic.List{`1})")]
[TestCase ("WithTypeParameterOfGenericTypeAndGenericMethod", "WithTypeParameterOfGenericTypeAndGenericMethod``1(System.Collections.Generic.Dictionary{`1,``0})")]
public void GenericTypeWithTypeParameters (string methodName, string docCommentId)
{
var type = GetTestType (typeof (N.GenericType<>.NestedGenericType<>));
var method = type.Methods.Single (m => m.Name == methodName);
AssertDocumentID ($"M:N.GenericType`1.NestedGenericType`1.{docCommentId}", method);
}
[Test]
public void OpAddition ()
{
var type = GetTestType ();
var op = type.Methods.Single (m => m.Name == "op_Addition");
AssertDocumentID ("M:N.X.op_Addition(N.X,N.X)", op);
}
[Test]
public void OpExplicit ()
{
var type = GetTestType ();
var op = type.Methods.Single (m => m.Name == "op_Explicit");
AssertDocumentID ("M:N.X.op_Explicit(N.X)~System.Int32", op);
}
[Test]
public void Property ()
{
var type = GetTestType ();
var property = type.Properties.Single (p => p.Name == "prop");
AssertDocumentID ("P:N.X.prop", property);
}
[Test]
public void Indexer ()
{
var type = GetTestType ();
var indexer = type.Properties.Single (p => p.Name == "Item");
AssertDocumentID ("P:N.X.Item(System.String)", indexer);
}
[Test]
public void Event ()
{
var type = GetTestType ();
var @event = type.Events.Single (e => e.Name == "d");
AssertDocumentID ("E:N.X.d", @event);
}
[Test]
public void Delegate ()
{
var type = GetTestType ();
var @delegate = type.NestedTypes.Single (t => t.Name == "D");
AssertDocumentID ("T:N.X.D", @delegate);
}
[Test]
public void NestedType ()
{
var type = GetTestType ();
var nestedType = type.NestedTypes.Single (t => t.Name == "Nested");
AssertDocumentID ("T:N.X.Nested", nestedType);
}
[Test]
public void Linq ()
{
var type = GetTestType ();
var method = type.GetMethod ("Linq");
AssertDocumentID ("M:N.X.Linq(System.Collections.Generic.IEnumerable{System.String},System.Func{System.String})", method);
}
[Test]
public void EII ()
{
var type = GetTestType ();
var method = type.Methods.Where (m => m.Name.Contains ("IXA")).First ();
AssertDocumentID ("M:N.X.N#IX{N#KVP{System#String,System#Int32}}#IXA(N.KVP{System.String,System.Int32})", method);
}
TypeDefinition GetTestType ()
{
return typeof (N.X).ToDefinition ();
}
TypeDefinition GetTestType (Type type)
{
return type.ToDefinition ();
}
static void AssertDocumentID (string docId, IMemberDefinition member)
{
Assert.AreEqual (docId, DocCommentId.GetDocCommentId (member));
}
}
}
| |
// (c) Copyright Esri, 2010 - 2013
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Resources;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.OSM.OSMClassExtension;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("b0878ae8-a85d-4fee-8cce-4ed015e03e4e")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("OSMEditor.OSMGPFeatureComparison")]
public class OSMGPFeatureComparison : ESRI.ArcGIS.Geoprocessing.IGPFunction2
{
string m_DisplayName = String.Empty;
int in_sourceFeatureClassNumber, in_sourceIntersectionFieldNumber, in_sourceRefIDsFieldNumber, in_MatchFeatureClassNumber, out_FeatureClassNumber;
ResourceManager resourceManager = null;
OSMGPFactory osmGPFactory = null;
public OSMGPFeatureComparison()
{
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
osmGPFactory = new OSMGPFactory();
}
#region "IGPFunction2 Implementations"
public ESRI.ArcGIS.esriSystem.UID DialogCLSID
{
get
{
return null;
}
}
public string DisplayName
{
get
{
if (String.IsNullOrEmpty(m_DisplayName))
{
m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_FeatureComparisonName).DisplayName;
}
return m_DisplayName;
}
}
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
{
try
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;
if (TrackCancel == null)
{
TrackCancel = new CancelTrackerClass();
}
// decode in the input layers
IGPParameter in_SourceFeatureClassParameter = paramvalues.get_Element(in_sourceFeatureClassNumber) as IGPParameter;
IGPValue in_SourceFeatureGPValue = gpUtilities3.UnpackGPValue(in_SourceFeatureClassParameter) as IGPValue;
IFeatureClass sourceFeatureClass = null;
IQueryFilter queryFilter = null;
gpUtilities3.DecodeFeatureLayer((IGPValue)in_SourceFeatureGPValue, out sourceFeatureClass, out queryFilter);
if (sourceFeatureClass == null)
{
message.AddError(120027, resourceManager.GetString("GPTools_OSMGPFeatureComparison_source_nullpointer"));
return;
}
IGPParameter in_NumberOfIntersectionsFieldParameter = paramvalues.get_Element(in_sourceIntersectionFieldNumber) as IGPParameter;
IGPValue in_NumberOfIntersectionsFieldGPValue = gpUtilities3.UnpackGPValue(in_NumberOfIntersectionsFieldParameter) as IGPValue;
IGPParameter in_SourceRefIDFieldParameter = paramvalues.get_Element(in_sourceRefIDsFieldNumber) as IGPParameter;
IGPValue in_SourceRefIDFieldGPValue = gpUtilities3.UnpackGPValue(in_SourceRefIDFieldParameter) as IGPValue;
IGPParameter in_MatchFeatureClassParameter = paramvalues.get_Element(in_MatchFeatureClassNumber) as IGPParameter;
IGPValue in_MatchFeatureGPValue = gpUtilities3.UnpackGPValue(in_MatchFeatureClassParameter) as IGPValue;
IFeatureClass matchFeatureClass = null;
IQueryFilter matchQueryFilter = null;
gpUtilities3.DecodeFeatureLayer((IGPValue)in_MatchFeatureGPValue, out matchFeatureClass, out matchQueryFilter);
if (matchFeatureClass == null)
{
message.AddError(120028, resourceManager.GetString("GPTools_OSMGPFeatureComparison_match_nullpointer"));
return;
}
if (queryFilter != null)
{
if (((IGeoDataset)matchFeatureClass).SpatialReference != null)
{
queryFilter.set_OutputSpatialReference(sourceFeatureClass.ShapeFieldName, ((IGeoDataset)matchFeatureClass).SpatialReference);
}
}
IWorkspace sourceWorkspace = ((IDataset) sourceFeatureClass).Workspace;
IWorkspaceEdit sourceWorkspaceEdit = sourceWorkspace as IWorkspaceEdit;
if (sourceWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace)
{
sourceWorkspaceEdit = sourceWorkspace as IWorkspaceEdit;
sourceWorkspaceEdit.StartEditing(false);
sourceWorkspaceEdit.StartEditOperation();
}
// get an overall feature count as that determines the progress indicator
int featureCount = ((ITable)sourceFeatureClass).RowCount(queryFilter);
// set up the progress indicator
IStepProgressor stepProgressor = TrackCancel as IStepProgressor;
if (stepProgressor != null)
{
stepProgressor.MinRange = 0;
stepProgressor.MaxRange = featureCount;
stepProgressor.Position = 0;
stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPFeatureComparison_progressMessage");
stepProgressor.StepValue = 1;
stepProgressor.Show();
}
int numberOfIntersectionsFieldIndex = sourceFeatureClass.FindField(in_NumberOfIntersectionsFieldGPValue.GetAsText());
int sourceRefIDFieldIndex = sourceFeatureClass.FindField(in_SourceRefIDFieldGPValue.GetAsText());
ISpatialFilter matchFCSpatialFilter = new SpatialFilter();
matchFCSpatialFilter.GeometryField = matchFeatureClass.ShapeFieldName;
matchFCSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
matchFCSpatialFilter.WhereClause = matchQueryFilter.WhereClause;
using (ComReleaser comReleaser = new ComReleaser())
{
IFeatureCursor sourceFeatureCursor = sourceFeatureClass.Search(queryFilter, false);
comReleaser.ManageLifetime(sourceFeatureCursor);
IFeature sourceFeature = null;
while ((sourceFeature = sourceFeatureCursor.NextFeature()) != null)
{
int numberOfIntersections = 0;
string intersectedFeatures = String.Empty;
IPolyline sourceLine = sourceFeature.Shape as IPolyline;
matchFCSpatialFilter.Geometry = sourceLine;
using (ComReleaser innerReleaser = new ComReleaser())
{
IFeatureCursor matchFeatureCursor = matchFeatureClass.Search(matchFCSpatialFilter, false);
innerReleaser.ManageLifetime(matchFeatureCursor);
IFeature matchFeature = null;
while ((matchFeature = matchFeatureCursor.NextFeature()) != null)
{
IPointCollection intersectionPointCollection = null;
try
{
ITopologicalOperator topoOperator = sourceLine as ITopologicalOperator;
if (topoOperator.IsSimple == false)
{
((ITopologicalOperator2)topoOperator).IsKnownSimple_2 = false;
topoOperator.Simplify();
}
IPolyline matchPolyline = matchFeature.Shape as IPolyline;
if (queryFilter != null)
{
matchPolyline.Project(sourceLine.SpatialReference);
}
if (((ITopologicalOperator)matchPolyline).IsSimple == false)
{
((ITopologicalOperator2)matchPolyline).IsKnownSimple_2 = false;
((ITopologicalOperator)matchPolyline).Simplify();
}
intersectionPointCollection = topoOperator.Intersect(matchPolyline, esriGeometryDimension.esriGeometry0Dimension) as IPointCollection;
}
catch (Exception ex)
{
message.AddWarning(ex.Message);
continue;
}
if (intersectionPointCollection != null && intersectionPointCollection.PointCount > 0)
{
numberOfIntersections = numberOfIntersections + intersectionPointCollection.PointCount;
if (String.IsNullOrEmpty(intersectedFeatures))
{
intersectedFeatures = matchFeature.OID.ToString();
}
else
{
intersectedFeatures = intersectedFeatures + "," + matchFeature.OID.ToString();
}
}
}
if (numberOfIntersectionsFieldIndex > -1)
{
sourceFeature.set_Value(numberOfIntersectionsFieldIndex, numberOfIntersections);
}
if (sourceRefIDFieldIndex > -1)
{
if (intersectedFeatures.Length > sourceFeatureClass.Fields.get_Field(sourceRefIDFieldIndex).Length)
{
sourceFeature.set_Value(sourceRefIDFieldIndex, intersectedFeatures.Substring(0, sourceFeatureClass.Fields.get_Field(sourceRefIDFieldIndex).Length));
}
else
{
sourceFeature.set_Value(sourceRefIDFieldIndex, intersectedFeatures);
}
}
}
try
{
sourceFeature.Store();
}
catch (Exception ex)
{
message.AddWarning(ex.Message);
}
if (stepProgressor != null)
{
// update the progress UI
stepProgressor.Step();
}
// check for user cancellation
if (TrackCancel.Continue() == false)
{
return;
}
}
}
if (sourceWorkspaceEdit != null)
{
sourceWorkspaceEdit.StopEditOperation();
sourceWorkspaceEdit.StopEditing(true);
}
if (stepProgressor != null)
{
stepProgressor.Hide();
}
}
catch (Exception ex)
{
message.AddAbort(ex.Message);
}
}
public ESRI.ArcGIS.esriSystem.IName FullName
{
get
{
IName fullName = null;
if (osmGPFactory != null)
{
fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_FeatureComparisonName) as IName;
}
return fullName;
}
}
public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam)
{
return null;
}
public int HelpContext
{
get
{
return 0;
}
}
public string HelpFile
{
get
{
return String.Empty;
}
}
public bool IsLicensed()
{
// as an open-source tool it will also be licensed
return true;
}
public string MetadataFile
{
get
{
string metadafile = "gpfeaturecomparison.xml";
try
{
string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray());
string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation();
string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpupload_" + languageid[0] + ".xml";
string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpupload_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml";
if (System.IO.File.Exists(localizedMetaDataFileShort))
{
metadafile = localizedMetaDataFileShort;
}
else if (System.IO.File.Exists(localizedMetaDataFileLong))
{
metadafile = localizedMetaDataFileLong;
}
}
catch { }
return metadafile;
}
}
public string Name
{
get
{
return OSMGPFactory.m_FeatureComparisonName;
}
}
public ESRI.ArcGIS.esriSystem.IArray ParameterInfo
{
get
{
IArray parameters = new ArrayClass();
// source feature class
IGPParameterEdit3 in_sourceFeaturesParameter = new GPParameterClass() as IGPParameterEdit3;
in_sourceFeaturesParameter.DataType = new GPFeatureLayerTypeClass();
in_sourceFeaturesParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
in_sourceFeaturesParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPFeatureComparison_inputsourcefeatures_displayname");
in_sourceFeaturesParameter.Name = "in_sourceFeatures";
in_sourceFeaturesParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
IGPFeatureClassDomain sourceFeatureClassDomain = new GPFeatureClassDomainClass();
sourceFeatureClassDomain.AddType(esriGeometryType.esriGeometryPolyline);
in_sourceFeaturesParameter.Domain = (IGPDomain)sourceFeatureClassDomain;
in_sourceFeatureClassNumber = 0;
parameters.Add((IGPParameter3)in_sourceFeaturesParameter);
// input field to hold the number of intersections
IGPParameterEdit3 in_sourceIntersectionFieldParameter = new GPParameterClass() as IGPParameterEdit3;
in_sourceIntersectionFieldParameter.DataType = new FieldTypeClass();
in_sourceIntersectionFieldParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
in_sourceIntersectionFieldParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPFeatureComparison_inputintersectnumber_displayname");
in_sourceIntersectionFieldParameter.Name = "in_number_of_intersections_field";
in_sourceIntersectionFieldParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
in_sourceIntersectionFieldParameter.AddDependency("in_sourceFeatures");
IGPFieldDomain fieldDomain = new GPFieldDomainClass();
fieldDomain.AddType(esriFieldType.esriFieldTypeInteger);
in_sourceIntersectionFieldParameter.Domain = fieldDomain as IGPDomain;
in_sourceIntersectionFieldNumber = 1;
parameters.Add((IGPParameter3)in_sourceIntersectionFieldParameter);
// input field to hold the intersected OIDs (comma separated)
IGPParameterEdit3 in_sourceRefIDsFieldParameter = new GPParameterClass() as IGPParameterEdit3;
in_sourceRefIDsFieldParameter.DataType = new FieldTypeClass();
in_sourceRefIDsFieldParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
in_sourceRefIDsFieldParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPFeatureComparison_inputintersectids_displayname");
in_sourceRefIDsFieldParameter.Name = "in_intersected_ids_field";
in_sourceRefIDsFieldParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
in_sourceRefIDsFieldParameter.AddDependency("in_sourceFeatures");
IGPFieldDomain id_fieldDomain = new GPFieldDomainClass();
id_fieldDomain.AddType(esriFieldType.esriFieldTypeString);
in_sourceRefIDsFieldParameter.Domain = id_fieldDomain as IGPDomain;
in_sourceRefIDsFieldNumber = 2;
parameters.Add((IGPParameter3)in_sourceRefIDsFieldParameter);
// input feature class
IGPParameterEdit3 in_MatchFeatureClassParameter = new GPParameterClass() as IGPParameterEdit3;
in_MatchFeatureClassParameter.DataType = new GPFeatureLayerTypeClass();
in_MatchFeatureClassParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
in_MatchFeatureClassParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPFeatureComparison_inputmatchfeatures_displayname");
in_MatchFeatureClassParameter.Name = "in_matchFeatures";
in_MatchFeatureClassParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
IGPFeatureClassDomain matchFeatureClassDomain = new GPFeatureClassDomainClass();
matchFeatureClassDomain.AddType(esriGeometryType.esriGeometryPolyline);
in_MatchFeatureClassParameter.Domain = (IGPDomain)matchFeatureClassDomain;
in_MatchFeatureClassNumber = 3;
parameters.Add((IGPParameter3)in_MatchFeatureClassParameter);
// output feature class
IGPParameterEdit3 out_FeatureClassParameter = new GPParameterClass() as IGPParameterEdit3;
out_FeatureClassParameter.DataType = new GPFeatureLayerTypeClass();
out_FeatureClassParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
out_FeatureClassParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPFeatureComparison_outputfeatures_displayname");
out_FeatureClassParameter.Name = "out_sourceFeatures";
out_FeatureClassParameter.ParameterType = esriGPParameterType.esriGPParameterTypeDerived;
out_FeatureClassParameter.AddDependency("in_sourceFeatures");
out_FeatureClassNumber = 4;
parameters.Add((IGPParameter3)out_FeatureClassParameter);
return parameters;
}
}
public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
{
}
public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
{
}
public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
{
return default(ESRI.ArcGIS.Geodatabase.IGPMessages);
}
#endregion
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using DiscUtils.Compression;
using DiscUtils.Streams;
using Buffer=DiscUtils.Streams.Buffer;
namespace DiscUtils.Dmg
{
internal class UdifBuffer : Buffer
{
private CompressedRun _activeRun;
private long _activeRunOffset;
private byte[] _decompBuffer;
private readonly ResourceFork _resources;
private readonly long _sectorCount;
private readonly Stream _stream;
public UdifBuffer(Stream stream, ResourceFork resources, long sectorCount)
{
_stream = stream;
_resources = resources;
_sectorCount = sectorCount;
Blocks = new List<CompressedBlock>();
foreach (Resource resource in _resources.GetAllResources("blkx"))
{
Blocks.Add(((BlkxResource)resource).Block);
}
}
public List<CompressedBlock> Blocks { get; }
public override bool CanRead
{
get { return true; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Capacity
{
get { return _sectorCount * Sizes.Sector; }
}
public override int Read(long pos, byte[] buffer, int offset, int count)
{
int totalCopied = 0;
long currentPos = pos;
while (totalCopied < count && currentPos < Capacity)
{
LoadRun(currentPos);
int bufferOffset = (int)(currentPos - (_activeRunOffset + _activeRun.SectorStart * Sizes.Sector));
int toCopy = (int)Math.Min(_activeRun.SectorCount * Sizes.Sector - bufferOffset, count - totalCopied);
switch (_activeRun.Type)
{
case RunType.Zeros:
Array.Clear(buffer, offset + totalCopied, toCopy);
break;
case RunType.Raw:
_stream.Position = _activeRun.CompOffset + bufferOffset;
StreamUtilities.ReadExact(_stream, buffer, offset + totalCopied, toCopy);
break;
case RunType.AdcCompressed:
case RunType.ZlibCompressed:
case RunType.BZlibCompressed:
Array.Copy(_decompBuffer, bufferOffset, buffer, offset + totalCopied, toCopy);
break;
default:
throw new NotImplementedException("Reading from run of type " + _activeRun.Type);
}
currentPos += toCopy;
totalCopied += toCopy;
}
return totalCopied;
}
public override void Write(long pos, byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void SetCapacity(long value)
{
throw new NotSupportedException();
}
public override IEnumerable<StreamExtent> GetExtentsInRange(long start, long count)
{
StreamExtent lastRun = null;
foreach (CompressedBlock block in Blocks)
{
if ((block.FirstSector + block.SectorCount) * Sizes.Sector < start)
{
// Skip blocks before start of range
continue;
}
if (block.FirstSector * Sizes.Sector > start + count)
{
// Skip blocks after end of range
continue;
}
foreach (CompressedRun run in block.Runs)
{
if (run.SectorCount > 0 && run.Type != RunType.Zeros)
{
long thisRunStart = (block.FirstSector + run.SectorStart) * Sizes.Sector;
long thisRunEnd = thisRunStart + run.SectorCount * Sizes.Sector;
thisRunStart = Math.Max(thisRunStart, start);
thisRunEnd = Math.Min(thisRunEnd, start + count);
long thisRunLength = thisRunEnd - thisRunStart;
if (thisRunLength > 0)
{
if (lastRun != null && lastRun.Start + lastRun.Length == thisRunStart)
{
lastRun = new StreamExtent(lastRun.Start, lastRun.Length + thisRunLength);
}
else
{
if (lastRun != null)
{
yield return lastRun;
}
lastRun = new StreamExtent(thisRunStart, thisRunLength);
}
}
}
}
}
if (lastRun != null)
{
yield return lastRun;
}
}
private static int ADCDecompress(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer,
int outputOffset)
{
int consumed = 0;
int written = 0;
while (consumed < inputCount)
{
byte focusByte = inputBuffer[inputOffset + consumed];
if ((focusByte & 0x80) != 0)
{
// Data Run
int chunkSize = (focusByte & 0x7F) + 1;
Array.Copy(inputBuffer, inputOffset + consumed + 1, outputBuffer, outputOffset + written, chunkSize);
consumed += chunkSize + 1;
written += chunkSize;
}
else if ((focusByte & 0x40) != 0)
{
// 3 byte code
int chunkSize = (focusByte & 0x3F) + 4;
int offset = EndianUtilities.ToUInt16BigEndian(inputBuffer, inputOffset + consumed + 1);
for (int i = 0; i < chunkSize; ++i)
{
outputBuffer[outputOffset + written + i] =
outputBuffer[outputOffset + written + i - offset - 1];
}
consumed += 3;
written += chunkSize;
}
else
{
// 2 byte code
int chunkSize = ((focusByte & 0x3F) >> 2) + 3;
int offset = ((focusByte & 0x3) << 8) + (inputBuffer[inputOffset + consumed + 1] & 0xFF);
for (int i = 0; i < chunkSize; ++i)
{
outputBuffer[outputOffset + written + i] =
outputBuffer[outputOffset + written + i - offset - 1];
}
consumed += 2;
written += chunkSize;
}
}
return written;
}
private void LoadRun(long pos)
{
if (_activeRun != null
&& pos >= _activeRunOffset + _activeRun.SectorStart * Sizes.Sector
&& pos < _activeRunOffset + (_activeRun.SectorStart + _activeRun.SectorCount) * Sizes.Sector)
{
return;
}
long findSector = pos / 512;
foreach (CompressedBlock block in Blocks)
{
if (block.FirstSector <= findSector && block.FirstSector + block.SectorCount > findSector)
{
// Make sure the decompression buffer is big enough
if (_decompBuffer == null || _decompBuffer.Length < block.DecompressBufferRequested * Sizes.Sector)
{
_decompBuffer = new byte[block.DecompressBufferRequested * Sizes.Sector];
}
foreach (CompressedRun run in block.Runs)
{
if (block.FirstSector + run.SectorStart <= findSector &&
block.FirstSector + run.SectorStart + run.SectorCount > findSector)
{
LoadRun(run);
_activeRunOffset = block.FirstSector * Sizes.Sector;
return;
}
}
throw new IOException("No run for sector " + findSector + " in block starting at " +
block.FirstSector);
}
}
throw new IOException("No block for sector " + findSector);
}
private void LoadRun(CompressedRun run)
{
int toCopy = (int)(run.SectorCount * Sizes.Sector);
switch (run.Type)
{
case RunType.ZlibCompressed:
_stream.Position = run.CompOffset + 2; // 2 byte zlib header
using (DeflateStream ds = new DeflateStream(_stream, CompressionMode.Decompress, true))
{
StreamUtilities.ReadExact(ds, _decompBuffer, 0, toCopy);
}
break;
case RunType.AdcCompressed:
_stream.Position = run.CompOffset;
byte[] compressed = StreamUtilities.ReadExact(_stream, (int)run.CompLength);
if (ADCDecompress(compressed, 0, compressed.Length, _decompBuffer, 0) != toCopy)
{
throw new InvalidDataException("Run too short when decompressed");
}
break;
case RunType.BZlibCompressed:
using (
BZip2DecoderStream ds =
new BZip2DecoderStream(new SubStream(_stream, run.CompOffset, run.CompLength),
Ownership.None))
{
StreamUtilities.ReadExact(ds, _decompBuffer, 0, toCopy);
}
break;
case RunType.Zeros:
case RunType.Raw:
break;
default:
throw new NotImplementedException("Unrecognized run type " + run.Type);
}
_activeRun = run;
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Configuration;
using Umbraco.Core.Models;
using Umbraco.Web.Models;
using Umbraco.Web.Routing;
using umbraco.cms.businesslogic.template;
using System.Collections.Generic;
namespace Umbraco.Web.Mvc
{
public class RenderRouteHandler : IRouteHandler
{
// Define reserved dictionary keys for controller, action and area specified in route additional values data
private static class ReservedAdditionalKeys
{
internal const string Controller = "c";
internal const string Action = "a";
internal const string Area = "ar";
}
public RenderRouteHandler(IControllerFactory controllerFactory)
{
if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
_controllerFactory = controllerFactory;
}
/// <summary>
/// Contructor generally used for unit testing
/// </summary>
/// <param name="controllerFactory"></param>
/// <param name="umbracoContext"></param>
internal RenderRouteHandler(IControllerFactory controllerFactory, UmbracoContext umbracoContext)
{
if (controllerFactory == null) throw new ArgumentNullException("controllerFactory");
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
_controllerFactory = controllerFactory;
_umbracoContext = umbracoContext;
}
private readonly IControllerFactory _controllerFactory;
private readonly UmbracoContext _umbracoContext;
/// <summary>
/// Returns the current UmbracoContext
/// </summary>
public UmbracoContext UmbracoContext
{
get { return _umbracoContext ?? UmbracoContext.Current; }
}
#region IRouteHandler Members
/// <summary>
/// Assigns the correct controller based on the Umbraco request and returns a standard MvcHandler to prcess the response,
/// this also stores the render model into the data tokens for the current RouteData.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (UmbracoContext == null)
{
throw new NullReferenceException("There is not current UmbracoContext, it must be initialized before the RenderRouteHandler executes");
}
var docRequest = UmbracoContext.PublishedContentRequest;
if (docRequest == null)
{
throw new NullReferenceException("There is not current PublishedContentRequest, it must be initialized before the RenderRouteHandler executes");
}
SetupRouteDataForRequest(
new RenderModel(docRequest.PublishedContent, docRequest.Culture),
requestContext,
docRequest);
return GetHandlerForRoute(requestContext, docRequest);
}
#endregion
/// <summary>
/// Ensures that all of the correct DataTokens are added to the route values which are all required for rendering front-end umbraco views
/// </summary>
/// <param name="renderModel"></param>
/// <param name="requestContext"></param>
/// <param name="docRequest"></param>
internal void SetupRouteDataForRequest(RenderModel renderModel, RequestContext requestContext, PublishedContentRequest docRequest)
{
//put essential data into the data tokens, the 'umbraco' key is required to be there for the view engine
requestContext.RouteData.DataTokens.Add("umbraco", renderModel); //required for the RenderModelBinder and view engine
requestContext.RouteData.DataTokens.Add("umbraco-doc-request", docRequest); //required for RenderMvcController
requestContext.RouteData.DataTokens.Add("umbraco-context", UmbracoContext); //required for UmbracoTemplatePage
}
private void UpdateRouteDataForRequest(RenderModel renderModel, RequestContext requestContext)
{
requestContext.RouteData.DataTokens["umbraco"] = renderModel;
// the rest should not change -- it's only the published content that has changed
}
/// <summary>
/// Checks the request and query strings to see if it matches the definition of having a Surface controller
/// posted value, if so, then we return a PostedDataProxyInfo object with the correct information.
/// </summary>
/// <param name="requestContext"></param>
/// <returns></returns>
private static PostedDataProxyInfo GetPostedFormInfo(RequestContext requestContext)
{
if (requestContext.HttpContext.Request.RequestType != "POST")
return null;
//this field will contain a base64 encoded version of the surface route vals
if (requestContext.HttpContext.Request["uformpostroutevals"].IsNullOrWhiteSpace())
return null;
var encodedVal = requestContext.HttpContext.Request["uformpostroutevals"];
var decryptedString = encodedVal.DecryptWithMachineKey();
var parsedQueryString = HttpUtility.ParseQueryString(decryptedString);
var decodedParts = new Dictionary<string, string>();
foreach (var key in parsedQueryString.AllKeys)
{
decodedParts[key] = parsedQueryString[key];
}
//validate all required keys exist
//the controller
if (!decodedParts.Any(x => x.Key == ReservedAdditionalKeys.Controller))
return null;
//the action
if (!decodedParts.Any(x => x.Key == ReservedAdditionalKeys.Action))
return null;
//the area
if (!decodedParts.Any(x => x.Key == ReservedAdditionalKeys.Area))
return null;
////the controller type, if it contains this then it is a plugin controller, not locally declared.
//if (decodedParts.Any(x => x.Key == "t"))
//{
// return new PostedDataProxyInfo
// {
// ControllerName = requestContext.HttpContext.Server.UrlDecode(decodedParts.Single(x => x.Key == "c").Value),
// ActionName = requestContext.HttpContext.Server.UrlDecode(decodedParts.Single(x => x.Key == "a").Value),
// Area = requestContext.HttpContext.Server.UrlDecode(decodedParts.Single(x => x.Key == "ar").Value),
// ControllerType = requestContext.HttpContext.Server.UrlDecode(decodedParts.Single(x => x.Key == "t").Value)
// };
//}
foreach (var item in decodedParts.Where(x => !new string[] {
ReservedAdditionalKeys.Controller,
ReservedAdditionalKeys.Action,
ReservedAdditionalKeys.Area }.Contains(x.Key)))
{
// Populate route with additional values which aren't reserved values so they eventually to action parameters
requestContext.RouteData.Values[item.Key] = item.Value;
}
//return the proxy info without the surface id... could be a local controller.
return new PostedDataProxyInfo
{
ControllerName = requestContext.HttpContext.Server.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Controller).Value),
ActionName = requestContext.HttpContext.Server.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Action).Value),
Area = requestContext.HttpContext.Server.UrlDecode(decodedParts.Single(x => x.Key == ReservedAdditionalKeys.Area).Value),
};
}
/// <summary>
/// Handles a posted form to an Umbraco Url and ensures the correct controller is routed to and that
/// the right DataTokens are set.
/// </summary>
/// <param name="requestContext"></param>
/// <param name="postedInfo"></param>
private IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo)
{
//set the standard route values/tokens
requestContext.RouteData.Values["controller"] = postedInfo.ControllerName;
requestContext.RouteData.Values["action"] = postedInfo.ActionName;
IHttpHandler handler;
//get the route from the defined routes
using (RouteTable.Routes.GetReadLock())
{
Route surfaceRoute;
if (postedInfo.Area.IsNullOrWhiteSpace())
{
//find the controller in the route table without an area
surfaceRoute = RouteTable.Routes.OfType<Route>()
.SingleOrDefault(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString() == postedInfo.ControllerName &&
!x.DataTokens.ContainsKey("area"));
}
else
{
//find the controller in the route table with the specified area
surfaceRoute = RouteTable.Routes.OfType<Route>()
.SingleOrDefault(x => x.Defaults != null &&
x.Defaults.ContainsKey("controller") &&
x.Defaults["controller"].ToString().InvariantEquals(postedInfo.ControllerName) &&
x.DataTokens.ContainsKey("area") &&
x.DataTokens["area"].ToString().InvariantEquals(postedInfo.Area));
}
if (surfaceRoute == null)
throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName);
//set the area if one is there.
if (surfaceRoute.DataTokens.ContainsKey("area"))
{
requestContext.RouteData.DataTokens["area"] = surfaceRoute.DataTokens["area"];
}
//set the 'Namespaces' token so the controller factory knows where to look to construct it
if (surfaceRoute.DataTokens.ContainsKey("Namespaces"))
{
requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"];
}
handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext);
}
return handler;
}
/// <summary>
/// Returns a RouteDefinition object based on the current renderModel
/// </summary>
/// <param name="requestContext"></param>
/// <param name="publishedContentRequest"></param>
/// <returns></returns>
internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
{
var defaultControllerType = DefaultRenderMvcControllerResolver.Current.GetDefaultControllerType();
var defaultControllerName = ControllerExtensions.GetControllerName(defaultControllerType);
//creates the default route definition which maps to the 'UmbracoController' controller
var def = new RouteDefinition
{
ControllerName = defaultControllerName,
ControllerType = defaultControllerType,
PublishedContentRequest = publishedContentRequest,
ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(),
HasHijackedRoute = false
};
//check that a template is defined), if it doesn't and there is a hijacked route it will just route
// to the index Action
if (publishedContentRequest.HasTemplate)
{
//the template Alias should always be already saved with a safe name.
//if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed
// with the action name attribute.
var templateName = publishedContentRequest.TemplateAlias.Split('.')[0].ToSafeAlias();
def.ActionName = templateName;
}
//check if there's a custom controller assigned, base on the document type alias.
var controllerType = _controllerFactory.GetControllerTypeInternal(requestContext, publishedContentRequest.PublishedContent.DocumentTypeAlias);
//check if that controller exists
if (controllerType != null)
{
//ensure the controller is of type 'IRenderMvcController' and ControllerBase
if (TypeHelper.IsTypeAssignableFrom<IRenderMvcController>(controllerType)
&& TypeHelper.IsTypeAssignableFrom<ControllerBase>(controllerType))
{
//set the controller and name to the custom one
def.ControllerType = controllerType;
def.ControllerName = ControllerExtensions.GetControllerName(controllerType);
if (def.ControllerName != defaultControllerName)
{
def.HasHijackedRoute = true;
}
}
else
{
LogHelper.Warn<RenderRouteHandler>(
"The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must implement '{2}' and inherit from '{3}'.",
() => publishedContentRequest.PublishedContent.DocumentTypeAlias,
() => controllerType.FullName,
() => typeof(IRenderMvcController).FullName,
() => typeof(ControllerBase).FullName);
//exit as we cannnot route to the custom controller, just route to the standard one.
return def;
}
}
//store the route definition
requestContext.RouteData.DataTokens["umbraco-route-def"] = def;
return def;
}
internal IHttpHandler GetHandlerOnMissingTemplate(PublishedContentRequest pcr)
{
// missing template, so we're in a 404 here
// so the content, if any, is a custom 404 page of some sort
if (!pcr.HasPublishedContent)
// means the builder could not find a proper document to handle 404
return new PublishedContentNotFoundHandler();
if (!pcr.HasTemplate)
// means the engine could find a proper document, but the document has no template
// at that point there isn't much we can do and there is no point returning
// to Mvc since Mvc can't do much
return new PublishedContentNotFoundHandler("In addition, no template exists to render the custom 404.");
// so we have a template, so we should have a rendering engine
if (pcr.RenderingEngine == RenderingEngine.WebForms) // back to webforms ?
return (global::umbraco.UmbracoDefault)System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath("~/default.aspx", typeof(global::umbraco.UmbracoDefault));
else if (pcr.RenderingEngine != RenderingEngine.Mvc) // else ?
return new PublishedContentNotFoundHandler("In addition, no rendering engine exists to render the custom 404.");
return null;
}
/// <summary>
/// this will determine the controller and set the values in the route data
/// </summary>
/// <param name="requestContext"></param>
/// <param name="publishedContentRequest"></param>
internal IHttpHandler GetHandlerForRoute(RequestContext requestContext, PublishedContentRequest publishedContentRequest)
{
var routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
//Need to check for a special case if there is form data being posted back to an Umbraco URL
var postedInfo = GetPostedFormInfo(requestContext);
if (postedInfo != null)
{
return HandlePostedValues(requestContext, postedInfo);
}
//here we need to check if there is no hijacked route and no template assigned, if this is the case
//we want to return a blank page, but we'll leave that up to the NoTemplateHandler.
if (!publishedContentRequest.HasTemplate && !routeDef.HasHijackedRoute)
{
publishedContentRequest.UpdateOnMissingTemplate(); // will go 404
// HandleHttpResponseStatus returns a value indicating that the request should
// not be processed any further, eg because it has been redirect. then, exit.
if (UmbracoModule.HandleHttpResponseStatus(requestContext.HttpContext, publishedContentRequest))
return null;
var handler = GetHandlerOnMissingTemplate(publishedContentRequest);
// if it's not null it can be either the PublishedContentNotFoundHandler (no document was
// found to handle 404, or document with no template was found) or the WebForms handler
// (a document was found and its template is WebForms)
// if it's null it means that a document was found and its template is Mvc
// if we have a handler, return now
if (handler != null)
return handler;
// else we are running Mvc
// update the route data - because the PublishedContent has changed
UpdateRouteDataForRequest(
new RenderModel(publishedContentRequest.PublishedContent, publishedContentRequest.Culture),
requestContext);
// update the route definition
routeDef = GetUmbracoRouteDefinition(requestContext, publishedContentRequest);
}
//no post values, just route to the controller/action requried (local)
requestContext.RouteData.Values["controller"] = routeDef.ControllerName;
if (!string.IsNullOrWhiteSpace(routeDef.ActionName))
{
requestContext.RouteData.Values["action"] = routeDef.ActionName;
}
// Set the session state requirements
requestContext.HttpContext.SetSessionStateBehavior(GetSessionStateBehavior(requestContext, routeDef.ControllerName));
// reset the friendly path so in the controllers and anything occuring after this point in time,
//the URL is reset back to the original request.
requestContext.HttpContext.RewritePath(UmbracoContext.OriginalRequestUrl.PathAndQuery);
return new UmbracoMvcHandler(requestContext);
}
private SessionStateBehavior GetSessionStateBehavior(RequestContext requestContext, string controllerName)
{
return _controllerFactory.GetControllerSessionBehavior(requestContext, controllerName);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using log4net;
using OpenSim.Framework;
using OpenSim.Data;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Services.AssetService
{
public class AssetService : AssetServiceBase, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected static AssetService m_RootInstance;
public AssetService(IConfigSource config)
: this(config, "AssetService")
{
}
public AssetService(IConfigSource config, string configName) : base(config, configName)
{
if (m_RootInstance == null)
{
m_RootInstance = this;
if (m_AssetLoader != null)
{
IConfig assetConfig = config.Configs[m_ConfigName];
if (assetConfig == null)
throw new Exception("No " + m_ConfigName + " configuration");
string loaderArgs = assetConfig.GetString("AssetLoaderArgs",
String.Empty);
bool assetLoaderEnabled = assetConfig.GetBoolean("AssetLoaderEnabled", true);
if (assetLoaderEnabled)
{
m_log.DebugFormat("[ASSET SERVICE]: Loading default asset set from {0}", loaderArgs);
m_AssetLoader.ForEachDefaultXmlAsset(
loaderArgs,
delegate(AssetBase a)
{
AssetBase existingAsset = Get(a.ID);
// AssetMetadata existingMetadata = GetMetadata(a.ID);
if (existingAsset == null || Util.SHA1Hash(existingAsset.Data) != Util.SHA1Hash(a.Data))
{
// m_log.DebugFormat("[ASSET]: Storing {0} {1}", a.Name, a.ID);
Store(a);
}
});
}
m_log.Debug("[ASSET SERVICE]: Local asset service enabled");
}
}
}
public virtual AssetBase Get(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Get asset for {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
{
m_log.WarnFormat("[ASSET SERVICE]: Could not parse requested asset id {0}", id);
return null;
}
try
{
return m_Database.GetAsset(assetID);
}
catch (Exception e)
{
m_log.ErrorFormat("[ASSET SERVICE]: Exception getting asset {0} {1}", assetID, e);
return null;
}
}
public virtual AssetBase GetCached(string id)
{
return Get(id);
}
public virtual AssetMetadata GetMetadata(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Get asset metadata for {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return null;
AssetBase asset = m_Database.GetAsset(assetID);
if (asset != null)
return asset.Metadata;
return null;
}
public virtual byte[] GetData(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Get asset data for {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return null;
AssetBase asset = m_Database.GetAsset(assetID);
return asset.Data;
}
public virtual bool Get(string id, Object sender, AssetRetrieved handler)
{
//m_log.DebugFormat("[AssetService]: Get asset async {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return false;
AssetBase asset = m_Database.GetAsset(assetID);
//m_log.DebugFormat("[AssetService]: Got asset {0}", asset);
handler(id, sender, asset);
return true;
}
public virtual string Store(AssetBase asset)
{
if (!m_Database.ExistsAsset(asset.FullID))
{
// m_log.DebugFormat(
// "[ASSET SERVICE]: Storing asset {0} {1}, bytes {2}", asset.Name, asset.FullID, asset.Data.Length);
m_Database.StoreAsset(asset);
}
// else
// {
// m_log.DebugFormat(
// "[ASSET SERVICE]: Not storing asset {0} {1}, bytes {2} as it already exists", asset.Name, asset.FullID, asset.Data.Length);
// }
return asset.ID;
}
public bool UpdateContent(string id, byte[] data)
{
return false;
}
public virtual bool Delete(string id)
{
// m_log.DebugFormat("[ASSET SERVICE]: Deleting asset {0}", id);
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return false;
return m_Database.Delete(id);
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// ScoreBar.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace HoneycombRush
{
/// <summary>
/// Used by other components to display their status.
/// </summary>
public class ScoreBar : DrawableGameComponent
{
#region Enums
/// <summary>
/// Used to determine the component's orientation.
/// </summary>
public enum ScoreBarOrientation
{
Vertical,
Horizontal
}
#endregion
#region Fields/Properties
public int MinValue { get; set; }
public int MaxValue { get; set; }
public Vector2 Position { get; set; }
public Color ScoreBarColor { get; set; }
public int CurrentValue
{
get
{
return currentValue;
}
}
ScoreBarOrientation scoreBarOrientation;
int height;
int width;
SpriteBatch spriteBatch;
int currentValue;
Texture2D backgroundTexture;
Texture2D redTexture;
Texture2D greenTexture;
Texture2D yellowTexture;
GameplayScreen gameplayScreen;
bool isAppearAtCountDown;
#endregion
#region Initialization
/// <summary>
/// Creates a new score bar instance.
/// </summary>
/// <param name="game">The associated game object.</param>
/// <param name="minValue">The score bar's minimal value.</param>
/// <param name="maxValue">The score bar's maximal value.</param>
/// <param name="position">The score bar's position.</param>
/// <param name="height">The score bar's height.</param>
/// <param name="width">The score bar's width.</param>
/// <param name="scoreBarColor">Color to tint the scorebar's background with.</param>
/// <param name="scoreBarOrientation">The score bar's orientation.</param>
/// <param name="initialValue">The score bar's initial value.</param>
/// <param name="screen">Gameplay screen where the score bar will appear.</param>
/// <param name="isAppearAtCountDown">Whether or not the score bar will appear during the game's initial
/// countdown phase.</param>
public ScoreBar(Game game, int minValue, int maxValue, Vector2 position, int height, int width,
Color scoreBarColor, ScoreBarOrientation scoreBarOrientation, int initialValue, GameplayScreen screen,
bool isAppearAtCountDown)
: base(game)
{
this.MinValue = minValue;
this.MaxValue = maxValue;
this.Position = position;
this.ScoreBarColor = scoreBarColor;
this.scoreBarOrientation = scoreBarOrientation;
this.currentValue = initialValue;
this.width = width;
this.height = height;
this.gameplayScreen = screen;
this.isAppearAtCountDown = isAppearAtCountDown;
spriteBatch = (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch));
GetSpaceFromBorder();
}
/// <summary>
/// Loads the content that this component will use.
/// </summary>
protected override void LoadContent()
{
backgroundTexture = Game.Content.Load<Texture2D>("Textures/barBlackBorder");
greenTexture = Game.Content.Load<Texture2D>("Textures/barGreen");
yellowTexture = Game.Content.Load<Texture2D>("Textures/barYellow");
redTexture = Game.Content.Load<Texture2D>("Textures/barRed");
base.LoadContent();
}
#endregion
#region Render
/// <summary>
/// Draws the component.
/// </summary>
/// <param name="gameTime"></param>
public override void Draw(GameTime gameTime)
{
if (!gameplayScreen.IsActive)
{
base.Draw(gameTime);
return;
}
if (!isAppearAtCountDown && !gameplayScreen.IsStarted)
{
base.Draw(gameTime);
return;
}
float rotation;
// Determine the orientation of the component
if (scoreBarOrientation == ScoreBar.ScoreBarOrientation.Horizontal)
{
rotation = 0f;
}
else
{
rotation = 1.57f;
}
spriteBatch.Begin();
// Draws the background of the score bar
spriteBatch.Draw(backgroundTexture, new Rectangle((int)Position.X, (int)Position.Y, width, height),
null, ScoreBarColor, rotation, new Vector2(0, 0), SpriteEffects.None, 0);
// Gets the margin from the border
decimal spaceFromBorder = GetSpaceFromBorder();
spaceFromBorder += 4;
Texture2D coloredTexture = GetTextureByCurrentValue(currentValue);
if (scoreBarOrientation == ScoreBarOrientation.Horizontal)
{
spriteBatch.Draw(coloredTexture, new Rectangle((int)Position.X + 2, (int)Position.Y + 2,
width - (int)spaceFromBorder, height - 4), null, Color.White, rotation, new Vector2(0, 0),
SpriteEffects.None, 0);
}
else
{
spriteBatch.Draw(coloredTexture, new Rectangle((int)Position.X + 2 - height,
(int)Position.Y + width + -2, width - (int)spaceFromBorder, height - 4), null, ScoreBarColor,
-rotation, new Vector2(0, 0), SpriteEffects.None, 0);
}
spriteBatch.End();
base.Draw(gameTime);
}
#endregion
#region Public Methods
/// <summary>
/// Increases the current value of the score bar.
/// </summary>
/// <param name="valueToIncrease">Number to increase the value by</param>
/// <remarks>Negative numbers will have no effect.</remarks>
public void IncreaseCurrentValue(int valueToIncrease)
{
// Make sure that the target value does not exceed the max value
if (valueToIncrease >= 0 && currentValue < MaxValue && currentValue + valueToIncrease <= MaxValue)
{
currentValue += valueToIncrease;
}
// If the target value exceeds the max value, clamp the value to the maximum
else if (currentValue + valueToIncrease > MaxValue)
{
currentValue = MaxValue;
}
}
/// <summary>
/// Decreases the current value of the score bar.
/// </summary>
/// <param name="valueToDecrease">Number to decrease the value by.</param>
public void DecreaseCurrentValue(int valueToDecrease)
{
DecreaseCurrentValue(valueToDecrease, false);
}
/// <summary>
/// Decreases the current value of the score bar.
/// </summary>
/// <param name="valueToDecrease">Number to decrease the value by.</param>
/// <param name="clampToMinimum">If true, then decreasing by an amount which will cause the bar's value
/// to go under its minimum will set the bar to its minimal value. If false, performing such an operation
/// as just described will leave the bar's value unchanged.</param>
/// <returns>The actual amount which was subtracted from the bar's value.</returns>
public int DecreaseCurrentValue(int valueToDecrease, bool clampToMinimum)
{
// Make sure that the target value does not exceed the min value
int valueThatWasDecreased = 0;
if (valueToDecrease >= 0 && currentValue > MinValue && currentValue - valueToDecrease >= MinValue)
{
currentValue -= valueToDecrease;
valueThatWasDecreased = valueToDecrease;
}
// If the target value exceeds the min value, clamp the value to the minimum (or do nothing)
else if (currentValue - valueToDecrease < MinValue && clampToMinimum)
{
valueThatWasDecreased = currentValue - MinValue;
currentValue = MinValue;
}
return valueThatWasDecreased;
}
#endregion
#region Private Methods
/// <summary>
/// Calculate the empty portion of the score bar according to its current value.
/// </summary>
/// <returns>Width of the bar portion which should be empty to represent the bar's current score.</returns>
private decimal GetSpaceFromBorder()
{
int textureSize;
textureSize = width;
decimal valuePercent = Decimal.Divide(currentValue, MaxValue) * 100;
return textureSize - ((decimal)textureSize * valuePercent / (decimal)100);
}
/// <summary>
/// Returns a texture for the score bar's "fill" according to its value.
/// </summary>
/// <param name="value">Current value of the score bar.</param>
/// <returns>A texture the color of which indicates how close to the bar's maximum the value is.</returns>
private Texture2D GetTextureByCurrentValue(int value)
{
Texture2D selectedTexture;
decimal valuePercent = Decimal.Divide(currentValue, MaxValue) * 100;
if (valuePercent > 50)
{
selectedTexture = greenTexture;
}
else if (valuePercent > 25)
{
selectedTexture = yellowTexture;
}
else
{
selectedTexture = redTexture;
}
return selectedTexture;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.KeyVault
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Microsoft.Azure.KeyVault.WebKey;
/// <summary>
/// Performs cryptographic key operations and vault operations against the
/// Key Vault service.
/// </summary>
public partial interface IKeyVaultClient : IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
ServiceClientCredentials Credentials { get; }
/// <summary>
/// Client Api Version.
/// </summary>
string ApiVersion { get; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running
/// Operations. Default value is 30.
/// </summary>
int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is
/// generated and included in each request. Default is true.
/// </summary>
bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Creates a new, named, key in the specified vault.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='kty'>
/// The type of key to create. Valid key types, see JsonWebKeyType.
/// Supported JsonWebKey key types (kty) for Elliptic Curve, RSA,
/// HSM, Octet. Possible values include: 'EC', 'RSA', 'RSA-HSM', 'oct'
/// </param>
/// <param name='keySize'>
/// The key size in bytes. e.g. 1024 or 2048.
/// </param>
/// <param name='keyOps'>
/// </param>
/// <param name='keyAttributes'>
/// </param>
/// <param name='tags'>
/// Application-specific metadata in the form of key-value pairs
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyBundle>> CreateKeyWithHttpMessagesAsync(string vaultBaseUrl, string keyName, string kty, int? keySize = default(int?), IList<string> keyOps = default(IList<string>), KeyAttributes keyAttributes = default(KeyAttributes), IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Imports a key into the specified vault
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='key'>
/// The Json web key
/// </param>
/// <param name='hsm'>
/// Whether to import as a hardware key (HSM) or software key
/// </param>
/// <param name='keyAttributes'>
/// The key management attributes
/// </param>
/// <param name='tags'>
/// Application-specific metadata in the form of key-value pairs
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyBundle>> ImportKeyWithHttpMessagesAsync(string vaultBaseUrl, string keyName, JsonWebKey key, bool? hsm = default(bool?), KeyAttributes keyAttributes = default(KeyAttributes), IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified key
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyBundle>> DeleteKeyWithHttpMessagesAsync(string vaultBaseUrl, string keyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the Key Attributes associated with the specified key
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='keyVersion'>
/// The version of the key
/// </param>
/// <param name='keyOps'>
/// Json web key operations. For more information on possible key
/// operations, see JsonWebKeyOperation.
/// </param>
/// <param name='keyAttributes'>
/// </param>
/// <param name='tags'>
/// Application-specific metadata in the form of key-value pairs
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyBundle>> UpdateKeyWithHttpMessagesAsync(string vaultBaseUrl, string keyName, string keyVersion, IList<string> keyOps = default(IList<string>), KeyAttributes keyAttributes = default(KeyAttributes), IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieves the public portion of a key plus its attributes
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='keyVersion'>
/// The version of the key
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyBundle>> GetKeyWithHttpMessagesAsync(string vaultBaseUrl, string keyName, string keyVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List the versions of the specified key
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='maxresults'>
/// Maximum number of results to return in a page. If not specified
/// the service will return up to 25 results.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<KeyItem>>> GetKeyVersionsWithHttpMessagesAsync(string vaultBaseUrl, string keyName, int? maxresults = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List keys in the specified vault
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='maxresults'>
/// Maximum number of results to return in a page. If not specified
/// the service will return up to 25 results.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<KeyItem>>> GetKeysWithHttpMessagesAsync(string vaultBaseUrl, int? maxresults = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Requests that a backup of the specified key be downloaded to the
/// client.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<BackupKeyResult>> BackupKeyWithHttpMessagesAsync(string vaultBaseUrl, string keyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Restores the backup key in to a vault
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyBundleBackup'>
/// the backup blob associated with a key bundle
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyBundle>> RestoreKeyWithHttpMessagesAsync(string vaultBaseUrl, byte[] keyBundleBackup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Encrypts an arbitrary sequence of bytes using an encryption key
/// that is stored in Azure Key Vault.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='keyVersion'>
/// The version of the key
/// </param>
/// <param name='algorithm'>
/// algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5'
/// </param>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyOperationResult>> EncryptWithHttpMessagesAsync(string vaultBaseUrl, string keyName, string keyVersion, string algorithm, byte[] value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Decrypts a single block of encrypted data
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='keyVersion'>
/// The version of the key
/// </param>
/// <param name='algorithm'>
/// algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5'
/// </param>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyOperationResult>> DecryptWithHttpMessagesAsync(string vaultBaseUrl, string keyName, string keyVersion, string algorithm, byte[] value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a signature from a digest using the specified key in the
/// vault
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='keyVersion'>
/// The version of the key
/// </param>
/// <param name='algorithm'>
/// The signing/verification algorithm identifier. For more
/// information on possible algorithm types, see
/// JsonWebKeySignatureAlgorithm. Possible values include: 'RS256',
/// 'RS384', 'RS512', 'RSNULL'
/// </param>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyOperationResult>> SignWithHttpMessagesAsync(string vaultBaseUrl, string keyName, string keyVersion, string algorithm, byte[] value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verifies a signature using the specified key
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='keyVersion'>
/// The version of the key
/// </param>
/// <param name='algorithm'>
/// The signing/verification algorithm. For more information on
/// possible algorithm types, see JsonWebKeySignatureAlgorithm.
/// Possible values include: 'RS256', 'RS384', 'RS512', 'RSNULL'
/// </param>
/// <param name='digest'>
/// The digest used for signing
/// </param>
/// <param name='signature'>
/// The signature to be verified
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyVerifyResult>> VerifyWithHttpMessagesAsync(string vaultBaseUrl, string keyName, string keyVersion, string algorithm, byte[] digest, byte[] signature, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Wraps a symmetric key using the specified key
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='keyVersion'>
/// The version of the key
/// </param>
/// <param name='algorithm'>
/// algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5'
/// </param>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyOperationResult>> WrapKeyWithHttpMessagesAsync(string vaultBaseUrl, string keyName, string keyVersion, string algorithm, byte[] value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Unwraps a symmetric key using the specified key in the vault that
/// has initially been used for wrapping the key.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='keyName'>
/// The name of the key
/// </param>
/// <param name='keyVersion'>
/// The version of the key
/// </param>
/// <param name='algorithm'>
/// algorithm identifier. Possible values include: 'RSA-OAEP', 'RSA1_5'
/// </param>
/// <param name='value'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<KeyOperationResult>> UnwrapKeyWithHttpMessagesAsync(string vaultBaseUrl, string keyName, string keyVersion, string algorithm, byte[] value, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets a secret in the specified vault.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='secretName'>
/// The name of the secret in the given vault
/// </param>
/// <param name='value'>
/// The value of the secret
/// </param>
/// <param name='tags'>
/// Application-specific metadata in the form of key-value pairs
/// </param>
/// <param name='contentType'>
/// Type of the secret value such as a password
/// </param>
/// <param name='secretAttributes'>
/// The secret management attributes
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<SecretBundle>> SetSecretWithHttpMessagesAsync(string vaultBaseUrl, string secretName, string value, IDictionary<string, string> tags = default(IDictionary<string, string>), string contentType = default(string), SecretAttributes secretAttributes = default(SecretAttributes), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a secret from the specified vault.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='secretName'>
/// The name of the secret in the given vault
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<SecretBundle>> DeleteSecretWithHttpMessagesAsync(string vaultBaseUrl, string secretName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the attributes associated with the specified secret
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='secretName'>
/// The name of the secret in the given vault
/// </param>
/// <param name='secretVersion'>
/// The version of the secret
/// </param>
/// <param name='contentType'>
/// Type of the secret value such as a password
/// </param>
/// <param name='secretAttributes'>
/// The secret management attributes
/// </param>
/// <param name='tags'>
/// Application-specific metadata in the form of key-value pairs
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<SecretBundle>> UpdateSecretWithHttpMessagesAsync(string vaultBaseUrl, string secretName, string secretVersion, string contentType = default(string), SecretAttributes secretAttributes = default(SecretAttributes), IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a secret.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='secretName'>
/// The name of the secret in the given vault
/// </param>
/// <param name='secretVersion'>
/// The version of the secret
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<SecretBundle>> GetSecretWithHttpMessagesAsync(string vaultBaseUrl, string secretName, string secretVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List secrets in the specified vault
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='maxresults'>
/// Maximum number of results to return in a page. If not specified
/// the service will return up to 25 results.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<SecretItem>>> GetSecretsWithHttpMessagesAsync(string vaultBaseUrl, int? maxresults = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List the versions of the specified secret
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='secretName'>
/// The name of the secret in the given vault
/// </param>
/// <param name='maxresults'>
/// Maximum number of results to return in a page. If not specified
/// the service will return up to 25 results.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<SecretItem>>> GetSecretVersionsWithHttpMessagesAsync(string vaultBaseUrl, string secretName, int? maxresults = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List certificates in the specified vault
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='maxresults'>
/// Maximum number of results to return in a page. If not specified
/// the service will return up to 25 results.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<CertificateItem>>> GetCertificatesWithHttpMessagesAsync(string vaultBaseUrl, int? maxresults = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a certificate from the specified vault.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate in the given vault
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificateBundle>> DeleteCertificateWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets the certificate contacts for the specified vault.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='contacts'>
/// The contacts for the vault certificates.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Contacts>> SetCertificateContactsWithHttpMessagesAsync(string vaultBaseUrl, Contacts contacts, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the certificate contacts for the specified vault.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Contacts>> GetCertificateContactsWithHttpMessagesAsync(string vaultBaseUrl, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the certificate contacts for the specified vault.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Contacts>> DeleteCertificateContactsWithHttpMessagesAsync(string vaultBaseUrl, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List certificate issuers for the specified vault.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='maxresults'>
/// Maximum number of results to return in a page. If not specified
/// the service will return up to 25 results.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<CertificateIssuerItem>>> GetCertificateIssuersWithHttpMessagesAsync(string vaultBaseUrl, int? maxresults = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets the specified certificate issuer.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='issuerName'>
/// The name of the issuer.
/// </param>
/// <param name='provider'>
/// The issuer provider.
/// </param>
/// <param name='credentials'>
/// The credentials to be used for the issuer.
/// </param>
/// <param name='organizationDetails'>
/// Details of the organization as provided to the issuer.
/// </param>
/// <param name='attributes'>
/// Attributes of the issuer object.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IssuerBundle>> SetCertificateIssuerWithHttpMessagesAsync(string vaultBaseUrl, string issuerName, string provider, IssuerCredentials credentials = default(IssuerCredentials), OrganizationDetails organizationDetails = default(OrganizationDetails), IssuerAttributes attributes = default(IssuerAttributes), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified certificate issuer.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='issuerName'>
/// The name of the issuer.
/// </param>
/// <param name='provider'>
/// The issuer provider.
/// </param>
/// <param name='credentials'>
/// The credentials to be used for the issuer.
/// </param>
/// <param name='organizationDetails'>
/// Details of the organization as provided to the issuer.
/// </param>
/// <param name='attributes'>
/// Attributes of the issuer object.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IssuerBundle>> UpdateCertificateIssuerWithHttpMessagesAsync(string vaultBaseUrl, string issuerName, string provider = default(string), IssuerCredentials credentials = default(IssuerCredentials), OrganizationDetails organizationDetails = default(OrganizationDetails), IssuerAttributes attributes = default(IssuerAttributes), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified certificate issuer.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='issuerName'>
/// The name of the issuer.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IssuerBundle>> GetCertificateIssuerWithHttpMessagesAsync(string vaultBaseUrl, string issuerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified certificate issuer.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='issuerName'>
/// The name of the issuer.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IssuerBundle>> DeleteCertificateIssuerWithHttpMessagesAsync(string vaultBaseUrl, string issuerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new certificate version. If this is the first version,
/// the certificate resource is created.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate
/// </param>
/// <param name='certificatePolicy'>
/// The management policy for the certificate
/// </param>
/// <param name='certificateAttributes'>
/// The attributes of the certificate (optional)
/// </param>
/// <param name='tags'>
/// Application-specific metadata in the form of key-value pairs
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificateOperation>> CreateCertificateWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, CertificatePolicy certificatePolicy = default(CertificatePolicy), CertificateAttributes certificateAttributes = default(CertificateAttributes), IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Imports a certificate into the specified vault
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate
/// </param>
/// <param name='base64EncodedCertificate'>
/// Base64 encoded representation of the certificate object to import.
/// This certificate needs to contain the private key.
/// </param>
/// <param name='password'>
/// If the private key in base64EncodedCertificate is encrypted, the
/// password used for encryption
/// </param>
/// <param name='certificatePolicy'>
/// The management policy for the certificate
/// </param>
/// <param name='certificateAttributes'>
/// The attributes of the certificate (optional)
/// </param>
/// <param name='tags'>
/// Application-specific metadata in the form of key-value pairs
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificateBundle>> ImportCertificateWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, string base64EncodedCertificate, string password = default(string), CertificatePolicy certificatePolicy = default(CertificatePolicy), CertificateAttributes certificateAttributes = default(CertificateAttributes), IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List the versions of a certificate.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate
/// </param>
/// <param name='maxresults'>
/// Maximum number of results to return in a page. If not specified
/// the service will return up to 25 results.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<CertificateItem>>> GetCertificateVersionsWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, int? maxresults = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the policy for a certificate.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate in the given vault.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificatePolicy>> GetCertificatePolicyWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the policy for a certificate. Set appropriate members in
/// the certificatePolicy that must be updated. Leave others as null.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate in the given vault.
/// </param>
/// <param name='certificatePolicy'>
/// The policy for the certificate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificatePolicy>> UpdateCertificatePolicyWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, CertificatePolicy certificatePolicy, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the attributes associated with the specified certificate
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate in the given vault
/// </param>
/// <param name='certificateVersion'>
/// The version of the certificate
/// </param>
/// <param name='certificatePolicy'>
/// The management policy for the certificate
/// </param>
/// <param name='certificateAttributes'>
/// The attributes of the certificate (optional)
/// </param>
/// <param name='tags'>
/// Application-specific metadata in the form of key-value pairs
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificateBundle>> UpdateCertificateWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, string certificateVersion, CertificatePolicy certificatePolicy = default(CertificatePolicy), CertificateAttributes certificateAttributes = default(CertificateAttributes), IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a Certificate.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate in the given vault
/// </param>
/// <param name='certificateVersion'>
/// The version of the certificate
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificateBundle>> GetCertificateWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, string certificateVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a certificate operation.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate
/// </param>
/// <param name='cancellationRequested'>
/// Indicates if cancellation was requested on the certificate
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificateOperation>> UpdateCertificateOperationWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, bool cancellationRequested, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the certificate operation response.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificateOperation>> GetCertificateOperationWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the certificate operation.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificateOperation>> DeleteCertificateOperationWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Merges a certificate or a certificate chain with a key pair
/// existing on the server.
/// </summary>
/// <param name='vaultBaseUrl'>
/// The vault name, e.g. https://myvault.vault.azure.net
/// </param>
/// <param name='certificateName'>
/// The name of the certificate
/// </param>
/// <param name='x509Certificates'>
/// The certificate or the certificate chain to merge
/// </param>
/// <param name='certificateAttributes'>
/// The attributes of the certificate (optional)
/// </param>
/// <param name='tags'>
/// Application-specific metadata in the form of key-value pairs
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<CertificateBundle>> MergeCertificateWithHttpMessagesAsync(string vaultBaseUrl, string certificateName, IList<byte[]> x509Certificates, CertificateAttributes certificateAttributes = default(CertificateAttributes), IDictionary<string, string> tags = default(IDictionary<string, string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List the versions of the specified key
/// </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>
Task<AzureOperationResponse<IPage<KeyItem>>> GetKeyVersionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List keys in the specified vault
/// </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>
Task<AzureOperationResponse<IPage<KeyItem>>> GetKeysNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List secrets in the specified vault
/// </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>
Task<AzureOperationResponse<IPage<SecretItem>>> GetSecretsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List the versions of the specified secret
/// </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>
Task<AzureOperationResponse<IPage<SecretItem>>> GetSecretVersionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List certificates in the specified vault
/// </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>
Task<AzureOperationResponse<IPage<CertificateItem>>> GetCertificatesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List certificate issuers for the specified vault.
/// </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>
Task<AzureOperationResponse<IPage<CertificateIssuerItem>>> GetCertificateIssuersNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List the versions of a certificate.
/// </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>
Task<AzureOperationResponse<IPage<CertificateItem>>> GetCertificateVersionsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.ComponentModel;
using System.Threading.Tasks;
namespace Xamvvm
{
/// <summary>
/// Navigation extensions.
/// </summary>
public static class NavigationExtensions
{
/// <summary>
/// Pushes the page into current navigation stack.
/// </summary>
/// <returns>The page async.</returns>
/// <param name="currentPageModel">Current page model.</param>
/// <param name="pageToPush">Page to push.</param>
/// <param name="executeOnPageModel">Execute on page model.</param>
/// <param name="animated">If set to <c>true</c> animated.</param>
/// <typeparam name="TCurrentPageModel">The 1st type parameter.</typeparam>
/// <typeparam name="TPageModel">The 2nd type parameter.</typeparam>
public static Task<bool> PushPageAsync<TCurrentPageModel, TPageModel>(this TCurrentPageModel currentPageModel, IBasePage<TPageModel> pageToPush, Action<TPageModel> executeOnPageModel = null, bool animated = true) where TCurrentPageModel : class, IBasePageModel where TPageModel : class, IBasePageModel
{
var currentPage = XamvvmCore.CurrentFactory.GetPageByModel(currentPageModel);
if (currentPage != null)
{
if (executeOnPageModel != null)
pageToPush.ExecuteOnPageModel(executeOnPageModel);
return XamvvmCore.CurrentFactory.PushPageAsync(currentPage, pageToPush, animated);
}
return Task.FromResult(false);
}
/// <summary>
/// Pushes the cached page into current navigation stack.
/// </summary>
/// <returns>The page from cache async.</returns>
/// <param name="currentPageModel">Current page model.</param>
/// <param name="executeOnPageModel">Execute on page model.</param>
/// <param name="cacheKey">Cache key.</param>
/// <param name="animated">If set to <c>true</c> animated.</param>
/// <typeparam name="TPageModel">The 1st type parameter.</typeparam>
public static Task<bool> PushPageFromCacheAsync<TPageModel>(this IBasePageModel currentPageModel, Action<TPageModel> executeOnPageModel = null, string cacheKey = null, bool animated = true) where TPageModel : class, IBasePageModel
{
var currentPage = XamvvmCore.CurrentFactory.GetPageByModel(currentPageModel);
if (currentPage != null)
{
var pageToPush = XamvvmCore.CurrentFactory.GetPageFromCache<TPageModel>(cacheKey: cacheKey);
if (executeOnPageModel != null)
pageToPush.ExecuteOnPageModel(executeOnPageModel);
return XamvvmCore.CurrentFactory.PushPageAsync(currentPage, pageToPush, animated);
}
return Task.FromResult(false);
}
/// <summary>
/// Pushes the modal cached page as current navigation stack.
/// </summary>
/// <returns>The page from cache async.</returns>
/// <param name="currentPageModel">Current page model.</param>
/// <param name="executeOnPageModel">Execute on page model.</param>
/// <param name="cacheKey">Cache key.</param>
/// <param name="animated">If set to <c>true</c> animated.</param>
/// <typeparam name="TPageModel">The 1st type parameter.</typeparam>
public static Task<bool> PushModalPageFromCacheAsync<TPageModel>(this IBasePageModel currentPageModel, Action<TPageModel> executeOnPageModel = null, string cacheKey = null, bool animated = true) where TPageModel : class, IBasePageModel
{
var currentPage = XamvvmCore.CurrentFactory.GetPageByModel(currentPageModel);
if (currentPage != null)
{
var pageToPush = XamvvmCore.CurrentFactory.GetPageFromCache<TPageModel>(cacheKey: cacheKey);
if (executeOnPageModel != null)
pageToPush.ExecuteOnPageModel(executeOnPageModel);
return XamvvmCore.CurrentFactory.PushModalPageAsync(currentPage, pageToPush, animated);
}
return Task.FromResult(false);
}
/// <summary>
/// Pushs the page as new instance into current navigation stack.
/// </summary>
/// <returns>The page as new instance async.</returns>
/// <param name="currentPageModel">Current page model.</param>
/// <param name="executeOnPageModel">Execute on page model.</param>
/// <param name="animated">If set to <c>true</c> animated.</param>
/// <typeparam name="TPageModel">The 1st type parameter.</typeparam>
public static Task<bool> PushPageAsNewInstanceAsync<TPageModel>(this IBasePageModel currentPageModel, Action<TPageModel> executeOnPageModel = null, bool animated = true) where TPageModel : class, IBasePageModel
{
var currentPage = XamvvmCore.CurrentFactory.GetPageByModel(currentPageModel);
if (currentPage != null)
{
var pageToPush = XamvvmCore.CurrentFactory.GetPageAsNewInstance<TPageModel>();
if (executeOnPageModel != null)
pageToPush.ExecuteOnPageModel(executeOnPageModel);
return XamvvmCore.CurrentFactory.PushPageAsync(currentPage, pageToPush, animated);
}
return Task.FromResult(false);
}
/// <summary>
/// Pushs the page as new instance into current navigation stack.
/// </summary>
/// <returns>The page as new instance async.</returns>
/// <param name="currentPageModel">Current page model.</param>
/// <param name="executeOnPageModel">Execute on page model.</param>
/// <param name="animated">If set to <c>true</c> animated.</param>
/// <typeparam name="TPageModel">The 1st type parameter.</typeparam>
public static Task<bool> PushModalPageAsNewInstanceAsync<TPageModel>(this IBasePageModel currentPageModel, Action<TPageModel> executeOnPageModel = null, bool animated = true) where TPageModel : class, IBasePageModel
{
var currentPage = XamvvmCore.CurrentFactory.GetPageByModel(currentPageModel);
if (currentPage != null)
{
var pageToPush = XamvvmCore.CurrentFactory.GetPageAsNewInstance<TPageModel>();
if (executeOnPageModel != null)
pageToPush.ExecuteOnPageModel(executeOnPageModel);
return XamvvmCore.CurrentFactory.PushModalPageAsync(currentPage, pageToPush, animated);
}
return Task.FromResult(false);
}
/// <summary>
/// Pushes the modal page into current navigation stack.
/// </summary>
/// <returns>The modal page async.</returns>
/// <param name="currentPageModel">Current page model.</param>
/// <param name="pageToPush">Page to push.</param>
/// <param name="executeOnPageModel">Execute on page model.</param>
/// <param name="animated">If set to <c>true</c> animated.</param>
/// <typeparam name="TCurrentPageModel">The 1st type parameter.</typeparam>
/// <typeparam name="TPageModel">The 2nd type parameter.</typeparam>
public static Task<bool> PushModalPageAsync<TCurrentPageModel, TPageModel>(this TCurrentPageModel currentPageModel, IBasePage<TPageModel> pageToPush, Action<TPageModel> executeOnPageModel = null, bool animated = true) where TCurrentPageModel : class, IBasePageModel where TPageModel : class, IBasePageModel
{
var currentPage = XamvvmCore.CurrentFactory.GetPageByModel(currentPageModel);
if (currentPage != null)
{
if (executeOnPageModel != null)
pageToPush.ExecuteOnPageModel(executeOnPageModel);
return XamvvmCore.CurrentFactory.PushModalPageAsync(currentPage, pageToPush, animated);
}
return Task.FromResult(false);
}
/// <summary>
/// Pops the page from current navigation stack.
/// </summary>
/// <returns>The page async.</returns>
/// <param name="pageModel">Page model.</param>
/// <param name="animated">If set to <c>true</c> animated.</param>
/// <typeparam name="TPageModel">The 1st type parameter.</typeparam>
public static Task<bool> PopPageAsync<TPageModel>(this TPageModel pageModel, bool animated = true) where TPageModel : class, IBasePageModel
{
var page = XamvvmCore.CurrentFactory.GetPageByModel(pageModel);
if (page != null)
return XamvvmCore.CurrentFactory.PopPageAsync(page, animated);
return Task.FromResult(false);
}
/// <summary>
/// Pops the modal page from current navigation stack.
/// </summary>
/// <returns>The modal page async.</returns>
/// <param name="pageModel">Page model.</param>
/// <param name="animated">If set to <c>true</c> animated.</param>
/// <typeparam name="TPageModel">The 1st type parameter.</typeparam>
public static Task<bool> PopModalPageAsync<TPageModel>(this TPageModel pageModel, bool animated = true) where TPageModel : class, IBasePageModel
{
var page = XamvvmCore.CurrentFactory.GetPageByModel(pageModel);
if (page != null)
return XamvvmCore.CurrentFactory.PopModalPageAsync(page, animated);
return Task.FromResult(false);
}
/// <summary>
/// Removes the page from current navigation stack.
/// </summary>
/// <returns>The page.</returns>
/// <param name="currentPageModel">Current page model.</param>
/// <param name="pageToRemove">Page to remove.</param>
/// <typeparam name="TCurrentPageModel">The 1st type parameter.</typeparam>
/// <typeparam name="TPageModel">The 2nd type parameter.</typeparam>
public static Task<bool> RemovePageAsync<TCurrentPageModel, TPageModel>(this TCurrentPageModel currentPageModel, IBasePage<TPageModel> pageToRemove) where TCurrentPageModel : class, IBasePageModel where TPageModel : class, IBasePageModel
{
var currentPage = XamvvmCore.CurrentFactory.GetPageByModel(currentPageModel);
if (currentPage != null)
return XamvvmCore.CurrentFactory.RemovePageAsync(currentPage, pageToRemove);
return Task.FromResult(false);
}
/// <summary>
/// Pops all pages to root in current navigation stack.
/// </summary>
/// <returns>The pages to root async.</returns>
/// <param name="currentPageModel">Current page model.</param>
/// <param name="clearCache">If set to <c>true</c> clear cache.</param>
/// <param name="animated">If set to <c>true</c> animated.</param>
/// <typeparam name="TCurrentPageModel">The 1st type parameter.</typeparam>
public static Task<bool> PopPagesToRootAsync<TCurrentPageModel>(this TCurrentPageModel currentPageModel, bool clearCache = false, bool animated = true) where TCurrentPageModel : class, IBasePageModel
{
var currentPage = XamvvmCore.CurrentFactory.GetPageByModel(currentPageModel);
if (currentPage != null)
return XamvvmCore.CurrentFactory.PopPagesToRootAsync(currentPage, clearCache, animated);
return Task.FromResult(false);
}
/// <summary>
/// Sets the new root and resets based on PageModel
/// </summary>
/// <param name="currentPageModel">Current page model.</param>
/// <param name="clearCache">Clear cache.</param>
public static Task<bool> SetNewRootAndResetAsync<TNewRootPageModel>(this IBasePageModel currentPageModel, bool clearCache = true) where TNewRootPageModel : class, IBasePageModel
{
return XamvvmCore.CurrentFactory.SetNewRootAndResetAsync<TNewRootPageModel>(clearCache);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using Xunit;
namespace System.Buffers.Text.Tests
{
public class Base64DecoderUnitTests
{
[Fact]
public void BasicDecoding()
{
var rnd = new Random(42);
for (int i = 0; i < 10; i++)
{
int numBytes = rnd.Next(100, 1000 * 1000);
while (numBytes % 4 != 0)
{
numBytes = rnd.Next(100, 1000 * 1000);
}
Span<byte> source = new byte[numBytes];
Base64TestHelper.InitalizeDecodableBytes(source, numBytes);
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
Assert.Equal(OperationStatus.Done,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
Assert.Equal(source.Length, consumed);
Assert.Equal(decodedBytes.Length, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(source.Length, decodedBytes.Length, source, decodedBytes));
}
}
[Fact]
public void DecodeEmptySpan()
{
Span<byte> source = Span<byte>.Empty;
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
Assert.Equal(OperationStatus.Done,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
Assert.Equal(source.Length, consumed);
Assert.Equal(decodedBytes.Length, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(source.Length, decodedBytes.Length, source, decodedBytes));
}
[Fact]
public void BasicDecodingWithFinalBlockFalse()
{
var rnd = new Random(42);
for (int i = 0; i < 10; i++)
{
int numBytes = rnd.Next(100, 1000 * 1000);
while (numBytes % 4 != 0)
{
numBytes = rnd.Next(100, 1000 * 1000);
}
Span<byte> source = new byte[numBytes];
Base64TestHelper.InitalizeDecodableBytes(source, numBytes);
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
int expectedConsumed = source.Length / 4 * 4; // only consume closest multiple of four since isFinalBlock is false
Assert.Equal(OperationStatus.NeedMoreData,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount, isFinalBlock: false));
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(decodedBytes.Length, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, decodedBytes.Length, source, decodedBytes));
}
}
[Theory]
[InlineData("A", 0, 0)]
[InlineData("AQ", 0, 0)]
[InlineData("AQI", 0, 0)]
[InlineData("AQIDBA", 4, 3)]
[InlineData("AQIDBAU", 4, 3)]
[InlineData("AQID", 4, 3)]
[InlineData("AQIDBAUG", 8, 6)]
public void BasicDecodingWithFinalBlockFalseKnownInputNeedMoreData(string inputString, int expectedConsumed, int expectedWritten)
{
Span<byte> source = Encoding.ASCII.GetBytes(inputString);
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
Assert.Equal(OperationStatus.NeedMoreData, Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount, isFinalBlock: false));
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(expectedWritten, decodedByteCount); // expectedWritten == decodedBytes.Length
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, decodedBytes.Length, source, decodedBytes));
}
[Theory]
[InlineData("AQ==", 0, 0)]
[InlineData("AQI=", 0, 0)]
[InlineData("AQIDBA==", 4, 3)]
[InlineData("AQIDBAU=", 4, 3)]
public void BasicDecodingWithFinalBlockFalseKnownInputInvalid(string inputString, int expectedConsumed, int expectedWritten)
{
Span<byte> source = Encoding.ASCII.GetBytes(inputString);
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount, isFinalBlock: false));
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(expectedWritten, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, expectedWritten, source, decodedBytes));
}
[Theory]
[InlineData("A", 0, 0)]
[InlineData("AQ", 0, 0)]
[InlineData("AQI", 0, 0)]
[InlineData("AQIDBA", 4, 3)]
[InlineData("AQIDBAU", 4, 3)]
public void BasicDecodingWithFinalBlockTrueKnownInputInvalid(string inputString, int expectedConsumed, int expectedWritten)
{
Span<byte> source = Encoding.ASCII.GetBytes(inputString);
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(expectedWritten, decodedByteCount); // expectedWritten == decodedBytes.Length
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, decodedBytes.Length, source, decodedBytes));
}
[Theory]
[InlineData("AQ==", 4, 1)]
[InlineData("AQI=", 4, 2)]
[InlineData("AQID", 4, 3)]
[InlineData("AQIDBA==", 8, 4)]
[InlineData("AQIDBAU=", 8, 5)]
[InlineData("AQIDBAUG", 8, 6)]
public void BasicDecodingWithFinalBlockTrueKnownInputDone(string inputString, int expectedConsumed, int expectedWritten)
{
Span<byte> source = Encoding.ASCII.GetBytes(inputString);
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
Assert.Equal(OperationStatus.Done, Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(expectedWritten, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, expectedWritten, source, decodedBytes));
}
[Fact]
public void DecodingInvalidBytes()
{
// Invalid Bytes:
// 0-42
// 44-46
// 58-64
// 91-96
// 123-255
byte[] invalidBytes = Base64TestHelper.InvalidBytes;
Assert.Equal(byte.MaxValue + 1 - 64, invalidBytes.Length); // 192
for (int j = 0; j < 8; j++)
{
Span<byte> source = new byte[8] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
for (int i = 0; i < invalidBytes.Length; i++)
{
// Don't test padding (byte 61 i.e. '='), which is tested in DecodingInvalidBytesPadding
if (invalidBytes[i] == Base64TestHelper.s_encodingPad)
continue;
// replace one byte with an invalid input
source[j] = invalidBytes[i];
Assert.Equal(OperationStatus.InvalidData,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
if (j < 4)
{
Assert.Equal(0, consumed);
Assert.Equal(0, decodedByteCount);
}
else
{
Assert.Equal(4, consumed);
Assert.Equal(3, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(4, 3, source, decodedBytes));
}
}
}
// Input that is not a multiple of 4 is considered invalid
{
Span<byte> source = new byte[7] { 50, 50, 50, 50, 80, 80, 80 }; // incomplete input - "2222PPP"
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
Assert.Equal(OperationStatus.InvalidData,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
Assert.Equal(4, consumed);
Assert.Equal(3, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(4, 3, source, decodedBytes));
}
}
[Fact]
public void DecodingInvalidBytesPadding()
{
// Only last 2 bytes can be padding, all other occurrence of padding is invalid
for (int j = 0; j < 7; j++)
{
Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
source[j] = Base64TestHelper.s_encodingPad;
Assert.Equal(OperationStatus.InvalidData,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
if (j < 4)
{
Assert.Equal(0, consumed);
Assert.Equal(0, decodedByteCount);
}
else
{
Assert.Equal(4, consumed);
Assert.Equal(3, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(4, 3, source, decodedBytes));
}
}
// Invalid input with valid padding
{
Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 42, 42, 42 };
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
source[6] = Base64TestHelper.s_encodingPad;
source[7] = Base64TestHelper.s_encodingPad; // invalid input - "2222P*=="
Assert.Equal(OperationStatus.InvalidData,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
Assert.Equal(4, consumed);
Assert.Equal(3, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(4, 3, source, decodedBytes));
source = new byte[] { 50, 50, 50, 50, 80, 42, 42, 42 };
decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
source[7] = Base64TestHelper.s_encodingPad; // invalid input - "2222PP**="
Assert.Equal(OperationStatus.InvalidData,
Base64.DecodeFromUtf8(source, decodedBytes, out consumed, out decodedByteCount));
Assert.Equal(4, consumed);
Assert.Equal(3, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(4, 3, source, decodedBytes));
}
// The last byte or the last 2 bytes being the padding character is valid
{
Span<byte> source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 };
Span<byte> decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
source[6] = Base64TestHelper.s_encodingPad;
source[7] = Base64TestHelper.s_encodingPad; // valid input - "2222PP=="
Assert.Equal(OperationStatus.Done,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
Assert.Equal(source.Length, consumed);
Assert.Equal(4, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(source.Length, 4, source, decodedBytes));
source = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 };
decodedBytes = new byte[Base64.GetMaxDecodedFromUtf8Length(source.Length)];
source[7] = Base64TestHelper.s_encodingPad; // valid input - "2222PPP="
Assert.Equal(OperationStatus.Done,
Base64.DecodeFromUtf8(source, decodedBytes, out consumed, out decodedByteCount));
Assert.Equal(source.Length, consumed);
Assert.Equal(5, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(source.Length, 5, source, decodedBytes));
}
}
[Fact]
public void DecodingOutputTooSmall()
{
for (int numBytes = 5; numBytes < 20; numBytes++)
{
Span<byte> source = new byte[numBytes];
Base64TestHelper.InitalizeDecodableBytes(source, numBytes);
Span<byte> decodedBytes = new byte[3];
int consumed, written;
if (numBytes % 4 != 0)
{
Assert.True(OperationStatus.InvalidData ==
Base64.DecodeFromUtf8(source, decodedBytes, out consumed, out written), "Number of Input Bytes: " + numBytes);
}
else
{
Assert.True(OperationStatus.DestinationTooSmall ==
Base64.DecodeFromUtf8(source, decodedBytes, out consumed, out written), "Number of Input Bytes: " + numBytes);
}
int expectedConsumed = 4;
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(decodedBytes.Length, written);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, decodedBytes.Length, source, decodedBytes));
}
// Output too small even with padding characters in the input
{
Span<byte> source = new byte[12];
Base64TestHelper.InitalizeDecodableBytes(source);
source[10] = Base64TestHelper.s_encodingPad;
source[11] = Base64TestHelper.s_encodingPad;
Span<byte> decodedBytes = new byte[6];
Assert.Equal(OperationStatus.DestinationTooSmall,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int written));
int expectedConsumed = 8;
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(decodedBytes.Length, written);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, decodedBytes.Length, source, decodedBytes));
}
{
Span<byte> source = new byte[12];
Base64TestHelper.InitalizeDecodableBytes(source);
source[11] = Base64TestHelper.s_encodingPad;
Span<byte> decodedBytes = new byte[7];
Assert.Equal(OperationStatus.DestinationTooSmall,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int written));
int expectedConsumed = 8;
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(6, written);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, 6, source, decodedBytes));
}
}
[Fact]
public void DecodingOutputTooSmallRetry()
{
Span<byte> source = new byte[1000];
Base64TestHelper.InitalizeDecodableBytes(source);
int outputSize = 240;
int requiredSize = Base64.GetMaxDecodedFromUtf8Length(source.Length);
Span<byte> decodedBytes = new byte[outputSize];
Assert.Equal(OperationStatus.DestinationTooSmall,
Base64.DecodeFromUtf8(source, decodedBytes, out int consumed, out int decodedByteCount));
int expectedConsumed = decodedBytes.Length / 3 * 4;
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(decodedBytes.Length, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, decodedBytes.Length, source, decodedBytes));
decodedBytes = new byte[requiredSize - outputSize];
source = source.Slice(consumed);
Assert.Equal(OperationStatus.Done,
Base64.DecodeFromUtf8(source, decodedBytes, out consumed, out decodedByteCount));
expectedConsumed = decodedBytes.Length / 3 * 4;
Assert.Equal(expectedConsumed, consumed);
Assert.Equal(decodedBytes.Length, decodedByteCount);
Assert.True(Base64TestHelper.VerifyDecodingCorrectness(expectedConsumed, decodedBytes.Length, source, decodedBytes));
}
[Fact]
public void GetMaxDecodedLength()
{
Span<byte> sourceEmpty = Span<byte>.Empty;
Assert.Equal(0, Base64.GetMaxDecodedFromUtf8Length(0));
// int.MaxValue - (int.MaxValue % 4) => 2147483644, largest multiple of 4 less than int.MaxValue
int[] input = { 0, 4, 8, 12, 16, 20, 2000000000, 2147483640, 2147483644 };
int[] expected = { 0, 3, 6, 9, 12, 15, 1500000000, 1610612730, 1610612733 };
for (int i = 0; i < input.Length; i++)
{
Assert.Equal(expected[i], Base64.GetMaxDecodedFromUtf8Length(input[i]));
}
// Lengths that are not a multiple of 4.
int[] lengthsNotMultipleOfFour = { 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 1001, 1002, 1003, 2147483645, 2147483646, 2147483647 };
int[] expectedOutput = { 0, 0, 0, 3, 3, 3, 6, 6, 6, 9, 9, 9, 750, 750, 750, 1610612733, 1610612733, 1610612733 };
for (int i = 0; i < lengthsNotMultipleOfFour.Length; i++)
{
Assert.Equal(expectedOutput[i], Base64.GetMaxDecodedFromUtf8Length(lengthsNotMultipleOfFour[i]));
}
// negative input
Assert.Throws<ArgumentOutOfRangeException>(() => Base64.GetMaxDecodedFromUtf8Length(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => Base64.GetMaxDecodedFromUtf8Length(int.MinValue));
}
[Fact]
public void DecodeInPlace()
{
const int numberOfBytes = 15;
for (int numberOfBytesToTest = 0; numberOfBytesToTest <= numberOfBytes; numberOfBytesToTest += 4)
{
Span<byte> testBytes = new byte[numberOfBytes];
Base64TestHelper.InitalizeDecodableBytes(testBytes);
string sourceString = Encoding.ASCII.GetString(testBytes.Slice(0, numberOfBytesToTest).ToArray());
Span<byte> expectedBytes = Convert.FromBase64String(sourceString);
Assert.Equal(OperationStatus.Done, Base64.DecodeFromUtf8InPlace(testBytes.Slice(0, numberOfBytesToTest), out int bytesWritten));
Assert.Equal(Base64.GetMaxDecodedFromUtf8Length(numberOfBytesToTest), bytesWritten);
Assert.True(expectedBytes.SequenceEqual(testBytes.Slice(0, bytesWritten)));
}
}
[Fact]
public void EncodeAndDecodeInPlace()
{
byte[] testBytes = new byte[256];
for (int i = 0; i < 256; i++)
{
testBytes[i] = (byte)i;
}
for (int value = 0; value < 256; value++)
{
Span<byte> sourceBytes = testBytes.AsSpan(0, value + 1);
Span<byte> buffer = new byte[Base64.GetMaxEncodedToUtf8Length(sourceBytes.Length)];
Assert.Equal(OperationStatus.Done, Base64.EncodeToUtf8(sourceBytes, buffer, out int consumed, out int written));
var encodedText = Encoding.ASCII.GetString(buffer.ToArray());
var expectedText = Convert.ToBase64String(testBytes, 0, value + 1);
Assert.Equal(expectedText, encodedText);
Assert.Equal(OperationStatus.Done, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten));
Assert.Equal(sourceBytes.Length, bytesWritten);
Assert.True(sourceBytes.SequenceEqual(buffer.Slice(0, bytesWritten)));
}
}
[Fact]
public void DecodeInPlaceInvalidBytes()
{
byte[] invalidBytes = Base64TestHelper.InvalidBytes;
for (int j = 0; j < 8; j++)
{
for (int i = 0; i < invalidBytes.Length; i++)
{
Span<byte> buffer = new byte[8] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
// Don't test padding (byte 61 i.e. '='), which is tested in DecodeInPlaceInvalidBytesPadding
if (invalidBytes[i] == Base64TestHelper.s_encodingPad)
continue;
// replace one byte with an invalid input
buffer[j] = invalidBytes[i];
string sourceString = Encoding.ASCII.GetString(buffer.Slice(0, 4).ToArray());
Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten));
if (j < 4)
{
Assert.Equal(0, bytesWritten);
}
else
{
Assert.Equal(3, bytesWritten);
Span<byte> expectedBytes = Convert.FromBase64String(sourceString);
Assert.True(expectedBytes.SequenceEqual(buffer.Slice(0, bytesWritten)));
}
}
}
// Input that is not a multiple of 4 is considered invalid
{
Span<byte> buffer = new byte[7] { 50, 50, 50, 50, 80, 80, 80 }; // incomplete input - "2222PPP"
Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten));
Assert.Equal(0, bytesWritten);
}
}
[Fact]
public void DecodeInPlaceInvalidBytesPadding()
{
// Only last 2 bytes can be padding, all other occurrence of padding is invalid
for (int j = 0; j < 7; j++)
{
Span<byte> buffer = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 }; // valid input - "2222PPPP"
buffer[j] = Base64TestHelper.s_encodingPad;
string sourceString = Encoding.ASCII.GetString(buffer.Slice(0, 4).ToArray());
Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten));
if (j < 4)
{
Assert.Equal(0, bytesWritten);
}
else
{
Assert.Equal(3, bytesWritten);
Span<byte> expectedBytes = Convert.FromBase64String(sourceString);
Assert.True(expectedBytes.SequenceEqual(buffer.Slice(0, bytesWritten)));
}
}
// Invalid input with valid padding
{
Span<byte> buffer = new byte[] { 50, 50, 50, 50, 80, 42, 42, 42 };
buffer[6] = Base64TestHelper.s_encodingPad;
buffer[7] = Base64TestHelper.s_encodingPad; // invalid input - "2222P*=="
string sourceString = Encoding.ASCII.GetString(buffer.Slice(0, 4).ToArray());
Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten));
Assert.Equal(3, bytesWritten);
Span<byte> expectedBytes = Convert.FromBase64String(sourceString);
Assert.True(expectedBytes.SequenceEqual(buffer.Slice(0, bytesWritten)));
}
{
Span<byte> buffer = new byte[] { 50, 50, 50, 50, 80, 42, 42, 42 };
buffer[7] = Base64TestHelper.s_encodingPad; // invalid input - "2222P**="
string sourceString = Encoding.ASCII.GetString(buffer.Slice(0, 4).ToArray());
Assert.Equal(OperationStatus.InvalidData, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten));
Assert.Equal(3, bytesWritten);
Span<byte> expectedBytes = Convert.FromBase64String(sourceString);
Assert.True(expectedBytes.SequenceEqual(buffer.Slice(0, bytesWritten)));
}
// The last byte or the last 2 bytes being the padding character is valid
{
Span<byte> buffer = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 };
buffer[6] = Base64TestHelper.s_encodingPad;
buffer[7] = Base64TestHelper.s_encodingPad; // valid input - "2222PP=="
string sourceString = Encoding.ASCII.GetString(buffer.ToArray());
Assert.Equal(OperationStatus.Done, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten));
Assert.Equal(4, bytesWritten);
Span<byte> expectedBytes = Convert.FromBase64String(sourceString);
Assert.True(expectedBytes.SequenceEqual(buffer.Slice(0, bytesWritten)));
}
{
Span<byte> buffer = new byte[] { 50, 50, 50, 50, 80, 80, 80, 80 };
buffer[7] = Base64TestHelper.s_encodingPad; // valid input - "2222PPP="
string sourceString = Encoding.ASCII.GetString(buffer.ToArray());
Assert.Equal(OperationStatus.Done, Base64.DecodeFromUtf8InPlace(buffer, out int bytesWritten));
Assert.Equal(5, bytesWritten);
Span<byte> expectedBytes = Convert.FromBase64String(sourceString);
Assert.True(expectedBytes.SequenceEqual(buffer.Slice(0, bytesWritten)));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftLeftLogicalUInt1616()
{
var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt1616();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftLeftLogicalUInt1616
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt16);
private const int RetElementCount = VectorSize / sizeof(UInt16);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector128<UInt16> _clsVar;
private Vector128<UInt16> _fld;
private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable;
static SimpleUnaryOpTest__ShiftLeftLogicalUInt1616()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftLeftLogicalUInt1616()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.ShiftLeftLogical(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.ShiftLeftLogical(
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.ShiftLeftLogical(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.ShiftLeftLogical(
_clsVar,
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt1616();
var result = Sse2.ShiftLeftLogical(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.ShiftLeftLogical(_fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
if (0 != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical)}<UInt16>(Vector128<UInt16><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Orleans;
using Orleans.Concurrency;
using Orleans.Configuration;
using Orleans.Core;
using Orleans.Runtime;
using Orleans.Runtime.Scheduler;
using Orleans.Serialization;
using UnitTests.GrainInterfaces;
using Xunit;
using Orleans.Storage;
namespace UnitTests.Grains
{
internal static class TestRuntimeEnvironmentUtility
{
public static string CaptureRuntimeEnvironment()
{
var callStack = Utils.GetStackTrace(1); // Don't include this method in stack trace
return String.Format(
" TaskScheduler={0}" + Environment.NewLine
+ " RuntimeContext={1}" + Environment.NewLine
+ " WorkerPoolThread={2}" + Environment.NewLine
+ " Thread.CurrentThread.ManagedThreadId={4}" + Environment.NewLine
+ " StackTrace=" + Environment.NewLine
+ " {5}",
TaskScheduler.Current,
RuntimeContext.Current,
Thread.CurrentThread.Name,
Thread.CurrentThread.ManagedThreadId,
callStack);
}
}
[Serializable]
public class PersistenceTestGrainState
{
public PersistenceTestGrainState()
{
SortedDict = new SortedDictionary<int, int>();
}
public int Field1 { get; set; }
public string Field2 { get; set; }
public SortedDictionary<int, int> SortedDict { get; set; }
}
[Serializable]
public class PersistenceGenericGrainState<T>
{
public T Field1 { get; set; }
public string Field2 { get; set; }
public SortedDictionary<T, T> SortedDict { get; set; }
}
[Orleans.Providers.StorageProvider(ProviderName = "test1")]
public class PersistenceTestGrain : Grain<PersistenceTestGrainState>, IPersistenceTestGrain
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<bool> CheckStateInit()
{
Assert.NotNull(State);
Assert.Equal(0, State.Field1);
Assert.Null(State.Field2);
//Assert.NotNull(State.Field3, "Null Field3");
//Assert.AreEqual(0, State.Field3.Count, "Field3 = {0}", String.Join("'", State.Field3));
Assert.NotNull(State.SortedDict);
return Task.FromResult(true);
}
public Task<string> CheckProviderType()
{
IGrainStorage grainStorage = this.GetGrainStorage(this.ServiceProvider);
Assert.NotNull(grainStorage);
return Task.FromResult(grainStorage.GetType().FullName);
}
public Task DoSomething()
{
return Task.CompletedTask;
}
public Task DoWrite(int val)
{
State.Field1 = val;
State.SortedDict[val] = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync();
return State.Field1;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public async Task DoDelete()
{
await ClearStateAsync();
}
}
[Orleans.Providers.StorageProvider(ProviderName = "test1")]
public class PersistenceTestGenericGrain<T> : PersistenceTestGrain, IPersistenceTestGenericGrain<T>
{
//...
}
[Orleans.Providers.StorageProvider(ProviderName = "ErrorInjector")]
public class PersistenceProviderErrorGrain : Grain<PersistenceTestGrainState>, IPersistenceProviderErrorGrain
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync();
return State.Field1;
}
public Task<string> GetActivationId() => Task.FromResult(this.Data.ActivationId.ToString());
}
[Orleans.Providers.StorageProvider(ProviderName = "ErrorInjector")]
public class PersistenceUserHandledErrorGrain : Grain<PersistenceTestGrainState>, IPersistenceUserHandledErrorGrain
{
private readonly SerializationManager serializationManager;
private readonly ILogger logger;
public PersistenceUserHandledErrorGrain(ILoggerFactory loggerFactory, SerializationManager serializationManager)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
this.serializationManager = serializationManager;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public async Task DoWrite(int val, bool recover)
{
var original = this.serializationManager.DeepCopy(State);
try
{
State.Field1 = val;
await WriteStateAsync();
}
catch (Exception exc)
{
if (!recover) throw;
this.logger.Warn(0, "Grain is handling error in DoWrite - Resetting value to " + original, exc);
State = (PersistenceTestGrainState)original;
}
}
public async Task<int> DoRead(bool recover)
{
var original = this.serializationManager.DeepCopy(State);
try
{
await ReadStateAsync();
}
catch (Exception exc)
{
if (!recover) throw;
this.logger.Warn(0, "Grain is handling error in DoRead - Resetting value to " + original, exc);
State = (PersistenceTestGrainState)original;
}
return State.Field1;
}
}
public class PersistenceProviderErrorProxyGrain : Grain, IPersistenceProviderErrorProxyGrain
{
public Task<int> GetValue(IPersistenceProviderErrorGrain other) => other.GetValue();
public Task DoWrite(int val, IPersistenceProviderErrorGrain other) => other.DoWrite(val);
public Task<int> DoRead(IPersistenceProviderErrorGrain other) => other.DoRead();
public Task<string> GetActivationId() => Task.FromResult(this.Data.ActivationId.ToString());
}
[Orleans.Providers.StorageProvider(ProviderName = "test1")]
public class PersistenceErrorGrain : Grain<PersistenceTestGrainState>, IPersistenceErrorGrain
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task DoWriteError(int val, bool errorBeforeUpdate)
{
if (errorBeforeUpdate) throw new ApplicationException("Before Update");
State.Field1 = val;
await WriteStateAsync();
throw new ApplicationException("After Update");
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public async Task<int> DoReadError(bool errorBeforeRead)
{
if (errorBeforeRead) throw new ApplicationException("Before Read");
await ReadStateAsync(); // Attempt to re-read state from store
throw new ApplicationException("After Read");
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MissingProvider")]
public class BadProviderTestGrain : Grain<PersistenceTestGrainState>, IBadProviderTestGrain
{
private readonly ILogger logger;
public BadProviderTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
this.logger.Warn(1, "OnActivateAsync");
return Task.CompletedTask;
}
public Task DoSomething()
{
this.logger.Warn(1, "DoSomething");
throw new ApplicationException(
"BadProviderTestGrain.DoSomething should never get called when provider is missing");
}
}
[Orleans.Providers.StorageProvider(ProviderName = "test1")]
public class PersistenceNoStateTestGrain : Grain, IPersistenceNoStateTestGrain
{
private readonly ILogger logger;
public PersistenceNoStateTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
this.logger.Info(1, "OnActivateAsync");
return Task.CompletedTask;
}
public Task DoSomething()
{
this.logger.Info(1, "DoSomething");
return Task.CompletedTask;
}
}
public class ServiceIdGrain : Grain, IServiceIdGrain
{
private readonly IOptions<ClusterOptions> clusterOptions;
public ServiceIdGrain(IOptions<ClusterOptions> clusterOptions)
{
this.clusterOptions = clusterOptions;
}
public Task<string> GetServiceId()
{
return Task.FromResult(clusterOptions.Value.ServiceId);
}
}
[Orleans.Providers.StorageProvider(ProviderName = "GrainStorageForTest")]
public class GrainStorageTestGrain : Grain<PersistenceTestGrainState>,
IGrainStorageTestGrain, IGrainStorageTestGrain_LongKey
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "GrainStorageForTest")]
public class GrainStorageGenericGrain<T> : Grain<PersistenceGenericGrainState<T>>,
IGrainStorageGenericGrain<T>
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<T> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(T val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<T> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "GrainStorageForTest")]
public class GrainStorageTestGrainExtendedKey : Grain<PersistenceTestGrainState>,
IGrainStorageTestGrain_GuidExtendedKey, IGrainStorageTestGrain_LongExtendedKey
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task<string> GetExtendedKeyValue()
{
string extKey;
var pk = this.GetPrimaryKey(out extKey);
return Task.FromResult(extKey);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "DDBStore")]
public class AWSStorageTestGrain : Grain<PersistenceTestGrainState>,
IAWSStorageTestGrain, IAWSStorageTestGrain_LongKey
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task<string> GetActivationId() => Task.FromResult(this.Data.ActivationId.ToString());
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "DDBStore")]
public class AWSStorageGenericGrain<T> : Grain<PersistenceGenericGrainState<T>>,
IAWSStorageGenericGrain<T>
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<T> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(T val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<T> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "DDBStore")]
public class AWSStorageTestGrainExtendedKey : Grain<PersistenceTestGrainState>,
IAWSStorageTestGrain_GuidExtendedKey, IAWSStorageTestGrain_LongExtendedKey
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task<string> GetExtendedKeyValue()
{
string extKey;
var pk = this.GetPrimaryKey(out extKey);
return Task.FromResult(extKey);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync(); // Automatically marks this grain as DeactivateOnIdle
}
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
//[Orleans.Providers.StorageProvider(ProviderName = "AzureStorageEmulator")]
public class MemoryStorageTestGrain : Grain<MemoryStorageTestGrain.NestedPersistenceTestGrainState>,
IMemoryStorageTestGrain
{
public override Task OnActivateAsync()
{
return Task.CompletedTask;
}
public Task<int> GetValue()
{
return Task.FromResult(State.Field1);
}
public Task DoWrite(int val)
{
State.Field1 = val;
return WriteStateAsync();
}
public async Task<int> DoRead()
{
await ReadStateAsync(); // Re-read state from store
return State.Field1;
}
public Task DoDelete()
{
return ClearStateAsync();
}
[Serializable]
public class NestedPersistenceTestGrainState
{
public int Field1 { get; set; }
public string Field2 { get; set; }
public SortedDictionary<int, int> SortedDict { get; set; }
}
}
[Serializable]
public class UserState
{
public UserState()
{
Friends = new List<IUser>();
}
public string Name { get; set; }
public string Status { get; set; }
public List<IUser> Friends { get; set; }
}
[Serializable]
public class DerivedUserState : UserState
{
public int Field1 { get; set; }
public int Field2 { get; set; }
}
/// <summary>
/// Orleans grain implementation class.
/// </summary>
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
//[Orleans.Providers.StorageProvider(ProviderName = "AzureStore")]
//[Orleans.Providers.StorageProvider(ProviderName = "AzureStorageEmulator")]
public class UserGrain : Grain<DerivedUserState>, IUser
{
public Task SetName(string name)
{
State.Name = name;
return WriteStateAsync();
}
public Task<string> GetStatus()
{
return Task.FromResult(String.Format("{0} : {1}", State.Name, State.Status));
}
public Task<string> GetName()
{
return Task.FromResult(State.Name);
}
public Task UpdateStatus(string status)
{
State.Status = status;
return WriteStateAsync();
}
public Task AddFriend(IUser friend)
{
if (!State.Friends.Contains(friend))
State.Friends.Add(friend);
else
throw new Exception("Already a friend.");
return Task.CompletedTask;
}
public Task<List<IUser>> GetFriends()
{
return Task.FromResult(State.Friends);
}
public async Task<string> GetFriendsStatuses()
{
var sb = new StringBuilder();
var promises = new List<Task<string>>();
foreach (var friend in State.Friends)
promises.Add(friend.GetStatus());
var friends = await Task.WhenAll(promises);
foreach (var f in friends)
{
sb.AppendLine(f);
}
return sb.ToString();
}
}
[Serializable]
public class StateForIReentrentGrain
{
public StateForIReentrentGrain()
{
DictOne = new Dictionary<string, int>();
DictTwo = new Dictionary<string, int>();
}
public int One { get; set; }
public int Two { get; set; }
public Dictionary<string, int> DictOne { get; set; }
public Dictionary<string, int> DictTwo { get; set; }
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
[Reentrant]
public class ReentrentGrainWithState : Grain<StateForIReentrentGrain>, IReentrentGrainWithState
{
private const int Multiple = 100;
private IReentrentGrainWithState _other;
private ISchedulingContext _context;
private TaskScheduler _scheduler;
private ILogger logger;
private bool executing;
private Task outstandingWriteStateOperation;
public ReentrentGrainWithState(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
_context = RuntimeContext.Current.ActivationContext;
_scheduler = TaskScheduler.Current;
executing = false;
return base.OnActivateAsync();
}
// When reentrant grain is doing WriteStateAsync, etag violations are posssible due to concurent writes.
// The solution is to serialize all writes, and make sure only a single write is outstanind at any moment in time.
// No deadlocks are posssible with that approach, since all WriteStateAsync go to the store, which does not issue call into grains,
// thus cycle of calls is not posssible.
// Implementaton: need to use While and not if, due to the same "early check becomes later invalid" standard problem, like in conditional variables.
private async Task PerformSerializedStateUpdate()
{
while (outstandingWriteStateOperation != null)
{
await outstandingWriteStateOperation;
}
outstandingWriteStateOperation = WriteStateAsync();
await outstandingWriteStateOperation;
outstandingWriteStateOperation = null;
}
public Task Setup(IReentrentGrainWithState other)
{
logger.Info("Setup");
_other = other;
return Task.CompletedTask;
}
public async Task SetOne(int val)
{
logger.Info("SetOne Start");
CheckRuntimeEnvironment();
var iStr = val.ToString(CultureInfo.InvariantCulture);
State.One = val;
State.DictOne[iStr] = val;
State.DictTwo[iStr] = val;
CheckRuntimeEnvironment();
await PerformSerializedStateUpdate();
CheckRuntimeEnvironment();
}
public async Task SetTwo(int val)
{
logger.Info("SetTwo Start");
CheckRuntimeEnvironment();
var iStr = val.ToString(CultureInfo.InvariantCulture);
State.Two = val;
State.DictTwo[iStr] = val;
State.DictOne[iStr] = val;
CheckRuntimeEnvironment();
await PerformSerializedStateUpdate();
CheckRuntimeEnvironment();
}
public async Task Test1()
{
logger.Info(" ==================================== Test1 Started");
CheckRuntimeEnvironment();
for (var i = 1*Multiple; i < 2*Multiple; i++)
{
var t1 = SetOne(i);
await t1;
CheckRuntimeEnvironment();
var t2 = PerformSerializedStateUpdate();
await t2;
CheckRuntimeEnvironment();
var t3 = _other.SetTwo(i);
await t3;
CheckRuntimeEnvironment();
var t4 = PerformSerializedStateUpdate();
await t4;
CheckRuntimeEnvironment();
}
CheckRuntimeEnvironment();
logger.Info(" ==================================== Test1 Done");
}
public async Task Test2()
{
logger.Info("==================================== Test2 Started");
CheckRuntimeEnvironment();
for (var i = 2*Multiple; i < 3*Multiple; i++)
{
var t1 = _other.SetOne(i);
await t1;
CheckRuntimeEnvironment();
var t2 = PerformSerializedStateUpdate();
await t2;
CheckRuntimeEnvironment();
var t3 = SetTwo(i);
await t3;
CheckRuntimeEnvironment();
var t4 = PerformSerializedStateUpdate();
await t4;
CheckRuntimeEnvironment();
}
CheckRuntimeEnvironment();
logger.Info(" ==================================== Test2 Done");
}
public async Task Task_Delay(bool doStart)
{
var wrapper = new Task(async () =>
{
logger.Info("Before Task.Delay #1 TaskScheduler.Current=" + TaskScheduler.Current);
await DoDelay(1);
logger.Info("After Task.Delay #1 TaskScheduler.Current=" + TaskScheduler.Current);
await DoDelay(2);
logger.Info("After Task.Delay #2 TaskScheduler.Current=" + TaskScheduler.Current);
});
if (doStart)
{
wrapper.Start(); // THIS IS THE KEY STEP!
}
await wrapper;
}
private async Task DoDelay(int i)
{
logger.Info("Before Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current);
await Task.Delay(1);
logger.Info("After Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current);
}
private void CheckRuntimeEnvironment()
{
if (executing)
{
var errorMsg = "Found out that this grain is already in the middle of execution."
+ " Single threaded-ness violation!\n" +
TestRuntimeEnvironmentUtility.CaptureRuntimeEnvironment();
this.logger.Error(1, "\n\n\n\n" + errorMsg + "\n\n\n\n");
throw new Exception(errorMsg);
//Environment.Exit(1);
}
if (RuntimeContext.Current == null || RuntimeContext.Current.ActivationContext == null)
{
var errorMsg = "Found RuntimeContext.Current == null.\n" + TestRuntimeEnvironmentUtility.CaptureRuntimeEnvironment();
this.logger.Error(1, "\n\n\n\n" + errorMsg + "\n\n\n\n");
throw new Exception(errorMsg);
//Environment.Exit(1);
}
var context = RuntimeContext.Current.ActivationContext;
var scheduler = TaskScheduler.Current;
executing = true;
Assert.Equal(_scheduler, scheduler);
Assert.Equal(_context, context);
Assert.NotNull(context);
executing = false;
}
}
internal class NonReentrentStressGrainWithoutState : Grain, INonReentrentStressGrainWithoutState
{
private readonly OrleansTaskScheduler scheduler;
private const int Multiple = 100;
private ILogger logger;
private bool executing;
private const int LEVEL = 2; // level 2 is enough to repro the problem.
private static int _counter = 1;
private int _id;
// HACK for testing
private readonly Tuple<string, Severity>[] overridesOn =
{
new Tuple<string, Severity>("Scheduler", Severity.Verbose),
new Tuple<string, Severity>("Scheduler.ActivationTaskScheduler", Severity.Verbose3)
};
private readonly Tuple<string, Severity>[] overridesOff =
{
new Tuple<string, Severity>("Scheduler", Severity.Info),
new Tuple<string, Severity>("Scheduler.ActivationTaskScheduler", Severity.Info)
};
public NonReentrentStressGrainWithoutState(OrleansTaskScheduler scheduler)
{
this.scheduler = scheduler;
}
private NonReentrentStressGrainWithoutState(IGrainIdentity identity, IGrainRuntime runtime)
: base(identity, runtime)
{
}
public static NonReentrentStressGrainWithoutState Create(IGrainIdentity identity, IGrainRuntime runtime)
=> new NonReentrentStressGrainWithoutState(identity, runtime);
public override Task OnActivateAsync()
{
_id = _counter++;
var loggerFactory = this.ServiceProvider?.GetService<ILoggerFactory>();
//if grain created outside a cluster
if (loggerFactory == null)
loggerFactory = NullLoggerFactory.Instance;
logger = loggerFactory.CreateLogger($"NonReentrentStressGrainWithoutState-{_id}");
executing = false;
Log("--> OnActivateAsync");
//#if DEBUG
// // HACK for testing
// Logger.SetTraceLevelOverrides(overridesOn.ToList());
//#endif
Log("<-- OnActivateAsync");
return base.OnActivateAsync();
}
private async Task SetOne(int iter, int level)
{
Log(String.Format("---> SetOne {0}-{1}_0", iter, level));
CheckRuntimeEnvironment("SetOne");
if (level > 0)
{
Log("SetOne {0}-{1}_1. Before await Task.Done.", iter, level);
await Task.CompletedTask;
Log("SetOne {0}-{1}_2. After await Task.Done.", iter, level);
CheckRuntimeEnvironment(String.Format("SetOne {0}-{1}_3", iter, level));
Log("SetOne {0}-{1}_4. Before await Task.Delay.", iter, level);
await Task.Delay(TimeSpan.FromMilliseconds(10));
Log("SetOne {0}-{1}_5. After await Task.Delay.", iter, level);
CheckRuntimeEnvironment(String.Format("SetOne {0}-{1}_6", iter, level));
var nextLevel = level - 1;
await SetOne(iter, nextLevel);
Log("SetOne {0}-{1}_7 => {2}. After await SetOne call.", iter, level, nextLevel);
CheckRuntimeEnvironment(String.Format("SetOne {0}-{1}_8", iter, level));
Log("SetOne {0}-{1}_9. Finished SetOne.", iter, level);
}
CheckRuntimeEnvironment(String.Format("SetOne {0}-{1}_10", iter, level));
Log("<--- SetOne {0}-{1}_11", iter, level);
}
public async Task Test1()
{
Log(String.Format("Test1.Start"));
CheckRuntimeEnvironment("Test1.BeforeLoop");
var tasks = new List<Task>();
for (var i = 0; i < Multiple; i++)
{
Log("Test1_ ------>" + i);
CheckRuntimeEnvironment(String.Format("Test1_{0}_0", i));
var task = SetOne(i, LEVEL);
Log("After SetOne call " + i);
CheckRuntimeEnvironment(String.Format("Test1_{0}_1", i));
tasks.Add(task);
CheckRuntimeEnvironment(String.Format("Test1_{0}_2", i));
Log("Test1_ <------" + i);
}
CheckRuntimeEnvironment("Test1.AfterLoop");
Log(String.Format("Test1_About to WhenAll"));
await Task.WhenAll(tasks);
Log(String.Format("Test1.Finish"));
CheckRuntimeEnvironment("Test1.Finish-CheckRuntimeEnvironment");
//#if DEBUG
// // HACK for testing
// Logger.SetTraceLevelOverrides(overridesOff.ToList());
//#endif
}
public async Task Task_Delay(bool doStart)
{
var wrapper = new Task(async () =>
{
logger.Info("Before Task.Delay #1 TaskScheduler.Current=" + TaskScheduler.Current);
await DoDelay(1);
logger.Info("After Task.Delay #1 TaskScheduler.Current=" + TaskScheduler.Current);
await DoDelay(2);
logger.Info("After Task.Delay #2 TaskScheduler.Current=" + TaskScheduler.Current);
});
if (doStart)
{
wrapper.Start(); // THIS IS THE KEY STEP!
}
await wrapper;
}
private async Task DoDelay(int i)
{
logger.Info("Before Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current);
await Task.Delay(1);
logger.Info("After Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current);
}
private void CheckRuntimeEnvironment(string str)
{
var callStack = new StackTrace();
//Log("CheckRuntimeEnvironment - {0} Executing={1}", str, executing);
if (executing)
{
var errorMsg = string.Format(
"Found out that grain {0} is already in the middle of execution."
+ "\n Single threaded-ness violation!"
+ "\n {1} \n Call Stack={2}",
this._id,
TestRuntimeEnvironmentUtility.CaptureRuntimeEnvironment(),
callStack);
this.logger.Error(1, "\n\n\n\n" + errorMsg + "\n\n\n\n");
this.scheduler.DumpSchedulerStatus();
//Environment.Exit(1);
throw new Exception(errorMsg);
}
//Assert.IsFalse(executing, "Found out that this grain is already in the middle of execution. Single threaded-ness violation!");
executing = true;
//Log("CheckRuntimeEnvironment - Start sleep " + str);
Thread.Sleep(10);
executing = false;
//Log("CheckRuntimeEnvironment - End sleep " + str);
}
private void Log(string fmt, params object[] args)
{
var msg = fmt; // +base.CaptureRuntimeEnvironment();
logger.Info(msg, args);
}
}
[Serializable]
public class InternalGrainStateData
{
public int One { get; set; }
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
internal class InternalGrainWithState : Grain<InternalGrainStateData>, IInternalGrainWithState
{
private ILogger logger;
public InternalGrainWithState(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public Task SetOne(int val)
{
logger.Info("SetOne");
State.One = val;
return Task.CompletedTask;
}
}
public interface IBaseStateData // Note: I am deliberately not using IGrainState here.
{
int Field1 { get; set; }
}
[Serializable]
public class StateInheritanceTestGrainData : IBaseStateData
{
private int Field2 { get; set; }
public int Field1 { get; set; }
}
[Orleans.Providers.StorageProvider(ProviderName = "MemoryStore")]
public class StateInheritanceTestGrain : Grain<StateInheritanceTestGrainData>, IStateInheritanceTestGrain
{
private ILogger logger;
public StateInheritanceTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
logger.Info("OnActivateAsync");
return base.OnActivateAsync();
}
public Task<int> GetValue()
{
var val = State.Field1;
logger.Info("GetValue {0}", val);
return Task.FromResult(val);
}
public Task SetValue(int val)
{
State.Field1 = val;
logger.Info("SetValue {0}", val);
return WriteStateAsync();
}
}
public class SerializationTestGrain : Grain, ISerializationTestGrain
{
private static int _staticFilterValue1 = 41;
private static int _staticFilterValue2 = 42;
private static int _staticFilterValue3 = 43;
private static int _staticFilterValue4 = 44;
private readonly int _instanceFilterValue2 = _staticFilterValue2;
private readonly ILogger logger;
private readonly SerializationManager serializationManager;
public SerializationTestGrain(ILoggerFactory loggerFactory, SerializationManager serializationManager)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
this.serializationManager = serializationManager;
}
public Task Test_Serialize_Func()
{
Func<int, bool> staticFilterFunc = i => i == _staticFilterValue3;
//int instanceFilterValue2 = _staticFilterValue2;
//
//Func<int, bool> instanceFilterFunc = i => i == instanceFilterValue2;
Func<int, bool> staticFuncInGrainClass = PredFuncStatic;
//Func<int, bool> instanceFuncInGrainClass = this.PredFuncInstance;
// Works OK
TestSerializeFuncPtr("Func Lambda - Static field", staticFilterFunc);
TestSerializeFuncPtr("Static Func In Grain Class", staticFuncInGrainClass);
// Fails
//TestSerializeFuncPtr("Instance Func In Grain Class", instanceFuncInGrainClass);
//TestSerializeFuncPtr("Func Lambda - Instance field", instanceFilterFunc);
return Task.CompletedTask;
}
public Task Test_Serialize_Predicate()
{
Predicate<int> staticPredicate = i => i == _staticFilterValue2;
//int instanceFilterValue2 = _staticFilterValue2;
//
//Predicate<int> instancePredicate = i => i == instanceFilterValue2;
// Works OK
TestSerializePredicate("Predicate Lambda - Static field", staticPredicate);
// Fails
//TestSerializePredicate("Predicate Lambda - Instance field", instancePredicate);
return Task.CompletedTask;
}
public Task Test_Serialize_Predicate_Class()
{
IMyPredicate pred = new MyPredicate(_staticFilterValue2);
// Works OK
TestSerializePredicate("Predicate Class Instance", pred.FilterFunc);
return Task.CompletedTask;
}
public Task Test_Serialize_Predicate_Class_Param(IMyPredicate pred)
{
// Works OK
TestSerializePredicate("Predicate Class Instance passed as param", pred.FilterFunc);
return Task.CompletedTask;
}
// Utility methods
private void TestSerializeFuncPtr(string what, Func<int, bool> func1)
{
object obj2 = this.serializationManager.RoundTripSerializationForTesting(func1);
var func2 = (Func<int, bool>) obj2;
foreach (
var val in new[] {_staticFilterValue1, _staticFilterValue2, _staticFilterValue3, _staticFilterValue4})
{
logger.LogDebug("{0} -- Compare value={1}", what, val);
Assert.Equal(func1(val), func2(val));
}
}
private void TestSerializePredicate(string what, Predicate<int> pred1)
{
object obj2 = this.serializationManager.RoundTripSerializationForTesting(pred1);
var pred2 = (Predicate<int>) obj2;
foreach (
var val in new[] {_staticFilterValue1, _staticFilterValue2, _staticFilterValue3, _staticFilterValue4})
{
logger.LogDebug("{0} -- Compare value={1}", what, val);
Assert.Equal(pred1(val), pred2(val));
}
}
public bool PredFuncInstance(int i)
{
return i == _instanceFilterValue2;
}
public static bool PredFuncStatic(int i)
{
return i == _staticFilterValue2;
}
}
}
| |
// 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.Xml.XPath;
namespace MS.Internal.Xml.Cache
{
/// <summary>
/// Base internal class of all XPathDocument XPathNodeIterator implementations.
/// </summary>
internal abstract class XPathDocumentBaseIterator : XPathNodeIterator
{
protected XPathDocumentNavigator ctxt;
protected int pos;
/// <summary>
/// Create a new iterator that is initially positioned on the "ctxt" node.
/// </summary>
protected XPathDocumentBaseIterator(XPathDocumentNavigator ctxt)
{
this.ctxt = new XPathDocumentNavigator(ctxt);
}
/// <summary>
/// Create a new iterator that is a copy of "iter".
/// </summary>
protected XPathDocumentBaseIterator(XPathDocumentBaseIterator iter)
{
this.ctxt = new XPathDocumentNavigator(iter.ctxt);
this.pos = iter.pos;
}
/// <summary>
/// Return the current navigator.
/// </summary>
public override XPathNavigator Current
{
get { return this.ctxt; }
}
/// <summary>
/// Return the iterator's current position.
/// </summary>
public override int CurrentPosition
{
get { return this.pos; }
}
}
/// <summary>
/// Iterate over all element children with a particular QName.
/// </summary>
internal class XPathDocumentElementChildIterator : XPathDocumentBaseIterator
{
private string _localName, _namespaceUri;
/// <summary>
/// Create an iterator that ranges over all element children of "parent" having the specified QName.
/// </summary>
public XPathDocumentElementChildIterator(XPathDocumentNavigator parent, string name, string namespaceURI) : base(parent)
{
if (namespaceURI == null) throw new ArgumentNullException("namespaceURI");
_localName = parent.NameTable.Get(name);
_namespaceUri = namespaceURI;
}
/// <summary>
/// Create a new iterator that is a copy of "iter".
/// </summary>
public XPathDocumentElementChildIterator(XPathDocumentElementChildIterator iter) : base(iter)
{
_localName = iter._localName;
_namespaceUri = iter._namespaceUri;
}
/// <summary>
/// Create a copy of this iterator.
/// </summary>
public override XPathNodeIterator Clone()
{
return new XPathDocumentElementChildIterator(this);
}
/// <summary>
/// Position the iterator to the next matching child.
/// </summary>
public override bool MoveNext()
{
if (this.pos == 0)
{
if (!this.ctxt.MoveToChild(_localName, _namespaceUri))
return false;
}
else
{
if (!this.ctxt.MoveToNext(_localName, _namespaceUri))
return false;
}
this.pos++;
return true;
}
}
/// <summary>
/// Iterate over all content children with a particular XPathNodeType.
/// </summary>
internal class XPathDocumentKindChildIterator : XPathDocumentBaseIterator
{
private XPathNodeType _typ;
/// <summary>
/// Create an iterator that ranges over all content children of "parent" having the specified XPathNodeType.
/// </summary>
public XPathDocumentKindChildIterator(XPathDocumentNavigator parent, XPathNodeType typ) : base(parent)
{
_typ = typ;
}
/// <summary>
/// Create a new iterator that is a copy of "iter".
/// </summary>
public XPathDocumentKindChildIterator(XPathDocumentKindChildIterator iter) : base(iter)
{
_typ = iter._typ;
}
/// <summary>
/// Create a copy of this iterator.
/// </summary>
public override XPathNodeIterator Clone()
{
return new XPathDocumentKindChildIterator(this);
}
/// <summary>
/// Position the iterator to the next descendant.
/// </summary>
public override bool MoveNext()
{
if (this.pos == 0)
{
if (!this.ctxt.MoveToChild(_typ))
return false;
}
else
{
if (!this.ctxt.MoveToNext(_typ))
return false;
}
this.pos++;
return true;
}
}
/// <summary>
/// Iterate over all element descendants with a particular QName.
/// </summary>
internal class XPathDocumentElementDescendantIterator : XPathDocumentBaseIterator
{
private XPathDocumentNavigator _end;
private string _localName, _namespaceUri;
private bool _matchSelf;
/// <summary>
/// Create an iterator that ranges over all element descendants of "root" having the specified QName.
/// </summary>
public XPathDocumentElementDescendantIterator(XPathDocumentNavigator root, string name, string namespaceURI, bool matchSelf) : base(root)
{
if (namespaceURI == null) throw new ArgumentNullException("namespaceURI");
_localName = root.NameTable.Get(name);
_namespaceUri = namespaceURI;
_matchSelf = matchSelf;
// Find the next non-descendant node that follows "root" in document order
if (root.NodeType != XPathNodeType.Root)
{
_end = new XPathDocumentNavigator(root);
_end.MoveToNonDescendant();
}
}
/// <summary>
/// Create a new iterator that is a copy of "iter".
/// </summary>
public XPathDocumentElementDescendantIterator(XPathDocumentElementDescendantIterator iter) : base(iter)
{
_end = iter._end;
_localName = iter._localName;
_namespaceUri = iter._namespaceUri;
_matchSelf = iter._matchSelf;
}
/// <summary>
/// Create a copy of this iterator.
/// </summary>
public override XPathNodeIterator Clone()
{
return new XPathDocumentElementDescendantIterator(this);
}
/// <summary>
/// Position the iterator to the next descendant.
/// </summary>
public override bool MoveNext()
{
if (_matchSelf)
{
_matchSelf = false;
if (this.ctxt.IsElementMatch(_localName, _namespaceUri))
{
this.pos++;
return true;
}
}
if (!this.ctxt.MoveToFollowing(_localName, _namespaceUri, _end))
return false;
this.pos++;
return true;
}
}
/// <summary>
/// Iterate over all content descendants with a particular XPathNodeType.
/// </summary>
internal class XPathDocumentKindDescendantIterator : XPathDocumentBaseIterator
{
private XPathDocumentNavigator _end;
private XPathNodeType _typ;
private bool _matchSelf;
/// <summary>
/// Create an iterator that ranges over all content descendants of "root" having the specified XPathNodeType.
/// </summary>
public XPathDocumentKindDescendantIterator(XPathDocumentNavigator root, XPathNodeType typ, bool matchSelf) : base(root)
{
_typ = typ;
_matchSelf = matchSelf;
// Find the next non-descendant node that follows "root" in document order
if (root.NodeType != XPathNodeType.Root)
{
_end = new XPathDocumentNavigator(root);
_end.MoveToNonDescendant();
}
}
/// <summary>
/// Create a new iterator that is a copy of "iter".
/// </summary>
public XPathDocumentKindDescendantIterator(XPathDocumentKindDescendantIterator iter) : base(iter)
{
_end = iter._end;
_typ = iter._typ;
_matchSelf = iter._matchSelf;
}
/// <summary>
/// Create a copy of this iterator.
/// </summary>
public override XPathNodeIterator Clone()
{
return new XPathDocumentKindDescendantIterator(this);
}
/// <summary>
/// Position the iterator to the next descendant.
/// </summary>
public override bool MoveNext()
{
if (_matchSelf)
{
_matchSelf = false;
if (this.ctxt.IsKindMatch(_typ))
{
this.pos++;
return true;
}
}
if (!this.ctxt.MoveToFollowing(_typ, _end))
return false;
this.pos++;
return true;
}
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
namespace Alphaleonis.Win32.Filesystem
{
partial class Directory
{
/// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
/// <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
/// <para><b>Total:</b> is the total number of enumerated objects.</para>
/// <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
/// <para><b>Size:</b> is the total size of enumerated objects.</para>
/// <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
/// </summary>
/// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
/// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The target directory.</param>
[SecurityCritical]
public static Dictionary<string, long> GetProperties(string path)
{
return GetPropertiesCore(null, path, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
/// <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
/// <para><b>Total:</b> is the total number of enumerated objects.</para>
/// <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
/// <para><b>Size:</b> is the total size of enumerated objects.</para>
/// <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
/// </summary>
/// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
/// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The target directory.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static Dictionary<string, long> GetProperties(string path, PathFormat pathFormat)
{
return GetPropertiesCore(null, path, DirectoryEnumerationOptions.FilesAndFolders, pathFormat);
}
/// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
/// <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
/// <para><b>Total:</b> is the total number of enumerated objects.</para>
/// <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
/// <para><b>Size:</b> is the total size of enumerated objects.</para>
/// <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
/// </summary>
/// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
/// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The target directory.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static Dictionary<string, long> GetProperties(string path, DirectoryEnumerationOptions options)
{
return GetPropertiesCore(null, path, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
/// <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
/// <para><b>Total:</b> is the total number of enumerated objects.</para>
/// <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
/// <para><b>Size:</b> is the total size of enumerated objects.</para>
/// <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
/// </summary>
/// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
/// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="path">The target directory.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static Dictionary<string, long> GetProperties(string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
return GetPropertiesCore(null, path, options, pathFormat);
}
#region Transactional
/// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
/// <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
/// <para><b>Total:</b> is the total number of enumerated objects.</para>
/// <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
/// <para><b>Size:</b> is the total size of enumerated objects.</para>
/// <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
/// </summary>
/// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
/// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The target directory.</param>
[SecurityCritical]
public static Dictionary<string, long> GetPropertiesTransacted(KernelTransaction transaction, string path)
{
return GetPropertiesCore(transaction, path, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
/// <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
/// <para><b>Total:</b> is the total number of enumerated objects.</para>
/// <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
/// <para><b>Size:</b> is the total size of enumerated objects.</para>
/// <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
/// </summary>
/// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
/// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The target directory.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static Dictionary<string, long> GetPropertiesTransacted(KernelTransaction transaction, string path, PathFormat pathFormat)
{
return GetPropertiesCore(transaction, path, DirectoryEnumerationOptions.FilesAndFolders, pathFormat);
}
/// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
/// <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
/// <para><b>Total:</b> is the total number of enumerated objects.</para>
/// <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
/// <para><b>Size:</b> is the total size of enumerated objects.</para>
/// <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
/// </summary>
/// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
/// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The target directory.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SecurityCritical]
public static Dictionary<string, long> GetPropertiesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options)
{
return GetPropertiesCore(transaction, path, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
/// <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
/// <para><b>Total:</b> is the total number of enumerated objects.</para>
/// <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
/// <para><b>Size:</b> is the total size of enumerated objects.</para>
/// <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
/// </summary>
/// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
/// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The target directory.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
public static Dictionary<string, long> GetPropertiesTransacted(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
return GetPropertiesCore(transaction, path, options, pathFormat);
}
#endregion // Transactional
#region Internal Methods
/// <summary>[AlphaFS] Gets the properties of the particular directory without following any symbolic links or mount points.
/// <para>Properties include aggregated info from <see cref="FileAttributes"/> of each encountered file system object, plus additional ones: Total, File, Size and Error.</para>
/// <para><b>Total:</b> is the total number of enumerated objects.</para>
/// <para><b>File:</b> is the total number of files. File is considered when object is neither <see cref="FileAttributes.Directory"/> nor <see cref="FileAttributes.ReparsePoint"/>.</para>
/// <para><b>Size:</b> is the total size of enumerated objects.</para>
/// <para><b>Error:</b> is the total number of errors encountered during enumeration.</para>
/// </summary>
/// <returns>A dictionary mapping the keys mentioned above to their respective aggregated values.</returns>
/// <remarks><b>Directory:</b> is an object which has <see cref="FileAttributes.Directory"/> attribute without <see cref="FileAttributes.ReparsePoint"/> one.</remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The target directory.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
internal static Dictionary<string, long> GetPropertiesCore(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
long total = 0;
long size = 0;
const string propFile = "File";
const string propTotal = "Total";
const string propSize = "Size";
Type typeOfAttrs = typeof(FileAttributes);
Array attributes = Enum.GetValues(typeOfAttrs);
Dictionary<string, long> props = Enum.GetNames(typeOfAttrs).OrderBy(attrs => attrs).ToDictionary<string, string, long>(name => name, name => 0);
string pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);
foreach (var fsei in EnumerateFileSystemEntryInfosCore<FileSystemEntryInfo>(transaction, pathLp, Path.WildcardStarMatchAll, options, PathFormat.LongFullPath))
{
total++;
if (!fsei.IsDirectory)
size += fsei.FileSize;
var fsei1 = fsei;
foreach (FileAttributes attributeMarker in attributes.Cast<FileAttributes>().Where(attributeMarker => (fsei1.Attributes & attributeMarker) != 0))
{
props[(((attributeMarker & FileAttributes.Directory) != 0) ? FileAttributes.Directory : attributeMarker).ToString()]++;
}
}
// Adjust regular files count.
props.Add(propFile, total - props[FileAttributes.Directory.ToString()] - props[FileAttributes.ReparsePoint.ToString()]);
props.Add(propTotal, total);
props.Add(propSize, size);
return props;
}
#endregion // Internal Methods
}
}
| |
S/W Version Information
Model: Ref.Device-PQ
Tizen-Version: 2.2.1
Build-Number: Tizen_Ref.Device-PQ_20131107.2323
Build-Date: 2013.11.07 23:23:19
Crash Information
Process Name: QRDemo
PID: 24630
Date: 2013-11-30 10:50:00(GMT+0400)
Executable File Path: /opt/apps/vd84JCg9vN/bin/QRDemo
This process is multi-thread process
pid=24630 tid=24630
Signal: 11
(SIGSEGV)
si_code: -6
signal sent by tkill (sent by pid 24630, uid 5000)
Register Information
r0 = 0x00000010, r1 = 0x003a0a88
r2 = 0x003a0a88, r3 = 0x0016f76e
r4 = 0x00000010, r5 = 0x003a0a88
r6 = 0x001d96a0, r7 = 0x001d5148
r8 = 0xabf0af18, r9 = 0x000e46e0
r10 = 0xb447c940, fp = 0xbebc8d10
ip = 0xb430d1c5, sp = 0xbebc8cd8
lr = 0xb26ac218, pc = 0xb430d1cc
cpsr = 0x60000030
Memory Information
MemTotal: 797320 KB
MemFree: 33884 KB
Buffers: 15884 KB
Cached: 316064 KB
VmPeak: 264948 KB
VmSize: 229564 KB
VmLck: 0 KB
VmHWM: 40884 KB
VmRSS: 40884 KB
VmData: 113672 KB
VmStk: 136 KB
VmExe: 32 KB
VmLib: 79928 KB
VmPTE: 166 KB
VmSwap: 0 KB
Maps Information
00008000 00010000 r-xp /usr/bin/launchpad_preloading_preinitializing_daemon
00018000 000dc000 rw-p [heap]
000dc000 003c0000 rw-p [heap]
ac993000 ac9c6000 r-xp /usr/lib/gstreamer-0.10/libgstcoreelements.so
ac9cf000 aca05000 r-xp /usr/lib/gstreamer-0.10/libgstcamerasrc.so
ae35a000 ae35d000 r-xp /usr/lib/bufmgr/libtbm_exynos4412.so.0.0.0
afba5000 afbf0000 r-xp /usr/lib/libGLESv1_CM.so.1.1
afbf9000 afc21000 r-xp /usr/lib/evas/modules/engines/gl_x11/linux-gnueabi-armv7l-1.7.99/module.so
afd77000 afd83000 r-xp /usr/lib/libtzsvc.so.0.0.1
afd90000 afd92000 r-xp /usr/lib/libemail-network.so.1.1.0
afd9a000 afe44000 r-xp /usr/lib/libuw-imap-toolkit.so.0.0.0
afe52000 afe56000 r-xp /usr/lib/libss-client.so.1.0.0
afe5e000 afe63000 r-xp /usr/lib/libmmutil_jpeg.so.0.0.0
afe6c000 afe86000 r-xp /usr/lib/libnfc.so.1.0.0
afe8e000 afe9f000 r-xp /usr/lib/libnfc-common-lib.so.1.0.0
afea8000 afece000 r-xp /usr/lib/libbluetooth-api.so.1.0.0
afed7000 afefd000 r-xp /usr/lib/libzmq.so.3.0.0
aff07000 aff10000 r-xp /usr/lib/libpims-ipc.so.0.0.30
aff18000 aff1d000 r-xp /usr/lib/libmemenv.so.1.1.0
aff25000 aff63000 r-xp /usr/lib/libleveldb.so.1.1.0
aff6c000 aff74000 r-xp /usr/lib/libgstfft-0.10.so.0.25.0
aff7c000 affa6000 r-xp /usr/lib/libgstaudio-0.10.so.0.25.0
affaf000 affbe000 r-xp /usr/lib/libgstvideo-0.10.so.0.25.0
affc6000 affde000 r-xp /usr/lib/libgstpbutils-0.10.so.0.25.0
affe0000 b0005000 r-xp /usr/lib/libxslt.so.1.1.16
b000e000 b0012000 r-xp /usr/lib/libeukit.so.1.7.99
b001a000 b0022000 r-xp /usr/lib/libui-gadget-1.so.0.1.0
b002a000 b0033000 r-xp /usr/lib/libmsg_vobject.so
b003c000 b0046000 r-xp /usr/lib/libdrm-client.so.0.0.1
b004e000 b0067000 r-xp /usr/lib/libmsg_plugin_manager.so
b0070000 b00a9000 r-xp /usr/lib/libmsg_framework_handler.so
b00b2000 b00e6000 r-xp /usr/lib/libmsg_transaction_proxy.so
b00ef000 b012f000 r-xp /usr/lib/libmsg_utils.so
b0130000 b013f000 r-xp /usr/lib/libemail-common-use.so.1.1.0
b0148000 b01c3000 r-xp /usr/lib/libemail-core.so.1.1.0
b01d3000 b021c000 r-xp /usr/lib/libemail-storage.so.1.1.0
b0225000 b0232000 r-xp /usr/lib/libemail-ipc.so.1.1.0
b023a000 b0264000 r-xp /usr/lib/libSLP-location.so.0.0.0
b026d000 b0276000 r-xp /usr/lib/libdownload-provider-interface.so.1.1.6
b027e000 b0285000 r-xp /usr/lib/libmedia-utils.so.0.0.0
b028d000 b028f000 r-xp /usr/lib/libmedia-hash.so.1.0.0
b0297000 b02b0000 r-xp /usr/lib/libmedia-thumbnail.so.1.0.0
b02b8000 b02ba000 r-xp /usr/lib/libmedia-svc-hash.so.1.0.0
b02c2000 b02da000 r-xp /usr/lib/libmedia-service.so.1.0.0
b02e2000 b02f6000 r-xp /usr/lib/libnetwork.so.0.0.0
b02ff000 b030a000 r-xp /usr/lib/libstt.so
b0312000 b0318000 r-xp /usr/lib/libbadge.so.0.0.1
b0320000 b0326000 r-xp /usr/lib/libcapi-appfw-app-manager.so.0.1.0
b032e000 b0334000 r-xp /usr/lib/libshortcut.so.0.0.1
b033d000 b0340000 r-xp /usr/lib/libminicontrol-provider.so.0.0.1
b0348000 b0353000 r-xp /usr/lib/liblivebox-service.so.0.0.1
b035b000 b0370000 r-xp /usr/lib/liblivebox-viewer.so.0.0.1
b0378000 b037c000 r-xp /usr/lib/libcapi-appfw-package-manager.so.0.0.30
b0384000 b05a1000 r-xp /usr/lib/libface-engine-plugin.so
b05ff000 b0605000 r-xp /usr/lib/libcapi-network-nfc.so.0.0.11
b060e000 b0625000 r-xp /usr/lib/libcapi-network-bluetooth.so.0.1.40
b062d000 b0635000 r-xp /usr/lib/libcapi-network-wifi.so.0.1.2_24
b063d000 b0656000 r-xp /usr/lib/libaccounts-svc.so.0.2.66
b065e000 b06d0000 r-xp /usr/lib/libcontacts-service2.so.0.9.114.7
b06ef000 b0732000 r-xp /usr/lib/libcalendar-service2.so.0.1.44
b073c000 b0744000 r-xp /usr/lib/libcapi-web-favorites.so
b0745000 b1947000 r-xp /usr/lib/libewebkit2.so.0.11.113
b1a2c000 b1a34000 r-xp /usr/lib/libpush.so.0.2.12
b1a3c000 b1a57000 r-xp /usr/lib/libmsg_mapi.so.0.1.0
b1a60000 b1a78000 r-xp /usr/lib/libemail-api.so.1.1.0
b1a80000 b1a89000 r-xp /usr/lib/libcapi-system-sensor.so.0.1.17
b1a92000 b1a95000 r-xp /usr/lib/libcapi-telephony-sim.so.0.1.7
b1a9d000 b1aa0000 r-xp /usr/lib/libcapi-telephony-network-info.so.0.1.0
b1aa9000 b1ab4000 r-xp /usr/lib/libcapi-location-manager.so.0.1.11
b1abc000 b1ac0000 r-xp /usr/lib/libcapi-web-url-download.so.0.1.0
b1ac8000 b1ae9000 r-xp /usr/lib/libcapi-content-media-content.so.0.2.59
b1af1000 b1af3000 r-xp /usr/lib/libcamsrcjpegenc.so.0.0.0
b1afb000 b1b0f000 r-xp /usr/lib/libwifi-direct.so.0.0
b1b17000 b1b1f000 r-xp /usr/lib/libcapi-network-tethering.so.0.1.0
b1b20000 b1b29000 r-xp /usr/lib/libcapi-network-connection.so.0.1.3_18
b1b31000 b1b65000 r-xp /usr/lib/libopenal.so.1.13.0
b1b6e000 b1b71000 r-xp /usr/lib/libalut.so.0.1.0
b1b7b000 b1b80000 r-xp /usr/lib/osp/libosp-speech-stt.so.1.2.2.0
b1b88000 b1ba6000 r-xp /usr/lib/osp/libosp-shell-core.so.1.2.2.1
b1baf000 b1c20000 r-xp /usr/lib/osp/libosp-shell.so.1.2.2.1
b1c32000 b1c38000 r-xp /usr/lib/osp/libosp-speech-tts.so.1.2.2.0
b1c40000 b1c63000 r-xp /usr/lib/osp/libosp-face.so.1.2.2.0
b1c6d000 b1ccb000 r-xp /usr/lib/osp/libosp-nfc.so.1.2.2.0
b1cd7000 b1d32000 r-xp /usr/lib/osp/libosp-bluetooth.so.1.2.2.0
b1d3e000 b1db1000 r-xp /usr/lib/osp/libosp-wifi.so.1.2.2.0
b1dbd000 b1e7e000 r-xp /usr/lib/osp/libosp-social.so.1.2.2.0
b1e88000 b1efd000 r-xp /usr/lib/osp/libosp-web.so.1.2.2.0
b1f0b000 b1f58000 r-xp /usr/lib/osp/libosp-messaging.so.1.2.2.0
b1f62000 b1f7f000 r-xp /usr/lib/osp/libosp-uix.so.1.2.2.0
b1f89000 b1fa8000 r-xp /usr/lib/osp/libosp-telephony.so.1.2.2.0
b1fb1000 b1fca000 r-xp /usr/lib/osp/libosp-locations.so.1.2.2.3
b1fd3000 b2030000 r-xp /usr/lib/osp/libosp-content.so.1.2.2.0
b2039000 b204b000 r-xp /usr/lib/osp/libosp-ime.so.1.2.2.0
b2054000 b206e000 r-xp /usr/lib/osp/libosp-json.so.1.2.2.0
b2078000 b208a000 r-xp /usr/lib/libmmfile_utils.so.0.0.0
b2092000 b2097000 r-xp /usr/lib/libmmffile.so.0.0.0
b209f000 b2103000 r-xp /usr/lib/libmmfcamcorder.so.0.0.0
b2110000 b21d5000 r-xp /usr/lib/osp/libosp-net.so.1.2.2.0
b21e3000 b2406000 r-xp /usr/lib/osp/libarengine.so
b2482000 b2487000 r-xp /usr/lib/libcapi-media-metadata-extractor.so
b248f000 b2494000 r-xp /usr/lib/libcapi-media-recorder.so.0.1.3
b249c000 b24a7000 r-xp /usr/lib/libcapi-media-camera.so.0.1.4
b24af000 b24b2000 r-xp /usr/lib/libcapi-media-sound-manager.so.0.1.1
b24ba000 b24c8000 r-xp /usr/lib/libcapi-media-player.so.0.1.1
b24d0000 b24f1000 r-xp /usr/lib/libopencore-amrnb.so.0.0.2
b24fa000 b24fe000 r-xp /usr/lib/libogg.so.0.7.1
b2506000 b2528000 r-xp /usr/lib/libvorbis.so.0.4.3
b2530000 b2534000 r-xp /usr/lib/libcapi-media-audio-io.so.0.2.0
b253c000 b255a000 r-xp /usr/lib/osp/libosp-image.so.1.2.2.0
b2563000 b2581000 r-xp /usr/lib/osp/libosp-vision.so.1.2.2.0
b258a000 b2681000 r-xp /usr/lib/osp/libosp-media.so.1.2.2.0
b2693000 b269d000 r-xp /usr/lib/evas/modules/engines/software_generic/linux-gnueabi-armv7l-1.7.99/module.so
b26a5000 b26b4000 r-xp /opt/usr/apps/vd84JCg9vN/bin/QRDemo.exe
b26bd000 b272f000 r-xp /usr/lib/libosp-env-config.so.1.2.2.1
b2737000 b2771000 r-xp /usr/lib/libpulsecommon-0.9.23.so
b277a000 b277e000 r-xp /usr/lib/libmmfsoundcommon.so.0.0.0
b2786000 b27b7000 r-xp /usr/lib/libpulse.so.0.12.4
b27bf000 b2822000 r-xp /usr/lib/libasound.so.2.0.0
b282c000 b282f000 r-xp /usr/lib/libpulse-simple.so.0.0.3
b2837000 b283b000 r-xp /usr/lib/libascenario-0.2.so.0.0.0
b2844000 b2861000 r-xp /usr/lib/libavsysaudio.so.0.0.1
b2869000 b2877000 r-xp /usr/lib/libmmfsound.so.0.1.0
b287f000 b291b000 r-xp /usr/lib/libgstreamer-0.10.so.0.30.0
b2927000 b2968000 r-xp /usr/lib/libgstbase-0.10.so.0.30.0
b2971000 b297a000 r-xp /usr/lib/libgstapp-0.10.so.0.25.0
b2982000 b298f000 r-xp /usr/lib/libgstinterfaces-0.10.so.0.25.0
b2998000 b299e000 r-xp /usr/lib/libUMP.so
b29a6000 b29a9000 r-xp /usr/lib/libmm_ta.so.0.0.0
b29b1000 b29c0000 r-xp /usr/lib/libICE.so.6.3.0
b29ca000 b29cf000 r-xp /usr/lib/libSM.so.6.0.1
b29d7000 b29d8000 r-xp /usr/lib/libmmfkeysound.so.0.0.0
b29e0000 b29e8000 r-xp /usr/lib/libmmfcommon.so.0.0.0
b29f0000 b29f8000 r-xp /usr/lib/libaudio-session-mgr.so.0.0.0
b2a03000 b2a06000 r-xp /usr/lib/libmmfsession.so.0.0.0
b2a0e000 b2a52000 r-xp /usr/lib/libmmfplayer.so.0.0.0
b2a5b000 b2a6e000 r-xp /usr/lib/libEGL_platform.so
b2a77000 b2b4e000 r-xp /usr/lib/libMali.so
b2b59000 b2b5f000 r-xp /usr/lib/libxcb-render.so.0.0.0
b2b67000 b2b68000 r-xp /usr/lib/libxcb-shm.so.0.0.0
b2b71000 b2baf000 r-xp /usr/lib/libGLESv2.so.2.0
b2bb7000 b2c02000 r-xp /usr/lib/libtiff.so.5.1.0
b2c0d000 b2c36000 r-xp /usr/lib/libturbojpeg.so
b2c4f000 b2c55000 r-xp /usr/lib/libmmutil_imgp.so.0.0.0
b2c5d000 b2c63000 r-xp /usr/lib/libgif.so.4.1.6
b2c6b000 b2c8d000 r-xp /usr/lib/libavutil.so.51.73.101
b2c9c000 b2cca000 r-xp /usr/lib/libswscale.so.2.1.101
b2cd3000 b2fca000 r-xp /usr/lib/libavcodec.so.54.59.100
b32f1000 b330a000 r-xp /usr/lib/libpng12.so.0.50.0
b3313000 b3319000 r-xp /usr/lib/libfeedback.so.0.1.4
b3321000 b332d000 r-xp /usr/lib/libtts.so
b3335000 b334c000 r-xp /usr/lib/libEGL.so.1.4
b3355000 b340c000 r-xp /usr/lib/libcairo.so.2.11200.12
b3416000 b3430000 r-xp /usr/lib/osp/libosp-image-core.so.1.2.2.0
b3439000 b3d37000 r-xp /usr/lib/osp/libosp-uifw.so.1.2.2.1
b3daa000 b3daf000 r-xp /usr/lib/libslp_devman_plugin.so
b3db8000 b3dbb000 r-xp /usr/lib/libsyspopup_caller.so.0.1.0
b3dc3000 b3dc7000 r-xp /usr/lib/libsysman.so.0.2.0
b3dcf000 b3de0000 r-xp /usr/lib/libsecurity-server-commons.so.1.0.0
b3de9000 b3deb000 r-xp /usr/lib/libsystemd-daemon.so.0.0.1
b3df3000 b3df5000 r-xp /usr/lib/libdeviced.so.0.1.0
b3dfd000 b3e13000 r-xp /usr/lib/libpkgmgr_parser.so.0.1.0
b3e1b000 b3e1d000 r-xp /usr/lib/libpkgmgr_installer_status_broadcast_server.so.0.1.0
b3e25000 b3e28000 r-xp /usr/lib/libpkgmgr_installer_client.so.0.1.0
b3e30000 b3e33000 r-xp /usr/lib/libdevice-node.so.0.1
b3e3b000 b3e3f000 r-xp /usr/lib/libheynoti.so.0.0.2
b3e47000 b3e8c000 r-xp /usr/lib/libsoup-2.4.so.1.5.0
b3e95000 b3eaa000 r-xp /usr/lib/libsecurity-server-client.so.1.0.1
b3eb3000 b3eb7000 r-xp /usr/lib/libcapi-system-info.so.0.2.0
b3ebf000 b3ec4000 r-xp /usr/lib/libcapi-system-system-settings.so.0.0.2
b3ecc000 b3ecd000 r-xp /usr/lib/libcapi-system-power.so.0.1.1
b3ed6000 b3ed9000 r-xp /usr/lib/libcapi-system-device.so.0.1.0
b3ee1000 b3ee4000 r-xp /usr/lib/libcapi-system-runtime-info.so.0.0.3
b3eed000 b3ef0000 r-xp /usr/lib/libcapi-network-serial.so.0.0.8
b3ef8000 b3ef9000 r-xp /usr/lib/libcapi-content-mime-type.so.0.0.2
b3f01000 b3f0f000 r-xp /usr/lib/libcapi-appfw-application.so.0.1.0
b3f18000 b3f3a000 r-xp /usr/lib/libSLP-tapi.so.0.0.0
b3f42000 b3f45000 r-xp /usr/lib/libuuid.so.1.3.0
b3f4e000 b3f6c000 r-xp /usr/lib/libpkgmgr-info.so.0.0.17
b3f74000 b3f8b000 r-xp /usr/lib/libpkgmgr-client.so.0.1.68
b3f94000 b3f95000 r-xp /usr/lib/libpmapi.so.1.2
b3f9d000 b3fa5000 r-xp /usr/lib/libminizip.so.1.0.0
b3fad000 b3fb8000 r-xp /usr/lib/libmessage-port.so.1.2.2.1
b3fc0000 b4098000 r-xp /usr/lib/libxml2.so.2.7.8
b40a5000 b40c3000 r-xp /usr/lib/libpcre.so.0.0.1
b40cb000 b40ce000 r-xp /usr/lib/libiniparser.so.0
b40d7000 b40db000 r-xp /usr/lib/libhaptic.so.0.1
b40e3000 b40ee000 r-xp /usr/lib/libcryptsvc.so.0.0.1
b40fb000 b4100000 r-xp /usr/lib/libdevman.so.0.1
b4109000 b410d000 r-xp /usr/lib/libchromium.so.1.0
b4115000 b411b000 r-xp /usr/lib/libappsvc.so.0.1.0
b4123000 b4124000 r-xp /usr/lib/osp/libappinfo.so.1.2.2.1
b4134000 b4136000 r-xp /opt/usr/apps/vd84JCg9vN/bin/QRDemo
b413e000 b4144000 r-xp /usr/lib/libalarm.so.0.0.0
b414d000 b415f000 r-xp /usr/lib/libprivacy-manager-client.so.0.0.5
b4167000 b4467000 r-xp /usr/lib/osp/libosp-appfw.so.1.2.2.1
b4486000 b4490000 r-xp /lib/libnss_files-2.13.so
b4499000 b44a2000 r-xp /lib/libnss_nis-2.13.so
b44ab000 b44bc000 r-xp /lib/libnsl-2.13.so
b44c7000 b44cd000 r-xp /lib/libnss_compat-2.13.so
b44d6000 b44df000 r-xp /usr/lib/libcapi-security-privilege-manager.so.0.0.3
b4807000 b4818000 r-xp /usr/lib/libcom-core.so.0.0.1
b4820000 b4822000 r-xp /usr/lib/libdri2.so.0.0.0
b482a000 b4832000 r-xp /usr/lib/libdrm.so.2.4.0
b483a000 b483e000 r-xp /usr/lib/libtbm.so.1.0.0
b4846000 b4849000 r-xp /usr/lib/libXv.so.1.0.0
b4851000 b491c000 r-xp /usr/lib/libscim-1.0.so.8.2.3
b4932000 b4942000 r-xp /usr/lib/libnotification.so.0.1.0
b494a000 b496e000 r-xp /usr/lib/ecore/immodules/libisf-imf-module.so
b4977000 b4987000 r-xp /lib/libresolv-2.13.so
b498b000 b498d000 r-xp /usr/lib/libgmodule-2.0.so.0.3200.3
b4995000 b4ae8000 r-xp /usr/lib/libcrypto.so.1.0.0
b4b06000 b4b52000 r-xp /usr/lib/libssl.so.1.0.0
b4b5e000 b4b8a000 r-xp /usr/lib/libidn.so.11.5.44
b4b93000 b4b9d000 r-xp /usr/lib/libcares.so.2.0.0
b4ba5000 b4bbc000 r-xp /lib/libexpat.so.1.5.2
b4bc6000 b4bea000 r-xp /usr/lib/libicule.so.48.1
b4bf3000 b4bfb000 r-xp /usr/lib/libsf_common.so
b4c03000 b4c9e000 r-xp /usr/lib/libstdc++.so.6.0.14
b4cb1000 b4d8e000 r-xp /usr/lib/libgio-2.0.so.0.3200.3
b4d99000 b4dbe000 r-xp /usr/lib/libexif.so.12.3.3
b4dd2000 b4ddc000 r-xp /usr/lib/libethumb.so.1.7.99
b4de4000 b4e28000 r-xp /usr/lib/libsndfile.so.1.0.25
b4e36000 b4e38000 r-xp /usr/lib/libctxdata.so.0.0.0
b4e40000 b4e4e000 r-xp /usr/lib/libremix.so.0.0.0
b4e56000 b4e57000 r-xp /usr/lib/libecore_imf_evas.so.1.7.99
b4e5f000 b4e78000 r-xp /usr/lib/liblua-5.1.so
b4e81000 b4e88000 r-xp /usr/lib/libembryo.so.1.7.99
b4e91000 b4e94000 r-xp /usr/lib/libecore_input_evas.so.1.7.99
b4e9c000 b4ed9000 r-xp /usr/lib/libcurl.so.4.3.0
b4ee3000 b4ee7000 r-xp /usr/lib/libecore_ipc.so.1.7.99
b4ef0000 b4f5a000 r-xp /usr/lib/libpixman-1.so.0.28.2
b4f67000 b4f8b000 r-xp /usr/lib/libfontconfig.so.1.5.0
b4f94000 b4ff0000 r-xp /usr/lib/libharfbuzz.so.0.907.0
b5002000 b5016000 r-xp /usr/lib/libfribidi.so.0.3.1
b501e000 b5073000 r-xp /usr/lib/libfreetype.so.6.8.1
b507e000 b50a2000 r-xp /usr/lib/libjpeg.so.8.0.2
b50ba000 b50d1000 r-xp /lib/libz.so.1.2.5
b50d9000 b50e6000 r-xp /usr/lib/libsensor.so.1.1.0
b50f1000 b50f3000 r-xp /usr/lib/libapp-checker.so.0.1.0
b50fb000 b5101000 r-xp /usr/lib/libxdgmime.so.1.1.0
b6218000 b6300000 r-xp /usr/lib/libicuuc.so.48.1
b630d000 b642d000 r-xp /usr/lib/libicui18n.so.48.1
b643b000 b643e000 r-xp /usr/lib/libSLP-db-util.so.0.1.0
b6446000 b644f000 r-xp /usr/lib/libvconf.so.0.2.45
b6457000 b6465000 r-xp /usr/lib/libail.so.0.1.0
b646d000 b6485000 r-xp /usr/lib/libdbus-glib-1.so.2.2.2
b6486000 b648b000 r-xp /usr/lib/libffi.so.5.0.10
b6493000 b6494000 r-xp /usr/lib/libgthread-2.0.so.0.3200.3
b649c000 b64a6000 r-xp /usr/lib/libXext.so.6.4.0
b64af000 b64b2000 r-xp /usr/lib/libXtst.so.6.1.0
b64ba000 b64c0000 r-xp /usr/lib/libXrender.so.1.3.0
b64c8000 b64ce000 r-xp /usr/lib/libXrandr.so.2.2.0
b64d6000 b64d7000 r-xp /usr/lib/libXinerama.so.1.0.0
b64e0000 b64e9000 r-xp /usr/lib/libXi.so.6.1.0
b64f1000 b64f4000 r-xp /usr/lib/libXfixes.so.3.1.0
b64fc000 b64fe000 r-xp /usr/lib/libXgesture.so.7.0.0
b6506000 b6508000 r-xp /usr/lib/libXcomposite.so.1.0.0
b6510000 b6511000 r-xp /usr/lib/libXdamage.so.1.1.0
b651a000 b6521000 r-xp /usr/lib/libXcursor.so.1.0.2
b6529000 b6531000 r-xp /usr/lib/libemotion.so.1.7.99
b6539000 b6554000 r-xp /usr/lib/libecore_con.so.1.7.99
b655d000 b6562000 r-xp /usr/lib/libecore_imf.so.1.7.99
b656b000 b6573000 r-xp /usr/lib/libethumb_client.so.1.7.99
b657b000 b657d000 r-xp /usr/lib/libefreet_trash.so.1.7.99
b6585000 b6589000 r-xp /usr/lib/libefreet_mime.so.1.7.99
b6592000 b65a8000 r-xp /usr/lib/libefreet.so.1.7.99
b65b2000 b65bb000 r-xp /usr/lib/libedbus.so.1.7.99
b65c3000 b65c8000 r-xp /usr/lib/libecore_fb.so.1.7.99
b65d1000 b662d000 r-xp /usr/lib/libedje.so.1.7.99
b6637000 b664e000 r-xp /usr/lib/libecore_input.so.1.7.99
b6669000 b666e000 r-xp /usr/lib/libecore_file.so.1.7.99
b6676000 b6693000 r-xp /usr/lib/libecore_evas.so.1.7.99
b669c000 b66db000 r-xp /usr/lib/libeina.so.1.7.99
b66e4000 b6793000 r-xp /usr/lib/libevas.so.1.7.99
b67b5000 b67c8000 r-xp /usr/lib/libeet.so.1.7.99
b67d1000 b683b000 r-xp /lib/libm-2.13.so
b6847000 b684e000 r-xp /usr/lib/libutilX.so.1.1.0
b6856000 b685b000 r-xp /usr/lib/libappcore-common.so.1.1
b6863000 b686e000 r-xp /usr/lib/libaul.so.0.1.0
b6877000 b68ab000 r-xp /usr/lib/libgobject-2.0.so.0.3200.3
b68b4000 b68e4000 r-xp /usr/lib/libecore_x.so.1.7.99
b68ed000 b6902000 r-xp /usr/lib/libecore.so.1.7.99
b6919000 b6a39000 r-xp /usr/lib/libelementary.so.1.7.99
b6a4c000 b6a4f000 r-xp /lib/libattr.so.1.1.0
b6a57000 b6a59000 r-xp /usr/lib/libXau.so.6.0.0
b6a61000 b6a67000 r-xp /lib/librt-2.13.so
b6a70000 b6a78000 r-xp /lib/libcrypt-2.13.so
b6aa8000 b6aab000 r-xp /lib/libcap.so.2.21
b6ab3000 b6ab5000 r-xp /usr/lib/libiri.so
b6abd000 b6ad2000 r-xp /usr/lib/libxcb.so.1.1.0
b6ada000 b6ae5000 r-xp /lib/libunwind.so.8.0.1
b6b13000 b6c30000 r-xp /lib/libc-2.13.so
b6c3e000 b6c47000 r-xp /lib/libgcc_s-4.5.3.so.1
b6c4f000 b6c52000 r-xp /usr/lib/libsmack.so.1.0.0
b6c5a000 b6c86000 r-xp /usr/lib/libdbus-1.so.3.7.2
b6c8f000 b6c93000 r-xp /usr/lib/libbundle.so.0.1.22
b6c9b000 b6c9d000 r-xp /lib/libdl-2.13.so
b6ca6000 b6d80000 r-xp /usr/lib/libglib-2.0.so.0.3200.3
b6d89000 b6df3000 r-xp /usr/lib/libsqlite3.so.0.8.6
b6dfd000 b6e0a000 r-xp /usr/lib/libprivilege-control.so.0.0.2
b6e13000 b6ef9000 r-xp /usr/lib/libX11.so.6.3.0
b6f04000 b6f18000 r-xp /lib/libpthread-2.13.so
b6f28000 b6f2c000 r-xp /usr/lib/libappcore-efl.so.1.1
b6f35000 b6f36000 r-xp /usr/lib/libdlog.so.0.0.0
b6f3e000 b6f42000 r-xp /usr/lib/libsys-assert.so
b6f4a000 b6f67000 r-xp /lib/ld-2.13.so
bebaa000 bebcb000 rwxp [stack]
End of Maps Information
Callstack Information (PID:24630)
Call Stack Count: 24
0: Tizen::Io::RemoteMessagePort::SendMessage(Tizen::Base::Collection::IMap const*) + 0x7 (0xb430d1cc) [/usr/lib/osp/libosp-appfw.so] + 0x1a61cc
1: QRMessagePort::SendMessage(Tizen::Base::Collection::IMap const*) + 0x8c (0xb26ac218) [/opt/apps/vd84JCg9vN/bin/QRDemo.exe] + 0x7218
2: Tracker::OnCameraPreviewed(Tizen::Base::ByteBuffer&, unsigned long) + 0x710 (0xb26b1178) [/opt/apps/vd84JCg9vN/bin/QRDemo.exe] + 0xc178
End of Call Stack
Package Information
Package Name: vd84JCg9vN.QRDemo
Package ID : vd84JCg9vN
Version: 1.0.0
Package Type: tpk
App Name: QRDemo
App ID: vd84JCg9vN.QRDemo
Type: Application
Categories: (NULL)
| |
// <copyright file="Callbacks.cs" company="Google Inc.">
// Copyright (C) 2014 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>
#if UNITY_ANDROID
namespace GooglePlayGames.Native.PInvoke
{
using System;
using System.Collections;
using System.Runtime.InteropServices;
using GooglePlayGames.Native.Cwrapper;
using GooglePlayGames.OurUtils;
static class Callbacks
{
internal static readonly Action<CommonErrorStatus.UIStatus> NoopUICallback = status =>
{
Logger.d("Received UI callback: " + status);
};
internal delegate void ShowUICallbackInternal(CommonErrorStatus.UIStatus status,IntPtr data);
internal static IntPtr ToIntPtr<T>(Action<T> callback, Func<IntPtr, T> conversionFunction)
where T : BaseReferenceHolder
{
Action<IntPtr> pointerReceiver = result =>
{
using (T converted = conversionFunction(result))
{
if (callback != null)
{
callback(converted);
}
}
};
return ToIntPtr(pointerReceiver);
}
internal static IntPtr ToIntPtr<T, P>(Action<T, P> callback, Func<IntPtr, P> conversionFunction)
where P : BaseReferenceHolder
{
Action<T, IntPtr> pointerReceiver = (param1, param2) =>
{
using (P converted = conversionFunction(param2))
{
if (callback != null)
{
callback(param1, converted);
}
}
};
return ToIntPtr(pointerReceiver);
}
internal static IntPtr ToIntPtr(Delegate callback)
{
if (callback == null)
{
return IntPtr.Zero;
}
// Once the callback is passed off to native, we don't retain a reference to it - which
// means it's eligible for garbage collecting or being moved around by the runtime. If
// the garbage collector runs before the native code invokes the callback, chaos will
// ensue.
//
// To handle this, we create a normal GCHandle. The GCHandle will be freed when the callback returns the and
// handle is converted back to callback via IntPtrToCallback.
var handle = GCHandle.Alloc(callback);
return GCHandle.ToIntPtr(handle);
}
internal static T IntPtrToTempCallback<T>(IntPtr handle) where T : class
{
return IntPtrToCallback<T>(handle, true);
}
private static T IntPtrToCallback<T>(IntPtr handle, bool unpinHandle) where T : class
{
if (PInvokeUtilities.IsNull(handle))
{
return null;
}
var gcHandle = GCHandle.FromIntPtr(handle);
try
{
return (T)gcHandle.Target;
}
catch (System.InvalidCastException e)
{
Logger.e("GC Handle pointed to unexpected type: " + gcHandle.Target.ToString() +
". Expected " + typeof(T));
throw e;
}
finally
{
if (unpinHandle)
{
gcHandle.Free();
}
}
}
// TODO(hsakai): Better way of handling this.
internal static T IntPtrToPermanentCallback<T>(IntPtr handle) where T : class
{
return IntPtrToCallback<T>(handle, false);
}
[AOT.MonoPInvokeCallback(typeof(ShowUICallbackInternal))]
internal static void InternalShowUICallback(CommonErrorStatus.UIStatus status, IntPtr data)
{
Logger.d("Showing UI Internal callback: " + status);
var callback = IntPtrToTempCallback<Action<CommonErrorStatus.UIStatus>>(data);
try
{
callback(status);
}
catch (Exception e)
{
Logger.e("Error encountered executing InternalShowAllUICallback. " +
"Smothering to avoid passing exception into Native: " + e);
}
}
internal enum Type
{
Permanent,
Temporary}
;
internal static void PerformInternalCallback(string callbackName, Type callbackType,
IntPtr response, IntPtr userData)
{
Logger.d("Entering internal callback for " + callbackName);
Action<IntPtr> callback = callbackType == Type.Permanent
? IntPtrToPermanentCallback<Action<IntPtr>>(userData)
: IntPtrToTempCallback<Action<IntPtr>>(userData);
if (callback == null)
{
return;
}
try
{
callback(response);
}
catch (Exception e)
{
Logger.e("Error encountered executing " + callbackName + ". " +
"Smothering to avoid passing exception into Native: " + e);
}
}
internal static void PerformInternalCallback<T>(string callbackName, Type callbackType,
T param1, IntPtr param2, IntPtr userData)
{
Logger.d("Entering internal callback for " + callbackName);
Action<T, IntPtr> callback = null;
try
{
callback = callbackType == Type.Permanent
? IntPtrToPermanentCallback<Action<T, IntPtr>>(userData)
: IntPtrToTempCallback<Action<T, IntPtr>>(userData);
}
catch (Exception e)
{
Logger.e("Error encountered converting " + callbackName + ". " +
"Smothering to avoid passing exception into Native: " + e);
return;
}
Logger.d("Internal Callback converted to action");
if (callback == null)
{
return;
}
try
{
callback(param1, param2);
}
catch (Exception e)
{
Logger.e("Error encountered executing " + callbackName + ". " +
"Smothering to avoid passing exception into Native: " + e);
}
}
internal static Action<T> AsOnGameThreadCallback<T>(Action<T> toInvokeOnGameThread)
{
return result =>
{
if (toInvokeOnGameThread == null)
{
return;
}
PlayGamesHelperObject.RunOnGameThread(() => toInvokeOnGameThread(result));
};
}
internal static Action<T1, T2> AsOnGameThreadCallback<T1, T2>(
Action<T1, T2> toInvokeOnGameThread)
{
return (result1, result2) =>
{
if (toInvokeOnGameThread == null)
{
return;
}
PlayGamesHelperObject.RunOnGameThread(() => toInvokeOnGameThread(result1, result2));
};
}
internal static void AsCoroutine(IEnumerator routine)
{
PlayGamesHelperObject.RunCoroutine(routine);
}
internal static byte[] IntPtrAndSizeToByteArray(IntPtr data, UIntPtr dataLength)
{
if (dataLength.ToUInt64() == 0)
{
return null;
}
byte[] convertedData = new byte[dataLength.ToUInt32()];
Marshal.Copy(data, convertedData, 0, (int)dataLength.ToUInt32());
return convertedData;
}
}
}
#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;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.IL;
namespace ILCompiler
{
public class CompilerTypeSystemContext : MetadataTypeSystemContext, IMetadataStringDecoderProvider
{
private MetadataFieldLayoutAlgorithm _metadataFieldLayoutAlgorithm = new CompilerMetadataFieldLayoutAlgorithm();
private MetadataRuntimeInterfacesAlgorithm _metadataRuntimeInterfacesAlgorithm = new MetadataRuntimeInterfacesAlgorithm();
private ArrayOfTRuntimeInterfacesAlgorithm _arrayOfTRuntimeInterfacesAlgorithm;
private MetadataVirtualMethodAlgorithm _virtualMethodAlgorithm = new MetadataVirtualMethodAlgorithm();
private MetadataVirtualMethodEnumerationAlgorithm _virtualMethodEnumAlgorithm = new MetadataVirtualMethodEnumerationAlgorithm();
private DelegateVirtualMethodEnumerationAlgorithm _delegateVirtualMethodEnumAlgorithm = new DelegateVirtualMethodEnumerationAlgorithm();
private MetadataStringDecoder _metadataStringDecoder;
private class ModuleData
{
public string SimpleName;
public string FilePath;
public EcmaModule Module;
public MemoryMappedViewAccessor MappedViewAccessor;
}
private class ModuleHashtable : LockFreeReaderHashtable<EcmaModule, ModuleData>
{
protected override int GetKeyHashCode(EcmaModule key)
{
return key.GetHashCode();
}
protected override int GetValueHashCode(ModuleData value)
{
return value.Module.GetHashCode();
}
protected override bool CompareKeyToValue(EcmaModule key, ModuleData value)
{
return Object.ReferenceEquals(key, value.Module);
}
protected override bool CompareValueToValue(ModuleData value1, ModuleData value2)
{
return Object.ReferenceEquals(value1.Module, value2.Module);
}
protected override ModuleData CreateValueFromKey(EcmaModule key)
{
Debug.Assert(false, "CreateValueFromKey not supported");
return null;
}
}
private ModuleHashtable _moduleHashtable = new ModuleHashtable();
private class SimpleNameHashtable : LockFreeReaderHashtable<string, ModuleData>
{
StringComparer _comparer = StringComparer.OrdinalIgnoreCase;
protected override int GetKeyHashCode(string key)
{
return _comparer.GetHashCode(key);
}
protected override int GetValueHashCode(ModuleData value)
{
return _comparer.GetHashCode(value.SimpleName);
}
protected override bool CompareKeyToValue(string key, ModuleData value)
{
return _comparer.Equals(key, value.SimpleName);
}
protected override bool CompareValueToValue(ModuleData value1, ModuleData value2)
{
return _comparer.Equals(value1.SimpleName, value2.SimpleName);
}
protected override ModuleData CreateValueFromKey(string key)
{
Debug.Assert(false, "CreateValueFromKey not supported");
return null;
}
}
private SimpleNameHashtable _simpleNameHashtable = new SimpleNameHashtable();
private class DelegateInfoHashtable : LockFreeReaderHashtable<TypeDesc, DelegateInfo>
{
protected override int GetKeyHashCode(TypeDesc key)
{
return key.GetHashCode();
}
protected override int GetValueHashCode(DelegateInfo value)
{
return value.Type.GetHashCode();
}
protected override bool CompareKeyToValue(TypeDesc key, DelegateInfo value)
{
return Object.ReferenceEquals(key, value.Type);
}
protected override bool CompareValueToValue(DelegateInfo value1, DelegateInfo value2)
{
return Object.ReferenceEquals(value1.Type, value2.Type);
}
protected override DelegateInfo CreateValueFromKey(TypeDesc key)
{
return new DelegateInfo(key);
}
}
private DelegateInfoHashtable _delegateInfoHashtable = new DelegateInfoHashtable();
public CompilerTypeSystemContext(TargetDetails details)
: base(details)
{
}
public IReadOnlyDictionary<string, string> InputFilePaths
{
get;
set;
}
public IReadOnlyDictionary<string, string> ReferenceFilePaths
{
get;
set;
}
public override ModuleDesc ResolveAssembly(System.Reflection.AssemblyName name, bool throwIfNotFound)
{
return GetModuleForSimpleName(name.Name, throwIfNotFound);
}
public EcmaModule GetModuleForSimpleName(string simpleName, bool throwIfNotFound = true)
{
ModuleData existing;
if (_simpleNameHashtable.TryGetValue(simpleName, out existing))
return existing.Module;
string filePath;
if (!InputFilePaths.TryGetValue(simpleName, out filePath))
{
if (!ReferenceFilePaths.TryGetValue(simpleName, out filePath))
{
if (throwIfNotFound)
throw new FileNotFoundException("Assembly not found: " + simpleName);
return null;
}
}
return AddModule(filePath, simpleName);
}
public EcmaModule GetModuleFromPath(string filePath)
{
// This method is not expected to be called frequently. Linear search is acceptable.
foreach (var entry in ModuleHashtable.Enumerator.Get(_moduleHashtable))
{
if (entry.FilePath == filePath)
return entry.Module;
}
return AddModule(filePath, null);
}
private unsafe static PEReader OpenPEFile(string filePath, out MemoryMappedViewAccessor mappedViewAccessor)
{
// System.Reflection.Metadata has heuristic that tries to save virtual address space. This heuristic does not work
// well for us since it can make IL access very slow (call to OS for each method IL query). We will map the file
// ourselves to get the desired performance characteristics reliably.
FileStream fileStream = null;
MemoryMappedFile mappedFile = null;
MemoryMappedViewAccessor accessor = null;
try
{
// Create stream because CreateFromFile(string, ...) uses FileShare.None which is too strict
fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, false);
mappedFile = MemoryMappedFile.CreateFromFile(
fileStream, null, fileStream.Length, MemoryMappedFileAccess.Read, HandleInheritability.None, true);
accessor = mappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read);
var safeBuffer = accessor.SafeMemoryMappedViewHandle;
var peReader = new PEReader((byte*)safeBuffer.DangerousGetHandle(), (int)safeBuffer.ByteLength);
// MemoryMappedFile does not need to be kept around. MemoryMappedViewAccessor is enough.
mappedViewAccessor = accessor;
accessor = null;
return peReader;
}
finally
{
if (accessor != null)
accessor.Dispose();
if (mappedFile != null)
mappedFile.Dispose();
if (fileStream != null)
fileStream.Dispose();
}
}
private EcmaModule AddModule(string filePath, string expectedSimpleName)
{
MemoryMappedViewAccessor mappedViewAccessor = null;
PdbSymbolReader pdbReader = null;
try
{
PEReader peReader = OpenPEFile(filePath, out mappedViewAccessor);
pdbReader = OpenAssociatedSymbolFile(filePath);
EcmaModule module = EcmaModule.Create(this, peReader, pdbReader);
MetadataReader metadataReader = module.MetadataReader;
string simpleName = metadataReader.GetString(metadataReader.GetAssemblyDefinition().Name);
if (expectedSimpleName != null && !simpleName.Equals(expectedSimpleName, StringComparison.OrdinalIgnoreCase))
throw new FileNotFoundException("Assembly name does not match filename " + filePath);
ModuleData moduleData = new ModuleData()
{
SimpleName = simpleName,
FilePath = filePath,
Module = module,
MappedViewAccessor = mappedViewAccessor
};
lock (this)
{
ModuleData actualModuleData = _simpleNameHashtable.AddOrGetExisting(moduleData);
if (actualModuleData != moduleData)
{
if (actualModuleData.FilePath != filePath)
throw new FileNotFoundException("Module with same simple name already exists " + filePath);
return actualModuleData.Module;
}
mappedViewAccessor = null; // Ownership has been transfered
pdbReader = null; // Ownership has been transferred
_moduleHashtable.AddOrGetExisting(moduleData);
}
return module;
}
finally
{
if (mappedViewAccessor != null)
mappedViewAccessor.Dispose();
if (pdbReader != null)
pdbReader.Dispose();
}
}
public DelegateInfo GetDelegateInfo(TypeDesc delegateType)
{
return _delegateInfoHashtable.GetOrCreateValue(delegateType);
}
public override FieldLayoutAlgorithm GetLayoutAlgorithmForType(DefType type)
{
return _metadataFieldLayoutAlgorithm;
}
protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForNonPointerArrayType(ArrayType type)
{
if (_arrayOfTRuntimeInterfacesAlgorithm == null)
{
_arrayOfTRuntimeInterfacesAlgorithm = new ArrayOfTRuntimeInterfacesAlgorithm(SystemModule.GetKnownType("System", "Array`1"));
}
return _arrayOfTRuntimeInterfacesAlgorithm;
}
protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForDefType(DefType type)
{
return _metadataRuntimeInterfacesAlgorithm;
}
public override VirtualMethodAlgorithm GetVirtualMethodAlgorithmForType(TypeDesc type)
{
Debug.Assert(!type.IsArray, "Wanted to call GetClosestMetadataType?");
return _virtualMethodAlgorithm;
}
public override VirtualMethodEnumerationAlgorithm GetVirtualMethodEnumerationAlgorithmForType(TypeDesc type)
{
Debug.Assert(!type.IsArray, "Wanted to call GetClosestMetadataType?");
if (type.IsDelegate)
return _delegateVirtualMethodEnumAlgorithm;
return _virtualMethodEnumAlgorithm;
}
public MetadataStringDecoder GetMetadataStringDecoder()
{
if (_metadataStringDecoder == null)
_metadataStringDecoder = new CachingMetadataStringDecoder(0x10000); // TODO: Tune the size
return _metadataStringDecoder;
}
//
// Symbols
//
private PdbSymbolReader OpenAssociatedSymbolFile(string peFilePath)
{
// Assume that the .pdb file is next to the binary
var pdbFilename = Path.ChangeExtension(peFilePath, ".pdb");
if (!File.Exists(pdbFilename))
return null;
// Try to open the symbol file as portable pdb first
PdbSymbolReader reader = PortablePdbSymbolReader.TryOpen(pdbFilename, GetMetadataStringDecoder());
if (reader == null)
{
// Fallback to the diasymreader for non-portable pdbs
reader = UnmanagedPdbSymbolReader.TryOpenSymbolReaderForMetadataFile(peFilePath);
}
return reader;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Shared;
namespace Microsoft.Build.Conversion
{
/// <summary>
/// Contains strings identifying hint paths that we should remove
/// </summary>
/// <owner>AJenner</owner>
static internal class LegacyFrameworkPaths
{
internal const string RTMFrameworkPath = "MICROSOFT.NET\\FRAMEWORK\\V1.0.3705";
internal const string EverettFrameworkPath = "MICROSOFT.NET\\FRAMEWORK\\V1.1.4322";
internal const string JSharpRTMFrameworkPath = "MICROSOFT VISUAL JSHARP .NET\\FRAMEWORK\\V1.0.4205";
}
/// <summary>
/// Contains the names of the known elements in the VS.NET project file.
/// </summary>
/// <owner>RGoel</owner>
static internal class VSProjectElements
{
internal const string visualStudioProject = "VisualStudioProject";
internal const string visualJSharp = "VISUALJSHARP";
internal const string cSharp = "CSHARP";
internal const string visualBasic = "VisualBasic";
internal const string ECSharp = "ECSHARP";
internal const string EVisualBasic = "EVisualBasic";
internal const string build = "Build";
internal const string settings = "Settings";
internal const string config = "Config";
internal const string platform = "Platform";
internal const string interopRegistration = "InteropRegistration";
internal const string references = "References";
internal const string reference = "Reference";
internal const string files = "Files";
internal const string imports = "Imports";
internal const string import = "Import";
internal const string include = "Include";
internal const string exclude = "Exclude";
internal const string file = "File";
internal const string folder = "Folder";
internal const string startupServices = "StartupServices";
internal const string service = "Service";
internal const string userProperties = "UserProperties";
internal const string otherProjectSettings= "OtherProjectSettings";
internal const string PocketPC = "Pocket PC";
internal const string WindowsCE = "Windows CE";
internal const string Smartphone = "Smartphone";
internal const string SystemDataCommon = "System.Data.Common";
internal const string SystemSR = "System.SR";
internal const string MSCorLib = "MSCorLib";
}
/// <summary>
/// Contains the names of the known elements in the VS.NET project file.
/// </summary>
/// <owner>RGoel</owner>
static internal class VSProjectAttributes
{
internal const string relPath = "RelPath";
internal const string name = "Name";
internal const string guid = "Guid";
internal const string project = "Project";
internal const string projectType = "ProjectType";
internal const string local = "Local";
internal const string assemblyName = "AssemblyName";
internal const string importNamespace = "Namespace";
internal const string id = "ID";
internal const string link = "Link";
internal const string buildAction = "BuildAction";
internal const string buildActionNone = "None";
internal const string buildActionResource = "EmbeddedResource";
internal const string webReferences = "WebReferences";
internal const string webReferenceUrl = "WebReferenceUrl";
internal const string projectGuid = "ProjectGuid";
internal const string preBuildEvent = "PreBuildEvent";
internal const string postBuildEvent = "PostBuildEvent";
internal const string productVersion = "ProductVersion";
internal const string schemaVersion = "SchemaVersion";
internal const string outputPath = "OutputPath";
internal const string officeDocumentPath = "OfficeDocumentPath";
internal const string officeDocumentType = "OfficeProjectType";
internal const string officeProject = "OfficeProject";
internal const string additionalOptions = "AdditionalOptions";
internal const string platform = "Platform";
internal const string selectedDevice = "SelectedDevice";
internal const string deploymentPlatform = "DeploymentPlatform";
internal const string incrementalBuild = "IncrementalBuild";
internal const string hintPath = "HintPath";
internal const string documentationFile = "DocumentationFile";
internal const string debugType = "DebugType";
internal const string debugTypeNone = "none";
internal const string debugTypeFull = "full";
internal const string errorReport = "ErrorReport";
internal const string errorReportPrompt = "prompt";
}
/// <summary>
/// Contains the names of some of the hard-coded strings we'll be inserting into the newly converted MSBuild project file.
/// </summary>
/// <owner>RGoel</owner>
static internal class XMakeProjectStrings
{
internal const string project = "Project";
internal const string defaultTargets = "Build";
internal const string msbuildVersion = "MSBuildVersion";
internal const string xmlns = "xmlns";
internal const string importPrefix = "$(MSBuildToolsPath)\\";
internal const string importSuffix = ".targets";
internal const string targetsFilenamePrefix = "Microsoft.";
internal const string csharpTargets = "CSharp";
internal const string visualBasicTargets = "VisualBasic";
internal const string visualJSharpTargets = "VisualJSharp";
internal const string triumphImport = "$(MSBuildExtensionsPath)\\Microsoft\\VisualStudio\\v9.0\\OfficeTools\\Microsoft.VisualStudio.OfficeTools.targets";
internal const string officeTargetsVS2005Import = @"$(MSBuildExtensionsPath)\Microsoft.VisualStudio.OfficeTools.targets";
internal const string officeTargetsVS2005Import2 = @"$(MSBuildExtensionsPath)\Microsoft.VisualStudio.OfficeTools2.targets";
internal const string officeTargetsVS2005Repair = @"OfficeTools\Microsoft.VisualStudio.Tools.Office.targets";
internal const string configurationPrefix = " '$(Configuration)' == '";
internal const string configurationSuffix = "' ";
internal const string configuration = "Configuration";
internal const string platformPrefix = " '$(Platform)' == '";
internal const string platformSuffix = "' ";
internal const string platform = "Platform";
internal const string configplatformPrefix = " '$(Configuration)|$(Platform)' == '";
internal const string configplatformSeparator = "|";
internal const string configplatformSuffix = "' ";
internal const string defaultConfiguration = "Debug";
internal const string defaultPlatform = "AnyCPU";
internal const string x86Platform = "x86";
internal const string debugSymbols = "DebugSymbols";
internal const string reference = "Reference";
internal const string comReference = "COMReference";
internal const string projectReference = "ProjectReference";
internal const string import = "Import";
internal const string service = "Service";
internal const string folder = "Folder";
internal const string link = "Link";
internal const string autogen = "AutoGen";
internal const string webReferences = "WebReferences";
internal const string webReferenceUrl = "WebReferenceUrl";
internal const string relPath = "RelPath";
internal const string visualStudio = "VisualStudio";
internal const string webRefEnableProperties = "WebReference_EnableProperties";
internal const string webRefEnableSqlTypes = "WebReference_EnableSQLTypes";
internal const string webRefEnableLegacyEventing = "WebReference_EnableLegacyEventingModel";
internal const string xmlNamespace = "http://schemas.microsoft.com/developer/msbuild/2003";
internal const string cSharpGuid = "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC";
internal const string visualBasicGuid = "F184B08F-C81C-45F6-A57F-5ABD9991F28F";
internal const string visualJSharpGuid = "E6FDF86B-F3D1-11D4-8576-0002A516ECE8";
internal const string triumphProjectTypeGuid = "BAA0C2D2-18E2-41B9-852F-F413020CAA33";
internal const string VSDCSProjectTypeGuid = "4D628B5B-2FBC-4AA6-8C16-197242AEB884";
internal const string VSDVBProjectTypeGuid = "68B1623D-7FB9-47D8-8664-7ECEA3297D4F";
internal const string wpfFlavorGuid = "60dc8134-eba5-43b8-bcc9-bb4bc16c2548";
internal const string projectTypeGuids = "ProjectTypeGuids";
internal const string platformID = "PlatformID";
internal const string platformFamilyName = "PlatformFamilyName";
internal const string deployTargetSuffix = "DeployDirSuffix";
internal const string disableCSHostProc = "<FlavorProperties GUID=\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\">\n<HostingProcess disable=\"1\" />\n</FlavorProperties>";
internal const string disableVBHostProc = "<FlavorProperties GUID=\"{F184B08F-C81C-45F6-A57F-5ABD9991F28F}\">\n<HostingProcess disable=\"1\" />\n</FlavorProperties>";
internal const string SDECSTargets = "Microsoft.CompactFramework.CSharp.targets";
internal const string SDEVBTargets = "Microsoft.CompactFramework.VisualBasic.targets";
internal const string TargetFrameworkVersion = "TargetFrameworkVersion";
internal const string TargetFrameworkSubset = "TargetFrameworkSubset";
internal const string TargetFrameworkProfile = "TargetFrameworkProfile";
internal const string ClientProfile = "Client";
internal const string vOne = "v1.0";
internal const string vTwo = "v2.0";
internal const string noWarn = "NoWarn";
internal const string disabledVBWarnings = "42016,42017,42018,42019,42032,42353,42354,42355";
internal const string xmlFileExtension = ".xml";
internal const string csdprojFileExtension = ".csdproj";
internal const string vbdprojFileExtension = ".vbdproj";
internal const string csprojFileExtension = ".csproj";
internal const string vbprojFileExtension = ".vbproj";
internal const string myType = "MyType";
internal const string web = "Web";
internal const string windowsFormsWithCustomSubMain = "WindowsFormsWithCustomSubMain";
internal const string windows = "Windows";
internal const string codeAnalysisRuleAssemblies = "CodeAnalysisRuleAssemblies";
internal const string console = "Console";
internal const string empty = "Empty";
internal const string exe = "Exe";
internal const string library = "Library";
internal const string winExe = "WinExe";
internal const string outputType = "OutputType";
internal const string fileUpgradeFlags = "FileUpgradeFlags";
internal const string content = "Content";
internal const string copytooutput = "CopyToOutputDirectory";
internal const string preservenewest = "PreserveNewest";
internal const string toolsVersion = MSBuildConstants.CurrentToolsVersion;
internal const string vbTargetsVS2008 = @"$(MSBuildToolsPath)\Microsoft.VisualBasic.targets";
internal const string vbTargetsVS2005 = @"$(MSBuildBinPath)\Microsoft.VisualBasic.targets";
internal const string vsToolsPath = @"VSToolsPath";
internal const string visualStudioVersion = @"VisualStudioVersion";
internal const string toRepairPatternForAssetCompat = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\";
internal const string toRepairPatternForAssetCompatBeforeV10 = @"$(MSBuildExtensionsPath)\Microsoft\VisualStudio\";
internal const string toRepairPatternForAssetCompatV10 = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\";
internal const string repairHardCodedPathPattern = @"^v\d{1,2}\.\d\\";
}
}
| |
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections;
using System.Collections.Generic;
public class GLexTexture : GLexComponent {
public enum Filter {
NEAREST,
LINEAR,
NEAREST_MIPMAP_NEAREST,
LINEAR_MIPMAP_NEAREST,
NEAREST_MIPMAP_LINEAR,
LINEAR_MIPMAP_LINEAR
}
private static List<GLexTexture> mTextures;
private static GLexTexture[] mTexturesAsArray;
private Texture2D mTexture;
private TextureImporter mImporter;
private byte[] _dataBytes;
private string _dataBinaryKeystring;
private GLexTexture(Texture2D texture) : base() {
mTexture = texture;
mImporter = (TextureImporter)AssetImporter.GetAtPath(OriginalURL);
// texture need to be readable for export
if (!mImporter.isReadable) {
Debug.LogWarning("GLexTexture.Construct: Setting texture " + Name + " as Readable, or export will fail!");
mImporter.isReadable = true;
AssetDatabase.ImportAsset(OriginalURL);
mImporter = (TextureImporter)AssetImporter.GetAtPath(OriginalURL);
}
if (IsARGB32orRGB24) {
_dataBytes = mTexture.EncodeToPNG();
}
else {
_dataBytes = new JPGEncoder(mTexture, GLexConfig.JPEGQuality).GetBytes();
}
_dataBinaryKeystring = NamesUtil.GenerateBinaryId(_dataBytes, GLex.Instance.UserName);
mTextures.Add(this);
}
public static void Reset() {
mTextures = new List<GLexTexture>();
}
new public static void PrepareForExport() {
mTexturesAsArray = mTextures.ToArray();
}
public Texture2D Texture {
get {
return mTexture;
}
}
public void SaveBinaryData() {
var outPath = Path.Combine(GLexConfig.GetPathFor("image"), BinaryId);
if (!File.Exists(outPath)) {
// Because the filename is a hash of its contents, we know we don't need to actually write out the file if it already exists
File.WriteAllBytes(outPath, _dataBytes);
}
}
private bool IsARGB32orRGB24 {
get {
return mImporter.textureFormat == TextureImporterFormat.ARGB32 || mImporter.textureFormat == TextureImporterFormat.RGB24;
}
}
protected override string IdExtension {
get {
return GLexConfig.GetExtensionFor("texture");
}
}
// antler interface starts here
public override string Name {
get {
return mTexture.name;
}
}
public string BinaryId {
get {
return _dataBinaryKeystring + BinaryIdExtension;
}
}
public string BinaryFileFormat {
get {
if (IsARGB32orRGB24) {
return "RGBA";
}
else {
return "RGB";
}
}
}
public string BinaryIdExtension {
get {
return IsARGB32orRGB24 ? ".png" : ".jpg";
}
}
public bool IsJPG {
get {
return !IsARGB32orRGB24;
}
}
public bool IsPNG {
get {
return IsARGB32orRGB24;
}
}
public string OriginalURL {
get {
return AssetDatabase.GetAssetPath(mTexture);
}
}
public string RealURL {
get {
return Application.dataPath.Substring(0, Application.dataPath.LastIndexOf('/') + 1) + OriginalURL;
}
}
public string Wrap {
get {
return GLexConfig.TransformWrapMode(mTexture.wrapMode);
}
}
public string MagFilter {
get {
if (mTexture.filterMode == FilterMode.Point) {
return GLexConfig.TransformTextureFilter(Filter.NEAREST);
}
return GLexConfig.TransformTextureFilter(Filter.LINEAR);
}
}
public string MinFilter {
get {
if (mTexture.mipmapCount == 1) {
if (mTexture.filterMode == FilterMode.Point) {
return GLexConfig.TransformTextureFilter(Filter.NEAREST);
}
return GLexConfig.TransformTextureFilter(Filter.LINEAR);
}
else {
if (mTexture.filterMode == FilterMode.Point) {
return GLexConfig.TransformTextureFilter(Filter.NEAREST_MIPMAP_NEAREST);
}
else if (mTexture.filterMode == FilterMode.Bilinear) {
return GLexConfig.TransformTextureFilter(Filter.LINEAR_MIPMAP_NEAREST);
}
return GLexConfig.TransformTextureFilter(Filter.LINEAR_MIPMAP_LINEAR);
}
}
}
public string AnisotropyLevel {
get {
// The exported format bizarrely does not support disabling anisotropic filtering, so we need to set it to at least 1...
return Mathf.Max(1, mImporter.anisoLevel).ToString();
}
}
public string Offset {
get {
return "0, 0";
}
}
public string Scaling {
get {
return "1, 1";
}
}
// static
public static GLexTexture[] TexturesAsArray {
get {
return mTexturesAsArray;
}
}
public static bool Exists(Texture2D texture) {
if (texture != null) {
foreach (GLexTexture glexTexture in mTextures) {
if (glexTexture.Texture == texture) {
return true;
}
}
return false;
}
else {
return true; // return true for null textures to avoid creation of empty GLexTexture
}
}
public static GLexTexture Get(Texture2D texture) {
if (texture == null) {
return null;
}
else {
foreach (GLexTexture glexTexture in mTextures) {
if (glexTexture.Texture == texture) {
return glexTexture;
}
}
return new GLexTexture(texture);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using mshtml;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.HtmlEditor;
using OpenLiveWriter.Mshtml;
using OpenLiveWriter.PostEditor.ContentSources;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing
{
public enum SmartContentState { Enabled, Disabled, Broken, Preserve }
/// <summary>
/// The editor selection for a structured content block.
/// </summary>
///
///
public class PreserveContentSelection : ContentSelection
{
protected PreserveContentSelection(IHtmlEditorComponentContext editorComponentContext, IHTMLElement element, SmartContentState contentState)
: base(editorComponentContext, element, contentState)
{
}
public static PreserveContentSelection SelectElement(IHtmlEditorComponentContext editorComponentContext, IHTMLElement e, SmartContentState contentState)
{
PreserveContentSelection selection = (PreserveContentSelection)SelectElementCore(editorComponentContext, e, new PreserveContentSelection(editorComponentContext, e, contentState));
return selection;
}
}
public class SmartContentSelection : ContentSelection
{
protected SmartContentSelection(IHtmlEditorComponentContext editorComponentContext, IHTMLElement element, SmartContentState contentState)
: base(editorComponentContext, element, contentState)
{
}
public static SmartContentSelection SelectIfSmartContentElement(IHtmlEditorComponentContext editorComponentContext, IHTMLElement e)
{
return SelectIfSmartContentElement(editorComponentContext, e, SmartContentState.Enabled);
}
public static SmartContentSelection SelectIfSmartContentElement(IHtmlEditorComponentContext editorComponentContext, IHTMLElement e, SmartContentState contentState)
{
if (e != null)
{
IHTMLElement smartContent = ContentSourceManager.GetContainingSmartContent(e);
if (smartContent == null)
return null;
return SelectElement(editorComponentContext, smartContent, contentState);
}
return null;
}
public static SmartContentSelection SelectElement(IHtmlEditorComponentContext editorComponentContext, IHTMLElement e, SmartContentState contentState)
{
SmartContentSelection selection = (SmartContentSelection)SelectElementCore(editorComponentContext, e, new SmartContentSelection(editorComponentContext, e, contentState));
return selection;
}
}
public class DisabledImageSelection : ContentSelection
{
protected DisabledImageSelection(IHtmlEditorComponentContext editorComponentContext, IHTMLElement element)
: base(editorComponentContext, element, SmartContentState.Disabled)
{
}
public static DisabledImageSelection SelectElement(IHtmlEditorComponentContext editorComponentContext, IHTMLElement e)
{
return (DisabledImageSelection)SelectElementCore(editorComponentContext, e, new DisabledImageSelection(editorComponentContext, e));
}
}
public class ContentSelection : IHtmlEditorSelection
{
private IHTMLElement _element;
private SmartContentState _contentState;
private MshtmlMarkupServices _markupServices;
private MarkupRange _markupRange;
private IHtmlEditorComponentContext _editorComponentContext;
protected ContentSelection(IHtmlEditorComponentContext editorComponentContext, IHTMLElement element, SmartContentState contentState)
{
_editorComponentContext = editorComponentContext;
_markupServices = editorComponentContext.MarkupServices;
_element = element;
_contentState = contentState;
_markupRange = _markupServices.CreateMarkupRange(_element, true);
_markupRange.Start.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right;
_markupRange.End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Left;
_markupRange.Start.Cling = false;
_markupRange.End.Cling = false;
}
public IHTMLSelectionObject HTMLSelectionObject
{
get { return ((IHTMLDocument2)_element.document).selection; }
}
public bool IsValid
{
get
{
return _markupRange.Start.Positioned && _markupRange.Start.Positioned;
}
}
public SmartContentState ContentState
{
get { return _contentState; }
set { _contentState = value; }
}
public bool HasContiguousSelection
{
get
{
return true;
}
}
public bool IsEditField
{
get
{
return SmartContentElementBehavior.IsChildEditFieldSelected(HTMLElement, SelectedMarkupRange);
}
}
public void ExecuteSelectionOperation(HtmlEditorSelectionOperation op)
{
//suspend selection change events while the real HTML selection is temporarily adjusted
//to include the smart content element while the selection operation executes.
_editorComponentContext.BeginSelectionChange();
try
{
IHTMLDocument2 document = (IHTMLDocument2)HTMLElement.document;
MarkupRange elementRange = CreateElementClingMarkupRange();
MarkupRange insertionRange = CreateSelectionBoundaryMarkupRange();
elementRange.ToTextRange().select();
op(this);
//reset the selection
if (elementRange.Start.Positioned && elementRange.End.Positioned)
{
document.selection.empty();
_editorComponentContext.Selection = this;
}
else
{
insertionRange.ToTextRange().select();
}
}
finally
{
_editorComponentContext.EndSelectionChange();
}
}
/// <summary>
/// Creates a markup range that will cling to the smart content element.
/// </summary>
/// <returns></returns>
private MarkupRange CreateElementClingMarkupRange()
{
MarkupRange markupRange = _markupServices.CreateMarkupRange(HTMLElement);
markupRange.Start.Cling = true;
markupRange.End.Cling = true;
markupRange.Start.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right;
markupRange.End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Left;
return markupRange;
}
/// <summary>
/// Creates a markup range that will cling to the smart content element's
/// virtual selection boundaries.
/// </summary>
/// <returns></returns>
private MarkupRange CreateSelectionBoundaryMarkupRange()
{
MarkupRange markupRange = _markupServices.CreateMarkupRange(HTMLElement);
markupRange.Start.Cling = false;
markupRange.End.Cling = false;
markupRange.Start.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right;
markupRange.End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right;
return markupRange;
}
public IHTMLElement HTMLElement
{
get
{
return _element;
}
}
public bool Resizable
{
get
{
return true;
}
}
public MarkupRange SelectedMarkupRange
{
get
{
return _markupRange;
}
}
public IHTMLImgElement SelectedImage
{
get
{
return null;
}
}
public IHTMLElement SelectedControl
{
get { return null; }
}
public IHTMLTable SelectedTable
{
get
{
return null;
}
}
protected static ContentSelection SelectElementCore(IHtmlEditorComponentContext editorComponentContext, IHTMLElement e, ContentSelection smartContentSelection)
{
Debug.Assert(e.sourceIndex > -1, "Cannot select an unpositioned element");
if (e.sourceIndex > -1) //avoid unhandled exception reported by bug 291968
{
//suspend selection change events while the selection object is replaced
editorComponentContext.BeginSelectionChange();
try
{
//clear the DOM selection so that whatever is currently selected gets unselected.
editorComponentContext.EmptySelection();
//select the newly smart content element
editorComponentContext.Selection = smartContentSelection;
return smartContentSelection;
}
finally
{
editorComponentContext.EndSelectionChange();
}
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using VersionOne.SDK.APIClient;
using VersionOne.ServerConnector.Entities;
using VersionOne.ServiceHost.ConfigurationTool.DL.Exceptions;
using VersionOne.ServiceHost.ConfigurationTool.Entities;
using VersionOne.ServiceHost.Core.Configuration;
using ListValue = VersionOne.ServiceHost.ConfigurationTool.BZ.ListValue;
using VersionOneSettings = VersionOne.ServiceHost.ConfigurationTool.Entities.VersionOneSettings;
namespace VersionOne.ServiceHost.ConfigurationTool.DL {
/// <summary>
/// VersionOne interaction handler.
/// </summary>
public class V1Connector {
public const string TestTypeToken = "Test";
public const string DefectTypeToken = "Defect";
public const string FeatureGroupTypeToken = "Theme";
public const string StoryTypeToken = "Story";
public const string PrimaryWorkitemTypeToken = "PrimaryWorkitem";
private const string TestStatusTypeToken = "TestStatus";
private const string StoryStatusTypeToken = "StoryStatus";
private const string WorkitemPriorityToken = "WorkitemPriority";
private const string ProjectTypeToken = "Scope";
private IServices services;
public bool IsConnected { get; private set; }
private static V1Connector instance;
public static V1Connector Instance {
get { return instance ?? (instance = new V1Connector()); }
}
private V1Connector() { }
/// <summary>
/// Validate V1 connection
/// </summary>
/// <param name="settings">settings for connection to VersionOne.</param>
/// <returns>true, if validation succeeds; false, otherwise.</returns>
public bool ValidateConnection(VersionOneSettings settings) {
Connect(settings);
return IsConnected;
}
/// <summary>
/// Create connection to V1 server.
/// </summary>
/// <param name="settings">Connection settings</param>
public void Connect(VersionOneSettings settings) {
var url = settings.ApplicationUrl;
var accessToken = settings.AccessToken;
try
{
var connector = SDK.APIClient.V1Connector
.WithInstanceUrl(url)
.WithUserAgentHeader("VersionOne.Integration.Bugzilla", Assembly.GetEntryAssembly().GetName().Version.ToString());
ICanSetProxyOrEndpointOrGetConnector connectorWithAuth;
switch (settings.AuthenticationType)
{
case AuthenticationTypes.AccessToken:
connectorWithAuth = connector.WithAccessToken(accessToken);
break;
default:
throw new Exception("Invalid authentication type");
}
if (settings.ProxySettings.Enabled)
{
connectorWithAuth.WithProxy(GetProxy(settings.ProxySettings));
}
services = new Services(connectorWithAuth.UseOAuthEndpoints().Build());
if (!services.LoggedIn.IsNull)
{
IsConnected = true;
ListPropertyValues = new Dictionary<string, IList<ListValue>>();
}
else
IsConnected = false;
}
catch (Exception)
{
IsConnected = false;
}
}
private ProxyProvider GetProxy(ProxyConnectionSettings proxySettings) {
if (proxySettings == null || !proxySettings.Enabled) {
return null;
}
var uri = new Uri(proxySettings.Uri);
return new ProxyProvider(uri, proxySettings.UserName, proxySettings.Password, proxySettings.Domain);
}
/// <summary>
/// Reset connection
/// </summary>
public void ResetConnection() {
IsConnected = false;
}
// TODO it is known that primary workitem statuses do not have to be unique in VersionOne. In this case, the following method fails.
private IDictionary<string, string> QueryPropertyValues(string propertyName) {
var res = new Dictionary<string, string>();
var assetType = services.Meta.GetAssetType(propertyName);
var valueDef = assetType.GetAttributeDefinition("Name");
IAttributeDefinition inactiveDef;
var query = new Query(assetType);
query.Selection.Add(valueDef);
if(assetType.TryGetAttributeDefinition("Inactive", out inactiveDef)) {
var filter = new FilterTerm(inactiveDef);
filter.Equal("False");
query.Filter = filter;
}
query.OrderBy.MajorSort(assetType.DefaultOrderBy, OrderBy.Order.Ascending);
foreach(var asset in services.Retrieve(query).Assets) {
var name = asset.GetAttribute(valueDef).Value.ToString();
res.Add(name, asset.Oid.ToString());
}
return res;
}
/// <summary>
/// Get available test statuses.
/// </summary>
public IDictionary<string, string> GetTestStatuses() {
return QueryPropertyValues(TestStatusTypeToken);
}
/// <summary>
/// Get primary backlog item statuses.
/// </summary>
public IDictionary<string, string> GetStoryStatuses() {
return QueryPropertyValues(StoryStatusTypeToken);
}
/// <summary>
/// Get available workitem priorities.
/// </summary>
public IDictionary<string, string> GetWorkitemPriorities() {
return QueryPropertyValues(WorkitemPriorityToken);
}
/// <summary>
/// Get collection of reference fields for asset type.
/// </summary>
/// <param name="assetTypeToken">AssetType token</param>
public List<string> GetReferenceFieldList(string assetTypeToken) {
var attributeDefinitionAssetType = services.Meta.GetAssetType("AttributeDefinition");
var nameAttributeDef = attributeDefinitionAssetType.GetAttributeDefinition("Name");
var assetNameAttributeDef = attributeDefinitionAssetType.GetAttributeDefinition("Asset.AssetTypesMeAndDown.Name");
var isCustomAttributeDef = attributeDefinitionAssetType.GetAttributeDefinition("IsCustom");
var attributeTypeAttributeDef = attributeDefinitionAssetType.GetAttributeDefinition("AttributeType");
var assetTypeTerm = new FilterTerm(assetNameAttributeDef);
assetTypeTerm.Equal(assetTypeToken);
var isCustomTerm = new FilterTerm(isCustomAttributeDef);
isCustomTerm.Equal("true");
var attributeTypeTerm = new FilterTerm(attributeTypeAttributeDef);
attributeTypeTerm.Equal("Text");
var result = GetFieldList(new AndFilterTerm(assetTypeTerm, isCustomTerm, attributeTypeTerm), new List<IAttributeDefinition> { nameAttributeDef });
var fieldList = new List<string>();
result.ForEach(x => fieldList.Add(x.GetAttribute(nameAttributeDef).Value.ToString()));
return fieldList;
}
/// <summary>
/// Gets collection of custom list fields for specified asset type.
/// </summary>
/// <param name="assetTypeName">Name of the asset type</param>
/// <param name="fieldType">Field type</param>
/// <returns>collection of custom list fields</returns>
public IList<string> GetCustomFields(string assetTypeName, FieldType fieldType) {
var attrType = services.Meta.GetAssetType("AttributeDefinition");
var assetType = services.Meta.GetAssetType(assetTypeName);
var isCustomAttributeDef = attrType.GetAttributeDefinition("IsCustom");
var nameAttrDef = attrType.GetAttributeDefinition("Name");
var termType = new FilterTerm(attrType.GetAttributeDefinition("Asset.AssetTypesMeAndDown.Name"));
termType.Equal(assetTypeName);
IAttributeDefinition inactiveDef;
FilterTerm termState = null;
if (assetType.TryGetAttributeDefinition("Inactive", out inactiveDef)) {
termState = new FilterTerm(inactiveDef);
termState.Equal("False");
}
var fieldTypeName = string.Empty;
var attributeTypeName = string.Empty;
switch(fieldType) {
case FieldType.List:
fieldTypeName = "OneToManyRelationDefinition";
attributeTypeName = "Relation";
break;
case FieldType.Numeric:
fieldTypeName = "SimpleAttributeDefinition";
attributeTypeName = "Numeric";
break;
case FieldType.Text:
fieldTypeName = "SimpleAttributeDefinition";
attributeTypeName = "Text";
break;
}
var assetTypeTerm = new FilterTerm(attrType.GetAttributeDefinition("AssetType"));
assetTypeTerm.Equal(fieldTypeName);
var attributeTypeTerm = new FilterTerm(attrType.GetAttributeDefinition("AttributeType"));
attributeTypeTerm.Equal(attributeTypeName);
var isCustomTerm = new FilterTerm(isCustomAttributeDef);
isCustomTerm.Equal("true");
var result = GetFieldList(new AndFilterTerm(termState, termType, assetTypeTerm, isCustomTerm, attributeTypeTerm),
new List<IAttributeDefinition> {nameAttrDef});
var fieldList = new List<string>();
result.ForEach(x => fieldList.Add(x.GetAttribute(nameAttrDef).Value.ToString()));
return fieldList;
}
private AssetList GetFieldList(IFilterTerm filter, IEnumerable<IAttributeDefinition> selection) {
var attributeDefinitionAssetType = services.Meta.GetAssetType("AttributeDefinition");
var query = new Query(attributeDefinitionAssetType);
foreach(var attribute in selection) {
query.Selection.Add(attribute);
}
query.Filter = filter;
return services.Retrieve(query).Assets;
}
/// <summary>
/// Get Source values from VersionOne server
/// </summary>
public List<string> GetSourceList() {
var assetType = services.Meta.GetAssetType("StorySource");
var nameDef = assetType.GetAttributeDefinition("Name");
IAttributeDefinition inactiveDef;
var query = new Query(assetType);
query.Selection.Add(nameDef);
if(assetType.TryGetAttributeDefinition("Inactive", out inactiveDef)) {
var filter = new FilterTerm(inactiveDef);
filter.Equal("False");
query.Filter = filter;
}
query.OrderBy.MajorSort(assetType.DefaultOrderBy, OrderBy.Order.Ascending);
return services.Retrieve(query).Assets.Select(asset => asset.GetAttribute(nameDef).Value.ToString()).ToList();
}
public List<ProjectWrapper> GetProjectList() {
var projectType = services.Meta.GetAssetType(ProjectTypeToken);
var scopeQuery = new Query(projectType, projectType.GetAttributeDefinition("Parent"));
var stateTerm = new FilterTerm(projectType.GetAttributeDefinition("AssetState"));
stateTerm.NotEqual(AssetState.Closed);
scopeQuery.Filter = stateTerm;
var nameDef = projectType.GetAttributeDefinition("Name");
scopeQuery.Selection.Add(nameDef);
scopeQuery.OrderBy.MajorSort(projectType.DefaultOrderBy, OrderBy.Order.Ascending);
var result = services.Retrieve(scopeQuery);
var roots = new List<ProjectWrapper>(result.Assets.Count);
foreach (Asset asset in result.Assets) {
roots.AddRange(GetProjectWrapperList(asset, nameDef, 0));
}
return roots;
}
private IEnumerable<ProjectWrapper> GetProjectWrapperList(Asset asset, IAttributeDefinition attrName, int depth) {
var list = new List<ProjectWrapper>{new ProjectWrapper(asset, asset.GetAttribute(attrName).Value.ToString(), depth)};
foreach (var child in asset.Children) {
list.AddRange(GetProjectWrapperList(child, attrName, depth + 1));
}
return list;
}
public virtual IEnumerable<string> GetPrimaryWorkitemTypes() {
return new[] { "Story", "Defect" };
}
public string GetTypeByFieldName(string fieldSystemName, string assetTypeName) {
IAssetType assetType;
try {
assetType = services.Meta.GetAssetType(assetTypeName);
} catch (MetaException ex) {
throw new AssetTypeException(string.Format("{0} is unknown asset type.", assetTypeName), ex);
}
IAttributeDefinition attrDef;
try {
attrDef = assetType.GetAttributeDefinition(fieldSystemName);
} catch(MetaException ex) {
throw new FieldNameException(string.Format("{0} is unknown field name for {1}", fieldSystemName, assetTypeName), ex);
}
return attrDef.RelatedAsset == null ? null : attrDef.RelatedAsset.Token;
}
public IDictionary<string, IList<ListValue>> ListPropertyValues { get; private set; }
/// <summary>
/// Gets values for specified asset type name.
/// </summary>
/// <param name="typeName">Asset type name.</param>
/// <returns>List of values for the asset type.</returns>
public IList<ListValue> GetValuesForType(string typeName) {
if (ListPropertyValues == null) {
ListPropertyValues = new Dictionary<string, IList<ListValue>>();
}
if (!ListPropertyValues.ContainsKey(typeName)) {
ListPropertyValues.Add(typeName, QueryPropertyOidValues(typeName));
}
return ListPropertyValues[typeName];
}
private IList<ListValue> QueryPropertyOidValues(string propertyName) {
var res = new List<ListValue>();
IAttributeDefinition nameDef;
var query = GetPropertyValuesQuery(propertyName, out nameDef);
foreach (var asset in services.Retrieve(query).Assets) {
var name = asset.GetAttribute(nameDef).Value.ToString();
res.Add(new ListValue(name, asset.Oid.Momentless.Token));
}
return res;
}
private Query GetPropertyValuesQuery(string propertyName, out IAttributeDefinition nameDef) {
IAssetType assetType;
try {
assetType = services.Meta.GetAssetType(propertyName);
} catch(MetaException ex) {
throw new AssetTypeException(string.Format("{0} is unknown asset type.", propertyName), ex);
}
nameDef = assetType.GetAttributeDefinition("Name");
IAttributeDefinition inactiveDef;
var query = new Query(assetType);
query.Selection.Add(nameDef);
if (assetType.TryGetAttributeDefinition("Inactive", out inactiveDef)) {
var filter = new FilterTerm(inactiveDef);
filter.Equal("False");
query.Filter = filter;
}
query.OrderBy.MajorSort(assetType.DefaultOrderBy, OrderBy.Order.Ascending);
return query;
}
}
}
| |
namespace More.Globalization
{
using FluentAssertions;
using System;
using Xunit;
using static System.DayOfWeek;
using static System.Globalization.CalendarWeekRule;
using static System.Globalization.CultureInfo;
using static System.String;
public partial class FourFourFiveCalendarTest
{
FourFourFiveCalendar Calendar { get; } = CreateCalendar();
[Fact]
public void get_week_of_year_should_not_allow_date_out_of_range()
{
// arrange
var date = new DateTime( 2007, 1, 1 );
// act
Action getWeekOfYear = () => Calendar.GetWeekOfYear( date );
// assert
getWeekOfYear.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( date ) );
}
[Fact]
public void get_week_of_year_should_return_correct_result()
{
// arrange
var date = new DateTime( 2007, 7, 4 );
// act
var weekOfYear = Calendar.GetWeekOfYear( date );
// assert
weekOfYear.Should().Be( 1 );
}
[Fact]
public void get_week_of_year_with_rule_should_not_allow_date_out_of_range()
{
// arrange
var date = new DateTime( 2007, 1, 1 );
// act
Action getWeekOfYear = () => Calendar.GetWeekOfYear( date, FirstDay, Calendar.MinSupportedDateTime.DayOfWeek );
// assert
getWeekOfYear.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( date ) );
}
[Fact]
public void get_week_of_year_with_rule_should_return_correct_result()
{
// arrange
var date = new DateTime( 2007, 7, 7 );
// act
var weekOfYear = Calendar.GetWeekOfYear( date, FirstDay, Calendar.MinSupportedDateTime.DayOfWeek );
// assert
weekOfYear.Should().Be( 2 );
}
[Fact]
public void epoch_month_should_return_expected_value()
{
// arrange
const int July = 7;
ICalendarEpoch epoch = Calendar;
// act
var month = epoch.Month;
// assert
month.Should().Be( July );
}
[Fact]
public void eras_should_always_return_single_era()
{
// arrange
// act
var eras = Calendar.Eras;
// assert
eras.Should().Equal( new[] { 1 } );
}
[Fact]
public void add_months_should_not_allow_date_out_of_range()
{
// arrange
var date = new DateTime( 2007, 1, 1 );
// act
Action addMonths = () => Calendar.AddMonths( date, 1 );
// assert
addMonths.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( date ) );
}
[Fact]
public void add_months_with_positive_value_should_return_correct_result()
{
// arrange
var expected = new DateTime( 2007, 12, 29 );
var date = new DateTime( 2007, 6, 30 );
// act
var result = Calendar.AddMonths( date, 6 );
// assert
result.Should().Be( expected );
}
[Fact]
public void add_months_with_negative_value_should_return_correct_result()
{
// assert
var expected = new DateTime( 2007, 6, 30 );
var date = new DateTime( 2007, 12, 29 );
// act
var result = Calendar.AddMonths( date, -6 );
// assert
result.Should().Be( expected );
}
[Fact]
public void add_years_should_not_allow_date_out_of_range()
{
// arrange
var date = new DateTime( 2007, 1, 1 );
// act
Action addYears = () => Calendar.AddYears( date, 1 );
// assert
addYears.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( date ) );
}
[Fact]
public void add_years_with_positive_value_should_return_correct_result()
{
// arrange
var expected = new DateTime( 2008, 6, 28 );
var date = new DateTime( 2007, 6, 30 );
// act
var result = Calendar.AddYears( date, 1 );
// assert
result.Should().Be( expected );
}
[Fact]
public void add_years_with_negative_value_should_return_correct_result()
{
// arrange
var expected = new DateTime( 2007, 6, 30 );
var date = new DateTime( 2008, 6, 28 );
// act
var result = Calendar.AddYears( date, -1 );
// assert
result.Should().Be( expected );
}
[Fact]
public void get_day_of_month_should_not_allow_date_out_of_range()
{
// arrange
var date = new DateTime( 2006, 1, 1 );
// act
Action getDayOfMonth = () => Calendar.GetDayOfMonth( date );
// assert
getDayOfMonth.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( date ) );
}
[Fact]
public void get_day_of_month_should_return_correct_result()
{
// NOTE: using 4-4-5, first day of month could be another month
// arrange
var firstDay = new DateTime( 2007, 6, 30 );
// act
var day = Calendar.GetDayOfMonth( firstDay );
// assert
day.Should().Be( 1 );
}
[Fact]
public void get_day_of_week_should_not_allow_date_out_of_range()
{
// arrange
var date = new DateTime( 2007, 1, 1 );
// act
Action getDayOfWeek = () => Calendar.GetDayOfWeek( date );
// assert
getDayOfWeek.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( date ) );
}
[Fact]
public void get_day_of_week_should_return_correct_result()
{
// arrange
var firstDay = new DateTime( 2007, 6, 30 );
// act
var dayOfWeek = Calendar.GetDayOfWeek( firstDay );
// assert
dayOfWeek.Should().Be( Saturday );
}
[Fact]
public void get_day_of_eyar_should_not_allow_date_out_of_range()
{
// arrange
var date = new DateTime( 2007, 1, 1 );
// act
Action getDayOfYear = () => Calendar.GetDayOfYear( date );
// assert
getDayOfYear.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( date ) );
}
[Fact]
public void get_day_of_year_should_return_correct_result()
{
// arrange
var date = new DateTime( 2007, 6, 30 );
// act
var day = Calendar.GetDayOfYear( date );
// assert
day.Should().Be( 1 );
}
[Fact]
public void get_days_in_month_should_not_allow_year_out_of_range()
{
// arrange
const int year = 2006;
// act
Action getDaysInMonth = () => Calendar.GetDaysInMonth( year, 6, 1 );
// assert
getDaysInMonth.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( year ) );
}
[Fact]
public void get_days_in_month_should_not_allow_month_out_of_range()
{
// arrange
const int month = 5;
// act
Action getDaysInMonth = () => Calendar.GetDaysInMonth( 2007, month, 1 );
// assert
getDaysInMonth.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( month ) );
}
[Fact]
public void get_days_in_month_should_return_correct_result()
{
// arrange
var expected = 28;
// act
var days = Calendar.GetDaysInMonth( 2008, 1, 1 );
// assert
days.Should().Be( expected );
}
[Fact]
public void get_days_in_year_should_not_allow_year_out_of_range()
{
// arrange
const int year = 2006;
// act
Action getDaysInYear = () => Calendar.GetDaysInYear( year, 1 );
// assert
getDaysInYear.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( year ) );
}
[Fact]
public void get_days_in_year_should_return_correct_result()
{
// arrange
var expected = 364;
// act
var days = Calendar.GetDaysInYear( 2008, 1 );
// assert
days.Should().Be( expected );
}
[Fact]
public void get_era_should_not_allow_date_out_of_range()
{
// arrange
var date = new DateTime( 2007, 1, 1 );
// act
Action getEra = () => Calendar.GetEra( date );
// assert
getEra.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( date ) );
}
[Fact]
public void get_era_should_return_correct_result()
{
// arrange
var firstDay = new DateTime( 2007, 6, 30 );
// act
var era = Calendar.GetEra( firstDay );
// assert
era.Should().Be( 1 );
}
[Fact]
public void get_month_should_not_allow_date_out_of_range()
{
// arrange
var date = new DateTime( 2007, 1, 1 );
// act
Action getMonth = () => Calendar.GetMonth( date );
// assert
getMonth.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( date ) );
}
[Fact]
public void get_month_should_return_correct_result()
{
// arrange
var firstDay = new DateTime( 2007, 6, 30 );
// act
var month = Calendar.GetMonth( firstDay );
// assert
month.Should().Be( 1 );
}
[Fact]
public void get_months_in_year_should_not_allow_year_out_of_range()
{
// arrange
const int year = 2006;
// act
Action getMonthsInYear = () => Calendar.GetMonthsInYear( year, 1 );
// assert
getMonthsInYear.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( year ) );
}
[Fact]
public void get_months_in_year_should_return_correct_result()
{
// arrange
// act
var months = Calendar.GetMonthsInYear( 2008, 1 );
// assert
months.Should().Be( 12 );
}
[Fact]
public void get_year_should_not_allow_date_out_of_range()
{
// arrange
var date = new DateTime( 2007, 1, 1 );
// act
Action getYear = () => Calendar.GetYear( date );
// assert
getYear.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( date ) );
}
[Fact]
public void get_year_should_return_correct_result()
{
// NOTE: when fiscal years span calendar years, the calendar year from the last day in the fiscal calendar is reported
// arrange
var firstDay = new DateTime( 2007, 6, 30 );
// act
var year = Calendar.GetYear( firstDay );
// asset
year.Should().Be( 2008 );
}
[Fact]
public void is_leap_day_should_not_allow_date_out_of_range()
{
// arrange
const int year = 2006;
// act
Action isLeapDay = () => Calendar.IsLeapDay( year, 1, 1, 1 );
// assert
isLeapDay.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( year ) );
}
[Fact]
public void is_leap_day_should_not_allow_month_out_of_range()
{
// arrange
const int month = 5;
// act
Action isLeapDay = () => Calendar.IsLeapDay( 2007, month, 1, 1 );
// assert
isLeapDay.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( month ) );
}
[Fact]
public void is_leap_month_should_not_allow_year_out_of_range()
{
// arrange
const int year = 2006;
// act
Action isLeapMonth = () => Calendar.IsLeapMonth( year, 1, 1 );
// assert
isLeapMonth.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( year ) );
}
[Fact]
public void is_leap_month_should_not_allow_month_out_of_range()
{
// arrange
const int month = 5;
// act
Action isLeapMonth = () => Calendar.IsLeapMonth( 2007, month, 1 );
// assert
isLeapMonth.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( month ) );
}
[Fact]
public void is_leap_year_should_not_allow_year_out_of_range()
{
// arrange
const int year = 2006;
// act
Action isLeapYear = () => Calendar.IsLeapYear( year, 1 );
// assert
isLeapYear.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( year ) );
}
[Fact]
public void to_date_time_should_not_allow_year_out_of_range()
{
// arrange
const int year = 2006;
// act
Action toDateTime = () => Calendar.ToDateTime( year, 1, 1, 0, 0, 0, 0 );
// assert
toDateTime.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( year ) );
}
[Fact]
public void to_date_time_should_not_allow_month_out_of_range()
{
// arrange
const int month = 5;
// act
Action toDateTime = () => Calendar.ToDateTime( 2007, month, 1, 0, 0, 0, 0 );
// assert
toDateTime.ShouldThrow<ArgumentOutOfRangeException>().And.ParamName.Should().Be( nameof( month ) );
}
[Fact]
public void to_date_time_should_return_correct_result()
{
// arrange
var expected = new DateTime( 2007, 6, 30 );
// act
var date = Calendar.ToDateTime( 2008, 1, 1, 0, 0, 0, 0 );
// assert
date.Should().Be( expected );
}
[Fact]
public void X34X2D4X2D5_calendar_to_string_should_return_expected_text()
{
// arrange
var expected = Format( CurrentCulture, "MinSupportedDateTime = {0:d}, MaxSupportedDateTime = {1:d}", Calendar.MinSupportedDateTime, Calendar.MaxSupportedDateTime );
// act
var text = Calendar.ToString();
// assert
text.Should().Be( expected );
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Kironer.Shop.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A07_RegionColl (editable child list).<br/>
/// This is a generated base class of <see cref="A07_RegionColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="A06_Country"/> editable child object.<br/>
/// The items of the collection are <see cref="A08_Region"/> objects.
/// </remarks>
[Serializable]
public partial class A07_RegionColl : BusinessListBase<A07_RegionColl, A08_Region>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="A08_Region"/> item from the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to be removed.</param>
public void Remove(int region_ID)
{
foreach (var a08_Region in this)
{
if (a08_Region.Region_ID == region_ID)
{
Remove(a08_Region);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="A08_Region"/> item is in the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the A08_Region is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int region_ID)
{
foreach (var a08_Region in this)
{
if (a08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="A08_Region"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the A08_Region is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int region_ID)
{
foreach (var a08_Region in DeletedList)
{
if (a08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="A08_Region"/> item of the <see cref="A07_RegionColl"/> collection, based on item key properties.
/// </summary>
/// <param name="region_ID">The Region_ID.</param>
/// <returns>A <see cref="A08_Region"/> object.</returns>
public A08_Region FindA08_RegionByParentProperties(int region_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Region_ID.Equals(region_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A07_RegionColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="A07_RegionColl"/> collection.</returns>
internal static A07_RegionColl NewA07_RegionColl()
{
return DataPortal.CreateChild<A07_RegionColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="A07_RegionColl"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="A07_RegionColl"/> object.</returns>
internal static A07_RegionColl GetA07_RegionColl(SafeDataReader dr)
{
A07_RegionColl obj = new A07_RegionColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A07_RegionColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public A07_RegionColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="A07_RegionColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(dr);
OnFetchPre(args);
while (dr.Read())
{
Add(A08_Region.GetA08_Region(dr));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="A08_Region"/> items on the A07_RegionObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="A05_CountryColl"/> collection.</param>
internal void LoadItems(A05_CountryColl collection)
{
foreach (var item in this)
{
var obj = collection.FindA06_CountryByParentProperties(item.parent_Country_ID);
var rlce = obj.A07_RegionObjects.RaiseListChangedEvents;
obj.A07_RegionObjects.RaiseListChangedEvents = false;
obj.A07_RegionObjects.Add(item);
obj.A07_RegionObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using RestSharp;
using RestSharp.Authenticators;
using Salience.FluentApi.Internal;
namespace Salience.FluentApi
{
/// <summary>
/// Represents a REST client able to issue requests over HTTP.
/// </summary>
public class FluentClient : IFluentClient
{
private readonly RestClient _restClient;
private readonly string _defaultBaseApiPath;
private readonly List<ITraceWriter> _traceWriters = new List<ITraceWriter>();
/// <inheritdoc/>
public JsonSerializer Serializer { get; set; }
/// <inheritdoc/>
public RestClient RestClient => _restClient;
public static JsonSerializer GetNewDefaultSerializer()
{
return new JsonSerializer
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Include,
DefaultValueHandling = DefaultValueHandling.Include,
DateParseHandling = DateParseHandling.None
};
}
public FluentClient(string host, string defaultBaseApiPath = "")
{
Guard.NotNullOrEmpty(host, "host");
Guard.NotNull(defaultBaseApiPath, "defaultBaseApiPath");
_defaultBaseApiPath = defaultBaseApiPath.Trim();
_defaultBaseApiPath = string.IsNullOrEmpty(_defaultBaseApiPath) ? "" : "/" + _defaultBaseApiPath.Trim('/');
var url = new Uri(host.Trim().TrimEnd('/'), UriKind.Absolute);
_restClient = new RestClient { BaseUrl = url };
this.Serializer = GetNewDefaultSerializer();
}
public IFluentClient SetAuthenticator(IAuthenticator authenticator)
{
_restClient.Authenticator = authenticator;
return this;
}
public IFluentClient AddTrace(ITraceWriter traceWriter)
{
Guard.NotNull(traceWriter, "traceWriter");
_traceWriters.Add(traceWriter);
return this;
}
public IFluentClient RemoveTrace(ITraceWriter traceWriter)
{
Guard.NotNull(traceWriter, "traceWriter");
_traceWriters.Remove(traceWriter);
return this;
}
public IRequestWithOperation To(string operation)
{
var data = this.CreateRequestData();
var request = this.CreateEmptyRequest(data);
return request.To(operation);
}
protected internal virtual RequestData CreateRequestData()
{
return new RequestData
{
BaseApiPath = _defaultBaseApiPath,
ExpectedStatusCodes = new HashSet<HttpStatusCode> { HttpStatusCode.OK },
AlternateResults = new Dictionary<HttpStatusCode, object>()
};
}
protected internal virtual IEmptyRequest CreateEmptyRequest(RequestData data)
{
return new FluentRequest(this, data);
}
protected internal virtual void Trace(TraceLevel level, string messageFormat, params object[] args)
{
try
{
foreach(var traceWriter in _traceWriters)
traceWriter.Trace(level, null, messageFormat, args);
}
catch(Exception) { }
}
protected internal virtual void TraceError(TraceLevel level, Exception exception, string messageFormat, params object[] args)
{
try
{
foreach(var traceWriter in _traceWriters)
traceWriter.Trace(level, exception, messageFormat, args);
}
catch(Exception) { }
}
protected internal virtual object HandleRequest(RequestData data)
{
this.CreateRestRequest(data);
this.ConfigureRequest(data);
this.TraceRequest(data);
this.ExecuteRequest(data);
this.ValidateResponse(data);
this.TraceResponse(data);
var result = this.GetResultFromResponse(data);
foreach(var followup in data.FollowUps)
{
var nextRequest = followup(result);
result = nextRequest.Execute();
}
return result;
}
protected internal virtual async Task<object> HandleRequestAsync(RequestData data, System.Threading.CancellationToken token)
{
token.ThrowIfCancellationRequested();
this.CreateRestRequest(data);
this.ConfigureRequest(data);
this.TraceRequest(data);
await this.ExecuteRequestAsync(data);
this.ValidateResponse(data);
this.TraceResponse(data);
var result = this.GetResultFromResponse(data);
foreach (var followup in data.FollowUps)
{
token.ThrowIfCancellationRequested();
var nextRequest = followup(result);
result = await nextRequest.ExecuteAsync();
}
return result;
}
protected internal virtual void CreateRestRequest(RequestData data)
{
data.Request = new RestRequest
{
RequestFormat = DataFormat.Json,
JsonSerializer = new JsonDotNetSerializerWrapper(this.Serializer)
};
data.Request.AddHeader("Accept", "application/json, text/json, text/x-json, text/javascript");
}
protected internal virtual void ConfigureRequest(RequestData data)
{
try
{
data.Request.Resource = data.BaseApiPath + data.ResourcePath;
data.Request.Method = data.Method;
data.RequestCustomizer?.Invoke(data.Request);
if (data.Method == Method.POST || data.Method == Method.PUT || data.Method == Method.PATCH)
if(!data.Request.Parameters.Any(p => p.Type == ParameterType.HttpHeader && p.Name == "Content-Type"))
data.Request.AddHeader("Content-Type", "application/json");
}
catch(Exception ex)
{
this.TraceError(TraceLevel.Error, ex, "Could not {0} (error while creating request): {1}", data.Operation, ex.Message);
throw new RestException("Error while creating request: " + ex.Message, ex);
}
}
protected internal virtual void TraceRequest(RequestData data)
{
var requestUri = _restClient.BuildUri(data.Request);
var requestBodyParameter = data.Request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
var requestBodyContent = requestBodyParameter == null ? "(no body)" : requestBodyParameter.Value;
this.Trace(TraceLevel.Debug, "Trying to {0} by sending {1} request to {2} : {3}", data.Operation, data.Request.Method, requestUri, requestBodyContent);
}
protected internal virtual void ExecuteRequest(RequestData data)
{
data.Response = _restClient.Execute(data.Request);
}
protected internal virtual async Task ExecuteRequestAsync(RequestData data)
{
data.Response = await _restClient.ExecuteAsync(data.Request);
}
protected internal virtual void ValidateResponse(RequestData data)
{
var response = data.Response;
// check transport error
if(response.ErrorException != null)
{
this.TraceError(TraceLevel.Error, response.ErrorException, "Could not {0} (transport level error): {1}", data.Operation, response.ErrorMessage);
throw new RestException("Transport level error: " + response.ErrorMessage, response.ErrorException);
}
// check status
if(data.ExpectedStatusCodes.Contains(response.StatusCode))
return;
if(200 <= (int)response.StatusCode && (int)response.StatusCode < 300)
return;
string responseContent = response.Content ?? "(no content)";
this.TraceError(TraceLevel.Error, response.ErrorException, "Could not {0} (wrong status returned - {1}): {2}", data.Operation, response.StatusCode, responseContent);
this.HandleUnexpectedResponse(data);
throw new RestException("Wrong status returned: " + response.StatusDescription, response.Content, response.StatusCode);
}
protected internal virtual void HandleUnexpectedResponse(RequestData data)
{
// by default, do nothing
}
protected internal virtual void TraceResponse(RequestData data)
{
this.Trace(TraceLevel.Debug, "Received response to {0}: {1}", data.Operation, data.Response.Content ?? "(no content)");
}
protected internal virtual object GetResultFromResponse(RequestData data)
{
if(data.UseRawResponseContent)
return (data.ResultGetter != null ? data.ResultGetter.DynamicInvoke(data.Response.Content) : data.Response.Content);
if (data.ResponseBodyType == null)
return null;
if(data.AlternateResults.ContainsKey(data.Response.StatusCode))
return data.AlternateResults[data.Response.StatusCode];
try
{
using(var reader = new StringReader(data.Response.Content))
{
var jsonReader = new JsonTextReader(reader);
var responseBody = this.Serializer.Deserialize(jsonReader, data.ResponseBodyType);
return (data.ResultGetter != null ? data.ResultGetter.DynamicInvoke(responseBody) : responseBody);
}
}
catch(Exception ex)
{
this.TraceError(TraceLevel.Error, ex, "Could not {0} (error while deserializing response): {1}", data.Operation, ex.Message);
throw new RestException("Error while deserializing response: " + ex.Message, ex);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
public struct VT
{
public uint[,] uint2darr;
public uint[, ,] uint3darr;
public uint[,] uint2darr_b;
public uint[, ,] uint3darr_b;
}
public class CL
{
public uint[,] uint2darr = { { 0, 1 }, { 0, 0 } };
public uint[, ,] uint3darr = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
public uint[,] uint2darr_b = { { 0, 49 }, { 0, 0 } };
public uint[, ,] uint3darr_b = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
}
public class uintMDArrTest
{
static uint[,] uint2darr = { { 0, 1 }, { 0, 0 } };
static uint[, ,] uint3darr = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
static uint[,] uint2darr_b = { { 0, 49 }, { 0, 0 } };
static uint[, ,] uint3darr_b = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
static uint[][,] ja1 = new uint[2][,];
static uint[][, ,] ja2 = new uint[2][, ,];
static uint[][,] ja1_b = new uint[2][,];
static uint[][, ,] ja2_b = new uint[2][, ,];
public static int Main()
{
bool pass = true;
VT vt1;
vt1.uint2darr = new uint[,] { { 0, 1 }, { 0, 0 } };
vt1.uint3darr = new uint[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
vt1.uint2darr_b = new uint[,] { { 0, 49 }, { 0, 0 } };
vt1.uint3darr_b = new uint[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
CL cl1 = new CL();
ja1[0] = new uint[,] { { 0, 1 }, { 0, 0 } };
ja2[1] = new uint[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
ja1_b[0] = new uint[,] { { 0, 49 }, { 0, 0 } };
ja2_b[1] = new uint[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
uint result = 1;
// 2D
if (result != uint2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != vt1.uint2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != cl1.uint2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != ja1[0][0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (result != uint3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != vt1.uint3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != cl1.uint3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != ja2[1][1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToBool
bool Bool_result = true;
// 2D
if (Bool_result != Convert.ToBoolean(uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(vt1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(cl1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Bool_result != Convert.ToBoolean(uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(vt1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(cl1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToByte
byte Byte_result = 1;
// 2D
if (Byte_result != Convert.ToByte(uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(vt1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(cl1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Byte_result != Convert.ToByte(uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(vt1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(cl1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToChar
char Char_result = '1';
// 2D
if (Char_result != Convert.ToChar(uint2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(vt1.uint2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("vt1.uint2darr_b[0, 1] is: {0}", vt1.uint2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(cl1.uint2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("cl1.uint2darr_b[0, 1] is: {0}", cl1.uint2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Char_result != Convert.ToChar(uint3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("uint3darr_b[1,0,1] is: {0}", uint3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(vt1.uint3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("vt1.uint3darr_b[1,0,1] is: {0}", vt1.uint3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(cl1.uint3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("cl1.uint3darr_b[1,0,1] is: {0}", cl1.uint3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToDecimal
decimal Decimal_result = 1;
// 2D
if (Decimal_result != Convert.ToDecimal(uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(vt1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(cl1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Decimal_result != Convert.ToDecimal(uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(vt1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(cl1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToDouble
double Double_result = 1;
// 2D
if (Double_result != Convert.ToDouble(uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(vt1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(cl1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Double_result != Convert.ToDouble(uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(vt1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(cl1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToSingle
float Single_result = 1;
// 2D
if (Single_result != Convert.ToSingle(uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(vt1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(cl1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Single_result != Convert.ToSingle(uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(vt1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(cl1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToInt32
int Int32_result = 1;
// 2D
if (Int32_result != Convert.ToInt32(uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(vt1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(cl1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int32_result != Convert.ToInt32(uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(vt1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(cl1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToInt64
long Int64_result = 1;
// 2D
if (Int64_result != Convert.ToInt64(uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(vt1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(cl1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int64_result != Convert.ToInt64(uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(vt1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(cl1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToInt16
short Int16_result = 1;
// 2D
if (Int16_result != Convert.ToInt16(uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(vt1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(cl1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int16_result != Convert.ToInt16(uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(vt1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(cl1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToUInt64
ulong UInt64_result = 1;
// 2D
if (UInt64_result != Convert.ToUInt64(uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(vt1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(cl1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt64_result != Convert.ToUInt64(uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(vt1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(cl1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//UInt32ToUInt16 tests
ushort UInt16_result = 1;
// 2D
if (UInt16_result != Convert.ToUInt16(uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("2darr[0, 1] is: {0}", uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(vt1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("vt1.uint2darr[0, 1] is: {0}", vt1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(cl1.uint2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("cl1.uint2darr[0, 1] is: {0}", cl1.uint2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt16_result != Convert.ToUInt16(uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("uint3darr[1,0,1] is: {0}", uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(vt1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("vt1.uint3darr[1,0,1] is: {0}", vt1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(cl1.uint3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("cl1.uint3darr[1,0,1] is: {0}", cl1.uint3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (!pass)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
};
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ContextOptimised.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.