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.
using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.WebSockets.Test
{
// This steam accepts writes from one side, buffers them internally, and returns the data via Reads
// when requested on the other side.
public class BufferStream : Stream
{
private bool _disposed;
private bool _aborted;
private bool _terminated;
private Exception _abortException;
private readonly ConcurrentQueue<byte[]> _bufferedData;
private ArraySegment<byte> _topBuffer;
private readonly SemaphoreSlim _readLock;
private readonly SemaphoreSlim _writeLock;
private TaskCompletionSource<object> _readWaitingForData;
internal BufferStream()
{
_readLock = new SemaphoreSlim(1, 1);
_writeLock = new SemaphoreSlim(1, 1);
_bufferedData = new ConcurrentQueue<byte[]>();
_readWaitingForData = new TaskCompletionSource<object>();
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
#region NotSupported
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
#endregion NotSupported
/// <summary>
/// Ends the stream, meaning all future reads will return '0'.
/// </summary>
public void End()
{
_terminated = true;
}
public override void Flush()
{
CheckDisposed();
// TODO: Wait for data to drain?
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetCanceled();
return tcs.Task;
}
Flush();
// TODO: Wait for data to drain?
return Task.FromResult(0);
}
public override int Read(byte[] buffer, int offset, int count)
{
if(_terminated)
{
return 0;
}
VerifyBuffer(buffer, offset, count, allowEmpty: false);
_readLock.Wait();
try
{
int totalRead = 0;
do
{
// Don't drain buffered data when signaling an abort.
CheckAborted();
if (_topBuffer.Count <= 0)
{
byte[] topBuffer = null;
while (!_bufferedData.TryDequeue(out topBuffer))
{
if (_disposed)
{
CheckAborted();
// Graceful close
return totalRead;
}
WaitForDataAsync().Wait();
}
_topBuffer = new ArraySegment<byte>(topBuffer);
}
int actualCount = Math.Min(count, _topBuffer.Count);
Buffer.BlockCopy(_topBuffer.Array, _topBuffer.Offset, buffer, offset, actualCount);
_topBuffer = new ArraySegment<byte>(_topBuffer.Array,
_topBuffer.Offset + actualCount,
_topBuffer.Count - actualCount);
totalRead += actualCount;
offset += actualCount;
count -= actualCount;
}
while (count > 0 && (_topBuffer.Count > 0 || !_bufferedData.IsEmpty));
// Keep reading while there is more data available and we have more space to put it in.
return totalRead;
}
finally
{
_readLock.Release();
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
// TODO: This option doesn't preserve the state object.
// return ReadAsync(buffer, offset, count);
return base.BeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
// return ((Task<int>)asyncResult).Result;
return base.EndRead(asyncResult);
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (_terminated)
{
return 0;
}
VerifyBuffer(buffer, offset, count, allowEmpty: false);
var registration = cancellationToken.Register(Abort);
await _readLock.WaitAsync(cancellationToken);
try
{
int totalRead = 0;
do
{
// Don't drained buffered data on abort.
CheckAborted();
if (_topBuffer.Count <= 0)
{
byte[] topBuffer = null;
while (!_bufferedData.TryDequeue(out topBuffer))
{
if (_disposed)
{
CheckAborted();
// Graceful close
return totalRead;
}
await WaitForDataAsync();
}
_topBuffer = new ArraySegment<byte>(topBuffer);
}
var actualCount = Math.Min(count, _topBuffer.Count);
Buffer.BlockCopy(_topBuffer.Array, _topBuffer.Offset, buffer, offset, actualCount);
_topBuffer = new ArraySegment<byte>(_topBuffer.Array,
_topBuffer.Offset + actualCount,
_topBuffer.Count - actualCount);
totalRead += actualCount;
offset += actualCount;
count -= actualCount;
}
while (count > 0 && (_topBuffer.Count > 0 || !_bufferedData.IsEmpty));
// Keep reading while there is more data available and we have more space to put it in.
return totalRead;
}
finally
{
registration.Dispose();
_readLock.Release();
}
}
// Write with count 0 will still trigger OnFirstWrite
public override void Write(byte[] buffer, int offset, int count)
{
VerifyBuffer(buffer, offset, count, allowEmpty: true);
CheckDisposed();
_writeLock.Wait();
try
{
if (count == 0)
{
return;
}
// Copies are necessary because we don't know what the caller is going to do with the buffer afterwards.
var internalBuffer = new byte[count];
Buffer.BlockCopy(buffer, offset, internalBuffer, 0, count);
_bufferedData.Enqueue(internalBuffer);
SignalDataAvailable();
}
finally
{
_writeLock.Release();
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
Write(buffer, offset, count);
var tcs = new TaskCompletionSource<object>(state);
tcs.TrySetResult(null);
var result = tcs.Task;
if (callback != null)
{
callback(result);
}
return result;
}
public override void EndWrite(IAsyncResult asyncResult) { }
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
VerifyBuffer(buffer, offset, count, allowEmpty: true);
if (cancellationToken.IsCancellationRequested)
{
var tcs = new TaskCompletionSource<object>();
tcs.TrySetCanceled();
return tcs.Task;
}
Write(buffer, offset, count);
return Task.FromResult<object>(null);
}
private static void VerifyBuffer(byte[] buffer, int offset, int count, bool allowEmpty)
{
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset), offset, string.Empty);
}
if (count < 0 || count > buffer.Length - offset
|| (!allowEmpty && count == 0))
{
throw new ArgumentOutOfRangeException(nameof(count), count, string.Empty);
}
}
private void SignalDataAvailable()
{
// Dispatch, as TrySetResult will synchronously execute the waiters callback and block our Write.
Task.Factory.StartNew(() => _readWaitingForData.TrySetResult(null));
}
private Task WaitForDataAsync()
{
_readWaitingForData = new TaskCompletionSource<object>();
if (!_bufferedData.IsEmpty || _disposed)
{
// Race, data could have arrived before we created the TCS.
_readWaitingForData.TrySetResult(null);
}
return _readWaitingForData.Task;
}
internal void Abort()
{
Abort(new OperationCanceledException());
}
internal void Abort(Exception innerException)
{
Contract.Requires(innerException != null);
_aborted = true;
_abortException = innerException;
Dispose();
}
private void CheckAborted()
{
if (_aborted)
{
throw new IOException(string.Empty, _abortException);
}
}
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_writeLock", Justification = "ODEs from the locks would mask IOEs from abort.")]
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_readLock", Justification = "Data can still be read unless we get aborted.")]
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Throw for further writes, but not reads. Allow reads to drain the buffered data and then return 0 for further reads.
_disposed = true;
_readWaitingForData.TrySetResult(null);
}
base.Dispose(disposing);
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
}
}
| |
// 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;
using System.Diagnostics;
using System.Text;
namespace System.Xml.Schema
{
/// <summary>
/// This enum specifies what format should be used when converting string to XsdDateTime
/// </summary>
[Flags]
internal enum XsdDateTimeFlags
{
DateTime = 0x01,
Time = 0x02,
Date = 0x04,
GYearMonth = 0x08,
GYear = 0x10,
GMonthDay = 0x20,
GDay = 0x40,
GMonth = 0x80,
AllXsd = 0xFF //All still does not include the XDR formats
}
/// <summary>
/// This structure extends System.DateTime to support timeInTicks zone and Gregorian types scomponents of an Xsd Duration. It is used internally to support Xsd durations without loss
/// of fidelity. XsdDuration structures are immutable once they've been created.
/// </summary>
internal struct XsdDateTime
{
// DateTime is being used as an internal representation only
// Casting XsdDateTime to DateTime might return a different value
private DateTime dt;
// Additional information that DateTime is not preserving
// Information is stored in the following format:
// Bits Info
// 31-24 DateTimeTypeCode
// 23-16 XsdDateTimeKind
// 15-8 Zone Hours
// 7-0 Zone Minutes
private uint extra;
// Subset of XML Schema types XsdDateTime represents
enum DateTimeTypeCode
{
DateTime,
Time,
Date,
GYearMonth,
GYear,
GMonthDay,
GDay,
GMonth,
}
// Internal representation of DateTimeKind
enum XsdDateTimeKind
{
Unspecified,
Zulu,
LocalWestOfZulu, // GMT-1..14, N..Y
LocalEastOfZulu // GMT+1..14, A..M
}
// Masks and shifts used for packing and unpacking extra
private const uint TypeMask = 0xFF000000;
private const uint KindMask = 0x00FF0000;
private const uint ZoneHourMask = 0x0000FF00;
private const uint ZoneMinuteMask = 0x000000FF;
private const int TypeShift = 24;
private const int KindShift = 16;
private const int ZoneHourShift = 8;
// Maximum number of fraction digits;
private const short maxFractionDigits = 7;
static readonly int Lzyyyy = "yyyy".Length;
static readonly int Lzyyyy_ = "yyyy-".Length;
static readonly int Lzyyyy_MM = "yyyy-MM".Length;
static readonly int Lzyyyy_MM_ = "yyyy-MM-".Length;
static readonly int Lzyyyy_MM_dd = "yyyy-MM-dd".Length;
static readonly int Lzyyyy_MM_ddT = "yyyy-MM-ddT".Length;
static readonly int LzHH = "HH".Length;
static readonly int LzHH_ = "HH:".Length;
static readonly int LzHH_mm = "HH:mm".Length;
static readonly int LzHH_mm_ = "HH:mm:".Length;
static readonly int LzHH_mm_ss = "HH:mm:ss".Length;
static readonly int Lz_ = "-".Length;
static readonly int Lz_zz = "-zz".Length;
static readonly int Lz_zz_ = "-zz:".Length;
static readonly int Lz_zz_zz = "-zz:zz".Length;
static readonly int Lz__ = "--".Length;
static readonly int Lz__mm = "--MM".Length;
static readonly int Lz__mm_ = "--MM-".Length;
static readonly int Lz__mm__ = "--MM--".Length;
static readonly int Lz__mm_dd = "--MM-dd".Length;
static readonly int Lz___ = "---".Length;
static readonly int Lz___dd = "---dd".Length;
/// <summary>
/// Constructs an XsdDateTime from a string using specific format.
/// </summary>
public XsdDateTime(string text, XsdDateTimeFlags kinds) : this()
{
Parser parser = new Parser();
if (!parser.Parse(text, kinds))
{
throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, text, kinds));
}
InitiateXsdDateTime(parser);
}
private void InitiateXsdDateTime(Parser parser)
{
dt = new DateTime(parser.year, parser.month, parser.day, parser.hour, parser.minute, parser.second);
if (parser.fraction != 0)
{
dt = dt.AddTicks(parser.fraction);
}
extra = (uint)(((int)parser.typeCode << TypeShift) | ((int)parser.kind << KindShift) | (parser.zoneHour << ZoneHourShift) | parser.zoneMinute);
}
/// <summary>
/// Constructs an XsdDateTime from a DateTime.
/// </summary>
public XsdDateTime(DateTime dateTime, XsdDateTimeFlags kinds)
{
Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set.");
dt = dateTime;
DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1);
int zoneHour = 0;
int zoneMinute = 0;
XsdDateTimeKind kind;
switch (dateTime.Kind)
{
case DateTimeKind.Unspecified: kind = XsdDateTimeKind.Unspecified; break;
case DateTimeKind.Utc: kind = XsdDateTimeKind.Zulu; break;
default:
{
Debug.Assert(dateTime.Kind == DateTimeKind.Local, "Unknown DateTimeKind: " + dateTime.Kind);
TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(dateTime);
if (utcOffset.Ticks < 0)
{
kind = XsdDateTimeKind.LocalWestOfZulu;
zoneHour = -utcOffset.Hours;
zoneMinute = -utcOffset.Minutes;
}
else
{
kind = XsdDateTimeKind.LocalEastOfZulu;
zoneHour = utcOffset.Hours;
zoneMinute = utcOffset.Minutes;
}
break;
}
}
extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneHour << ZoneHourShift) | zoneMinute);
}
// Constructs an XsdDateTime from a DateTimeOffset
public XsdDateTime(DateTimeOffset dateTimeOffset) : this(dateTimeOffset, XsdDateTimeFlags.DateTime)
{
}
public XsdDateTime(DateTimeOffset dateTimeOffset, XsdDateTimeFlags kinds)
{
Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set.");
dt = dateTimeOffset.DateTime;
TimeSpan zoneOffset = dateTimeOffset.Offset;
DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1);
XsdDateTimeKind kind;
if (zoneOffset.TotalMinutes < 0)
{
zoneOffset = zoneOffset.Negate();
kind = XsdDateTimeKind.LocalWestOfZulu;
}
else if (zoneOffset.TotalMinutes > 0)
{
kind = XsdDateTimeKind.LocalEastOfZulu;
}
else
{
kind = XsdDateTimeKind.Zulu;
}
extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneOffset.Hours << ZoneHourShift) | zoneOffset.Minutes);
}
/// <summary>
/// Returns auxiliary enumeration of XSD date type
/// </summary>
private DateTimeTypeCode InternalTypeCode
{
get { return (DateTimeTypeCode)((extra & TypeMask) >> TypeShift); }
}
/// <summary>
/// Returns geographical "position" of the value
/// </summary>
private XsdDateTimeKind InternalKind
{
get { return (XsdDateTimeKind)((extra & KindMask) >> KindShift); }
}
/// <summary>
/// Returns the year part of XsdDateTime
/// The returned value is integer between 1 and 9999
/// </summary>
public int Year
{
get { return dt.Year; }
}
/// <summary>
/// Returns the month part of XsdDateTime
/// The returned value is integer between 1 and 12
/// </summary>
public int Month
{
get { return dt.Month; }
}
/// <summary>
/// Returns the day of the month part of XsdDateTime
/// The returned value is integer between 1 and 31
/// </summary>
public int Day
{
get { return dt.Day; }
}
/// <summary>
/// Returns the hour part of XsdDateTime
/// The returned value is integer between 0 and 23
/// </summary>
public int Hour
{
get { return dt.Hour; }
}
/// <summary>
/// Returns the minute part of XsdDateTime
/// The returned value is integer between 0 and 60
/// </summary>
public int Minute
{
get { return dt.Minute; }
}
/// <summary>
/// Returns the second part of XsdDateTime
/// The returned value is integer between 0 and 60
/// </summary>
public int Second
{
get { return dt.Second; }
}
/// <summary>
/// Returns number of ticks in the fraction of the second
/// The returned value is integer between 0 and 9999999
/// </summary>
public int Fraction
{
get { return (int)(dt.Ticks - new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second).Ticks); }
}
/// <summary>
/// Returns the hour part of the time zone
/// The returned value is integer between -13 and 13
/// </summary>
public int ZoneHour
{
get
{
uint result = (extra & ZoneHourMask) >> ZoneHourShift;
return (int)result;
}
}
/// <summary>
/// Returns the minute part of the time zone
/// The returned value is integer between 0 and 60
/// </summary>
public int ZoneMinute
{
get
{
uint result = (extra & ZoneMinuteMask);
return (int)result;
}
}
/// <summary>
/// Cast to DateTime
/// The following table describes the behaviors of getting the default value
/// when a certain year/month/day values are missing.
///
/// An "X" means that the value exists. And "--" means that value is missing.
///
/// Year Month Day => ResultYear ResultMonth ResultDay Note
///
/// X X X Parsed year Parsed month Parsed day
/// X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month.
/// X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year.
/// X -- -- Parsed year First month First day If we have only the year, assume the first day of that year.
///
/// -- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year.
/// -- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day.
/// -- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month.
/// -- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date.
/// </summary>
public static implicit operator DateTime(XsdDateTime xdt)
{
DateTime result;
switch (xdt.InternalTypeCode)
{
case DateTimeTypeCode.GMonth:
case DateTimeTypeCode.GDay:
result = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day);
break;
case DateTimeTypeCode.Time:
//back to DateTime.Now
DateTime currentDateTime = DateTime.Now;
TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day);
result = xdt.dt.Add(addDiff);
break;
default:
result = xdt.dt;
break;
}
long ticks;
switch (xdt.InternalKind)
{
case XsdDateTimeKind.Zulu:
// set it to UTC
result = new DateTime(result.Ticks, DateTimeKind.Utc);
break;
case XsdDateTimeKind.LocalEastOfZulu:
// Adjust to UTC and then convert to local in the current time zone
ticks = result.Ticks - new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks;
if (ticks < DateTime.MinValue.Ticks)
{
// Underflow. Return the DateTime as local time directly
ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks;
if (ticks < DateTime.MinValue.Ticks)
ticks = DateTime.MinValue.Ticks;
return new DateTime(ticks, DateTimeKind.Local);
}
result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
break;
case XsdDateTimeKind.LocalWestOfZulu:
// Adjust to UTC and then convert to local in the current time zone
ticks = result.Ticks + new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks;
if (ticks > DateTime.MaxValue.Ticks)
{
// Overflow. Return the DateTime as local time directly
ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks;
if (ticks > DateTime.MaxValue.Ticks)
ticks = DateTime.MaxValue.Ticks;
return new DateTime(ticks, DateTimeKind.Local);
}
result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
break;
default:
break;
}
return result;
}
public static implicit operator DateTimeOffset(XsdDateTime xdt)
{
DateTime dt;
switch (xdt.InternalTypeCode)
{
case DateTimeTypeCode.GMonth:
case DateTimeTypeCode.GDay:
dt = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day);
break;
case DateTimeTypeCode.Time:
//back to DateTime.Now
DateTime currentDateTime = DateTime.Now;
TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day);
dt = xdt.dt.Add(addDiff);
break;
default:
dt = xdt.dt;
break;
}
DateTimeOffset result;
switch (xdt.InternalKind)
{
case XsdDateTimeKind.LocalEastOfZulu:
result = new DateTimeOffset(dt, new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0));
break;
case XsdDateTimeKind.LocalWestOfZulu:
result = new DateTimeOffset(dt, new TimeSpan(-xdt.ZoneHour, -xdt.ZoneMinute, 0));
break;
case XsdDateTimeKind.Zulu:
result = new DateTimeOffset(dt, new TimeSpan(0));
break;
case XsdDateTimeKind.Unspecified:
default:
result = new DateTimeOffset(dt, TimeZoneInfo.Local.GetUtcOffset(dt));
break;
}
return result;
}
/// <summary>
/// Serialization to a string
/// </summary>
public override string ToString()
{
StringBuilder sb = new StringBuilder(64);
char[] text;
switch (InternalTypeCode)
{
case DateTimeTypeCode.DateTime:
PrintDate(sb);
sb.Append('T');
PrintTime(sb);
break;
case DateTimeTypeCode.Time:
PrintTime(sb);
break;
case DateTimeTypeCode.Date:
PrintDate(sb);
break;
case DateTimeTypeCode.GYearMonth:
text = new char[Lzyyyy_MM];
IntToCharArray(text, 0, Year, 4);
text[Lzyyyy] = '-';
ShortToCharArray(text, Lzyyyy_, Month);
sb.Append(text);
break;
case DateTimeTypeCode.GYear:
text = new char[Lzyyyy];
IntToCharArray(text, 0, Year, 4);
sb.Append(text);
break;
case DateTimeTypeCode.GMonthDay:
text = new char[Lz__mm_dd];
text[0] = '-';
text[Lz_] = '-';
ShortToCharArray(text, Lz__, Month);
text[Lz__mm] = '-';
ShortToCharArray(text, Lz__mm_, Day);
sb.Append(text);
break;
case DateTimeTypeCode.GDay:
text = new char[Lz___dd];
text[0] = '-';
text[Lz_] = '-';
text[Lz__] = '-';
ShortToCharArray(text, Lz___, Day);
sb.Append(text);
break;
case DateTimeTypeCode.GMonth:
text = new char[Lz__mm__];
text[0] = '-';
text[Lz_] = '-';
ShortToCharArray(text, Lz__, Month);
text[Lz__mm] = '-';
text[Lz__mm_] = '-';
sb.Append(text);
break;
}
PrintZone(sb);
return sb.ToString();
}
// Serialize year, month and day
private void PrintDate(StringBuilder sb)
{
char[] text = new char[Lzyyyy_MM_dd];
IntToCharArray(text, 0, Year, 4);
text[Lzyyyy] = '-';
ShortToCharArray(text, Lzyyyy_, Month);
text[Lzyyyy_MM] = '-';
ShortToCharArray(text, Lzyyyy_MM_, Day);
sb.Append(text);
}
// Serialize hour, minute, second and fraction
private void PrintTime(StringBuilder sb)
{
char[] text = new char[LzHH_mm_ss];
ShortToCharArray(text, 0, Hour);
text[LzHH] = ':';
ShortToCharArray(text, LzHH_, Minute);
text[LzHH_mm] = ':';
ShortToCharArray(text, LzHH_mm_, Second);
sb.Append(text);
int fraction = Fraction;
if (fraction != 0)
{
int fractionDigits = maxFractionDigits;
while (fraction % 10 == 0)
{
fractionDigits--;
fraction /= 10;
}
text = new char[fractionDigits + 1];
text[0] = '.';
IntToCharArray(text, 1, fraction, fractionDigits);
sb.Append(text);
}
}
// Serialize time zone
private void PrintZone(StringBuilder sb)
{
char[] text;
switch (InternalKind)
{
case XsdDateTimeKind.Zulu:
sb.Append('Z');
break;
case XsdDateTimeKind.LocalWestOfZulu:
text = new char[Lz_zz_zz];
text[0] = '-';
ShortToCharArray(text, Lz_, ZoneHour);
text[Lz_zz] = ':';
ShortToCharArray(text, Lz_zz_, ZoneMinute);
sb.Append(text);
break;
case XsdDateTimeKind.LocalEastOfZulu:
text = new char[Lz_zz_zz];
text[0] = '+';
ShortToCharArray(text, Lz_, ZoneHour);
text[Lz_zz] = ':';
ShortToCharArray(text, Lz_zz_, ZoneMinute);
sb.Append(text);
break;
default:
// do nothing
break;
}
}
// Serialize integer into character array starting with index [start].
// Number of digits is set by [digits]
private void IntToCharArray(char[] text, int start, int value, int digits)
{
while (digits-- != 0)
{
text[start + digits] = (char)(value % 10 + '0');
value /= 10;
}
}
// Serialize two digit integer into character array starting with index [start].
private void ShortToCharArray(char[] text, int start, int value)
{
text[start] = (char)(value / 10 + '0');
text[start + 1] = (char)(value % 10 + '0');
}
// Parsing string according to XML schema spec
struct Parser
{
private const int leapYear = 1904;
private const int firstMonth = 1;
private const int firstDay = 1;
public DateTimeTypeCode typeCode;
public int year;
public int month;
public int day;
public int hour;
public int minute;
public int second;
public int fraction;
public XsdDateTimeKind kind;
public int zoneHour;
public int zoneMinute;
private string text;
private int length;
public bool Parse(string text, XsdDateTimeFlags kinds)
{
this.text = text;
this.length = text.Length;
// Skip leading withitespace
int start = 0;
while (start < length && char.IsWhiteSpace(text[start]))
{
start++;
}
// Choose format starting from the most common and trying not to reparse the same thing too many times
if (Test(kinds, XsdDateTimeFlags.DateTime | XsdDateTimeFlags.Date))
{
if (ParseDate(start))
{
if (Test(kinds, XsdDateTimeFlags.DateTime))
{
if (ParseChar(start + Lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(start + Lzyyyy_MM_ddT))
{
typeCode = DateTimeTypeCode.DateTime;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.Date))
{
if (ParseZoneAndWhitespace(start + Lzyyyy_MM_dd))
{
typeCode = DateTimeTypeCode.Date;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.Time))
{
if (ParseTimeAndZoneAndWhitespace(start))
{ //Equivalent to NoCurrentDateDefault on DateTimeStyles while parsing xs:time
year = leapYear;
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.Time;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GYearMonth | XsdDateTimeFlags.GYear))
{
if (Parse4Dig(start, ref year) && 1 <= year)
{
if (Test(kinds, XsdDateTimeFlags.GYearMonth))
{
if (
ParseChar(start + Lzyyyy, '-') &&
Parse2Dig(start + Lzyyyy_, ref month) && 1 <= month && month <= 12 &&
ParseZoneAndWhitespace(start + Lzyyyy_MM)
)
{
day = firstDay;
typeCode = DateTimeTypeCode.GYearMonth;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GYear))
{
if (ParseZoneAndWhitespace(start + Lzyyyy))
{
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.GYear;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.GMonthDay | XsdDateTimeFlags.GMonth))
{
if (
ParseChar(start, '-') &&
ParseChar(start + Lz_, '-') &&
Parse2Dig(start + Lz__, ref month) && 1 <= month && month <= 12
)
{
if (Test(kinds, XsdDateTimeFlags.GMonthDay) && ParseChar(start + Lz__mm, '-'))
{
if (
Parse2Dig(start + Lz__mm_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, month) &&
ParseZoneAndWhitespace(start + Lz__mm_dd)
)
{
year = leapYear;
typeCode = DateTimeTypeCode.GMonthDay;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GMonth))
{
if (ParseZoneAndWhitespace(start + Lz__mm) || (ParseChar(start + Lz__mm, '-') && ParseChar(start + Lz__mm_, '-') && ParseZoneAndWhitespace(start + Lz__mm__)))
{
year = leapYear;
day = firstDay;
typeCode = DateTimeTypeCode.GMonth;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.GDay))
{
if (
ParseChar(start, '-') &&
ParseChar(start + Lz_, '-') &&
ParseChar(start + Lz__, '-') &&
Parse2Dig(start + Lz___, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, firstMonth) &&
ParseZoneAndWhitespace(start + Lz___dd)
)
{
year = leapYear;
month = firstMonth;
typeCode = DateTimeTypeCode.GDay;
return true;
}
}
return false;
}
private bool ParseDate(int start)
{
return
Parse4Dig(start, ref year) && 1 <= year &&
ParseChar(start + Lzyyyy, '-') &&
Parse2Dig(start + Lzyyyy_, ref month) && 1 <= month && month <= 12 &&
ParseChar(start + Lzyyyy_MM, '-') &&
Parse2Dig(start + Lzyyyy_MM_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(year, month);
}
private bool ParseTimeAndZoneAndWhitespace(int start)
{
if (ParseTime(ref start))
{
if (ParseZoneAndWhitespace(start))
{
return true;
}
}
return false;
}
static int[] Power10 = new int[maxFractionDigits] { -1, 10, 100, 1000, 10000, 100000, 1000000 };
private bool ParseTime(ref int start)
{
if (
Parse2Dig(start, ref hour) && hour < 24 &&
ParseChar(start + LzHH, ':') &&
Parse2Dig(start + LzHH_, ref minute) && minute < 60 &&
ParseChar(start + LzHH_mm, ':') &&
Parse2Dig(start + LzHH_mm_, ref second) && second < 60
)
{
start += LzHH_mm_ss;
if (ParseChar(start, '.'))
{
// Parse factional part of seconds
// We allow any number of digits, but keep only first 7
this.fraction = 0;
int fractionDigits = 0;
int round = 0;
while (++start < length)
{
int d = text[start] - '0';
if (9u < (uint)d)
{ // d < 0 || 9 < d
break;
}
if (fractionDigits < maxFractionDigits)
{
this.fraction = (this.fraction * 10) + d;
}
else if (fractionDigits == maxFractionDigits)
{
if (5 < d)
{
round = 1;
}
else if (d == 5)
{
round = -1;
}
}
else if (round < 0 && d != 0)
{
round = 1;
}
fractionDigits++;
}
if (fractionDigits < maxFractionDigits)
{
if (fractionDigits == 0)
{
return false; // cannot end with .
}
fraction *= Power10[maxFractionDigits - fractionDigits];
}
else
{
if (round < 0)
{
round = fraction & 1;
}
fraction += round;
}
}
return true;
}
// cleanup - conflict with gYear
hour = 0;
return false;
}
private bool ParseZoneAndWhitespace(int start)
{
if (start < length)
{
char ch = text[start];
if (ch == 'Z' || ch == 'z')
{
kind = XsdDateTimeKind.Zulu;
start++;
}
else if (start + 5 < length)
{
if (
Parse2Dig(start + Lz_, ref zoneHour) && zoneHour <= 99 &&
ParseChar(start + Lz_zz, ':') &&
Parse2Dig(start + Lz_zz_, ref zoneMinute) && zoneMinute <= 99
)
{
if (ch == '-')
{
kind = XsdDateTimeKind.LocalWestOfZulu;
start += Lz_zz_zz;
}
else if (ch == '+')
{
kind = XsdDateTimeKind.LocalEastOfZulu;
start += Lz_zz_zz;
}
}
}
}
while (start < length && char.IsWhiteSpace(text[start]))
{
start++;
}
return start == length;
}
private bool Parse4Dig(int start, ref int num)
{
if (start + 3 < length)
{
int d4 = text[start] - '0';
int d3 = text[start + 1] - '0';
int d2 = text[start + 2] - '0';
int d1 = text[start + 3] - '0';
if (0 <= d4 && d4 < 10 &&
0 <= d3 && d3 < 10 &&
0 <= d2 && d2 < 10 &&
0 <= d1 && d1 < 10
)
{
num = ((d4 * 10 + d3) * 10 + d2) * 10 + d1;
return true;
}
}
return false;
}
private bool Parse2Dig(int start, ref int num)
{
if (start + 1 < length)
{
int d2 = text[start] - '0';
int d1 = text[start + 1] - '0';
if (0 <= d2 && d2 < 10 &&
0 <= d1 && d1 < 10
)
{
num = d2 * 10 + d1;
return true;
}
}
return false;
}
private bool ParseChar(int start, char ch)
{
return start < length && text[start] == ch;
}
private static bool Test(XsdDateTimeFlags left, XsdDateTimeFlags right)
{
return (left & right) != 0;
}
}
}
}
| |
//
// MimeUtils.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013 Jeffrey Stedfast
//
// 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.Net;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
namespace MimeKit.Utils {
/// <summary>
/// MIME utility methods.
/// </summary>
public static class MimeUtils
{
static int MessageIdCounter = 0;
/// <summary>
/// Generates a token suitable for a Message-Id.
/// </summary>
/// <returns>The message identifier.</returns>
/// <param name="domain">A domain to use.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="domain"/> is <c>null</c>.
/// </exception>
public static string GenerateMessageId (string domain)
{
if (domain == null)
throw new ArgumentNullException ("domain");
return string.Format ("<{0}.{1}.{2}@{3}>", DateTime.Now.Ticks,
Process.GetCurrentProcess ().Id,
MessageIdCounter++, domain);
}
/// <summary>
/// Generates a token suitable for a Message-Id.
/// </summary>
/// <returns>The message identifier.</returns>
public static string GenerateMessageId ()
{
return GenerateMessageId (Dns.GetHostName ());
}
/// <summary>
/// Enumerates the message-id references such as those that can be found in the In-Reply-To or References header.
/// </summary>
/// <returns>The references.</returns>
/// <param name="buffer">The raw byte buffer to parse.</param>
/// <param name="startIndex">The index into the buffer to start parsing.</param>
/// <param name="length">The length of the buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static IEnumerable<string> EnumerateReferences (byte[] buffer, int startIndex, int length)
{
int endIndex = startIndex + length;
int index = startIndex;
InternetAddress addr;
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || startIndex + length > buffer.Length)
throw new ArgumentOutOfRangeException ("length");
do {
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false))
break;
if (index >= endIndex)
break;
if (buffer[index] == '<') {
if (!InternetAddress.TryParseMailbox (buffer, startIndex, ref index, endIndex, "", 65001, false, out addr))
break;
yield return "<" + ((MailboxAddress) addr).Address + ">";
} else if (!ParseUtils.Skip8bitWord (buffer, ref index, endIndex, false)) {
index++;
}
} while (index < endIndex);
yield break;
}
/// <summary>
/// Enumerates the message-id references such as those that can be found in the In-Reply-To or References header.
/// </summary>
/// <returns>The references.</returns>
/// <param name="text">The text to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static IEnumerable<string> EnumerateReferences (string text)
{
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
return EnumerateReferences (buffer, 0, buffer.Length);
}
/// <summary>
/// Tries to parse a version from a header such as Mime-Version.
/// </summary>
/// <returns><c>true</c>, if the version was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The raw byte buffer to parse.</param>
/// <param name="startIndex">The index into the buffer to start parsing.</param>
/// <param name="length">The length of the buffer to parse.</param>
/// <param name="version">The parsed version.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParseVersion (byte[] buffer, int startIndex, int length, out Version version)
{
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (startIndex < 0 || startIndex > buffer.Length)
throw new ArgumentOutOfRangeException ("startIndex");
if (length < 0 || startIndex + length > buffer.Length)
throw new ArgumentOutOfRangeException ("length");
List<int> values = new List<int> ();
int endIndex = startIndex + length;
int index = startIndex;
int value;
version = null;
do {
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index >= endIndex)
return false;
if (!ParseUtils.TryParseInt32 (buffer, ref index, endIndex, out value))
return false;
values.Add (value);
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false))
return false;
if (index >= endIndex)
break;
if (buffer[index++] != (byte) '.')
return false;
} while (index < endIndex);
switch (values.Count) {
case 4: version = new Version (values[0], values[1], values[2], values[3]); break;
case 3: version = new Version (values[0], values[1], values[2]); break;
case 2: version = new Version (values[0], values[1]); break;
default: return false;
}
return true;
}
/// <summary>
/// Tries to parse a version from a header such as Mime-Version.
/// </summary>
/// <returns><c>true</c>, if the version was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="text">The text to parse.</param>
/// <param name="version">The parsed version.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParseVersion (string text, out Version version)
{
if (text == null)
throw new ArgumentNullException ("text");
var buffer = Encoding.UTF8.GetBytes (text);
return TryParseVersion (buffer, 0, buffer.Length, out version);
}
/// <summary>
/// Quotes the specified text, enclosing it in double-quotes and escaping
/// any backslashes and double-quotes within.
/// </summary>
/// <param name="text">The text to quote.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static string Quote (string text)
{
if (text == null)
throw new ArgumentNullException ("text");
var sb = new StringBuilder ();
sb.Append ("\"");
for (int i = 0; i < text.Length; i++) {
if (text[i] == '\\' || text[i] == '"')
sb.Append ('\\');
sb.Append (text[i]);
}
sb.Append ("\"");
return sb.ToString ();
}
/// <summary>
/// Unquotes the specified text, removing any escaped backslashes and
/// double-quotes within.
/// </summary>
/// <param name="text">The text to unquote.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static string Unquote (string text)
{
if (text == null)
throw new ArgumentNullException ("text");
int index = text.IndexOfAny (new char[] { '\r', '\n', '\t', '\\', '"' });
if (index == -1)
return text;
StringBuilder builder = new StringBuilder ();
bool escaped = false;
bool quoted = false;
for (int i = 0; i < text.Length; i++) {
switch (text[i]) {
case '\r':
case '\n':
break;
case '\t':
builder.Append (' ');
break;
case '\\':
if (escaped)
builder.Append ('\\');
escaped = !escaped;
break;
case '"':
if (escaped) {
builder.Append ('"');
escaped = false;
} else {
quoted = !quoted;
}
break;
default:
builder.Append (text[i]);
break;
}
}
return builder.ToString ();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace AngularJSExample.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Storage.Relational.Management;
using Orleans.Runtime.Storage.Relational;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace Orleans.Providers.SqlServer
{
public class SqlStatisticsPublisher: IConfigurableStatisticsPublisher, IConfigurableSiloMetricsDataPublisher, IConfigurableClientMetricsDataPublisher, IProvider
{
private string deploymentId;
private IPAddress clientAddress;
private SiloAddress siloAddress;
private IPEndPoint gateway;
private string clientId;
private string siloName;
private string hostName;
private bool isSilo;
private long generation;
private IRelationalStorage database;
private QueryConstantsBag queryConstants;
private Logger logger;
public string Name { get; private set; }
public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
{
Name = name;
logger = providerRuntime.GetLogger("SqlStatisticsPublisher");
string adoInvariant = AdoNetInvariants.InvariantNameSqlServer;
if (config.Properties.ContainsKey("AdoInvariant"))
adoInvariant = config.Properties["AdoInvariant"];
database = RelationalStorageUtilities.CreateGenericStorageInstance(adoInvariant, config.Properties["ConnectionString"]);
queryConstants = await database.InitializeOrleansQueriesAsync();
}
public void AddConfiguration(string deployment, string hostName, string client, IPAddress address)
{
deploymentId = deployment;
isSilo = false;
this.hostName = hostName;
clientId = client;
clientAddress = address;
generation = SiloAddress.AllocateNewGeneration();
}
public void AddConfiguration(string deployment, bool silo, string siloId, SiloAddress address, IPEndPoint gatewayAddress, string hostName)
{
deploymentId = deployment;
isSilo = silo;
siloName = siloId;
siloAddress = address;
gateway = gatewayAddress;
this.hostName = hostName;
if(!isSilo)
{
generation = SiloAddress.AllocateNewGeneration();
}
}
async Task IClientMetricsDataPublisher.Init(ClientConfiguration config, IPAddress address, string clientId)
{
database = RelationalStorageUtilities.CreateGenericStorageInstance(config.AdoInvariant, config.DataConnectionString);
queryConstants = await database.InitializeOrleansQueriesAsync();
}
public Task ReportMetrics(IClientPerformanceMetrics metricsData)
{
if(logger != null && logger.IsVerbose3) logger.Verbose3("SqlStatisticsPublisher.ReportMetrics (client) called with data: {0}.", metricsData);
try
{
var query = queryConstants.GetConstant(database.InvariantName, QueryKeys.UpsertReportClientMetricsKey);
return database.UpsertReportClientMetricsAsync(query, deploymentId, clientId, clientAddress, hostName, metricsData);
}
catch(Exception ex)
{
if (logger != null && logger.IsVerbose) logger.Verbose("SqlStatisticsPublisher.ReportMetrics (client) failed: {0}", ex);
throw;
}
}
async Task ISiloMetricsDataPublisher.Init(string deploymentId, string storageConnectionString, SiloAddress siloAddress, string siloName, IPEndPoint gateway, string hostName)
{
await database.InitializeOrleansQueriesAsync();
}
public Task ReportMetrics(ISiloPerformanceMetrics metricsData)
{
if (logger != null && logger.IsVerbose3) logger.Verbose3("SqlStatisticsPublisher.ReportMetrics (silo) called with data: {0}.", metricsData);
try
{
var query = queryConstants.GetConstant(database.InvariantName, QueryKeys.UpsertSiloMetricsKey);
return database.UpsertSiloMetricsAsync(query, deploymentId, siloName, gateway, siloAddress, hostName, metricsData);
}
catch(Exception ex)
{
if (logger != null && logger.IsVerbose) logger.Verbose("SqlStatisticsPublisher.ReportMetrics (silo) failed: {0}", ex);
throw;
}
}
Task IStatisticsPublisher.Init(bool isSilo, string storageConnectionString, string deploymentId, string address, string siloName, string hostName)
{
return TaskDone.Done;
}
public async Task ReportStats(List<ICounter> statsCounters)
{
var siloOrClientName = (isSilo) ? siloName : clientId;
var id = (isSilo) ? siloAddress.ToLongString() : string.Format("{0}:{1}", siloOrClientName, generation);
if (logger != null && logger.IsVerbose3) logger.Verbose3("ReportStats called with {0} counters, name: {1}, id: {2}", statsCounters.Count, siloOrClientName, id);
var insertTasks = new List<Task>();
try
{
//This batching is done for two reasons:
//1) For not to introduce a query large enough to be rejected.
//2) Performance, though using a fixed constants likely will not give the optimal performance in every situation.
const int maxBatchSizeInclusive = 200;
var counterBatches = BatchCounters(statsCounters, maxBatchSizeInclusive);
foreach(var counterBatch in counterBatches)
{
//The query template from which to retrieve the set of columns that are being inserted.
var queryTemplate = queryConstants.GetConstant(database.InvariantName, QueryKeys.InsertOrleansStatisticsKey);
insertTasks.Add(database.InsertStatisticsCountersAsync(queryTemplate, deploymentId, hostName, siloOrClientName, id, counterBatch));
}
await Task.WhenAll(insertTasks);
}
catch(Exception ex)
{
if (logger != null && logger.IsVerbose) logger.Verbose("ReportStats faulted: {0}", ex.ToString());
foreach(var faultedTask in insertTasks.Where(t => t.IsFaulted))
{
if (logger != null && logger.IsVerbose) logger.Verbose("Faulted task exception: {0}", faultedTask.ToString());
}
throw;
}
if (logger != null && logger.IsVerbose) logger.Verbose("ReportStats SUCCESS");
}
/// <summary>
/// Batches the counters list to batches of given maximum size.
/// </summary>
/// <param name="counters">The counters to batch.</param>
/// <param name="maxBatchSizeInclusive">The maximum size of one batch.</param>
/// <returns>The counters batched.</returns>
private static List<IList<ICounter>> BatchCounters(List<ICounter> counters, int maxBatchSizeInclusive)
{
var batches = new List<IList<ICounter>>();
for(int i = 0; i < counters.Count; i += maxBatchSizeInclusive)
{
batches.Add(counters.GetRange(i, Math.Min(maxBatchSizeInclusive, counters.Count - i)));
}
return batches;
}
}
}
| |
// <copyright file="Processing.cs" company="Public Domain">
// Released into the public domain
// </copyright>
// This file is part of the C# Packet Capture Analyser application. It is
// free and unencumbered software released into the public domain as detailed
// in the UNLICENSE file in the top level directory of this distribution
namespace PacketCaptureAnalyzer.EthernetFrame.IPPacket.IPv6Packet
{
/// <summary>
/// This class provides the IP v6 packet processing
/// </summary>
public class Processing
{
/// <summary>
/// The object that provides for the logging of debug information
/// </summary>
private Analysis.DebugInformation theDebugInformation;
/// <summary>
/// The object that provides for binary reading from the packet capture
/// </summary>
private System.IO.BinaryReader theBinaryReader;
/// <summary>
/// The reusable instance of the processing class for ICMP v6 packets
/// </summary>
private ICMPv6Packet.Processing theICMPv6PacketProcessing;
/// <summary>
/// The reusable instance of the processing class for TCP packets
/// </summary>
private TCPPacket.Processing theTCPPacketProcessing;
/// <summary>
/// The reusable instance of the processing class for UDP datagrams
/// </summary>
private UDPDatagram.Processing theUDPDatagramProcessing;
/// <summary>
/// The reusable instance of the processing class for EIGRP packets
/// </summary>
private EIGRPPacket.Processing theEIGRPPacketProcessing;
/// <summary>
/// Initializes a new instance of the Processing class
/// </summary>
/// <param name="theDebugInformation">The object that provides for the logging of debug information</param>
/// <param name="theBinaryReader">The object that provides for binary reading from the packet capture</param>
/// <param name="performLatencyAnalysisProcessing">Boolean flag that indicates whether to perform latency analysis processing for data read from the packet capture</param>
/// <param name="theLatencyAnalysisProcessing">The object that provides the latency analysis processing for data read from the packet capture</param>
/// <param name="performBurstAnalysisProcessing">Boolean flag that indicates whether to perform burst analysis processing for data read from the packet capture</param>
/// <param name="theBurstAnalysisProcessing">The object that provides the burst analysis processing for data read from the packet capture</param>
/// <param name="performTimeAnalysisProcessing">Boolean flag that indicates whether to perform time analysis processing for data read from the packet capture</param>
/// <param name="theTimeAnalysisProcessing">The object that provides the time analysis processing for data read from the packet capture</param>
/// <param name="useAlternativeSequenceNumber">Boolean flag that indicates whether to use the alternative sequence number in the data read from the packet capture, required for legacy recordings</param>
public Processing(Analysis.DebugInformation theDebugInformation, System.IO.BinaryReader theBinaryReader, bool performLatencyAnalysisProcessing, Analysis.LatencyAnalysis.Processing theLatencyAnalysisProcessing, bool performBurstAnalysisProcessing, Analysis.BurstAnalysis.Processing theBurstAnalysisProcessing, bool performTimeAnalysisProcessing, Analysis.TimeAnalysis.Processing theTimeAnalysisProcessing, bool useAlternativeSequenceNumber)
{
this.theDebugInformation = theDebugInformation;
this.theBinaryReader = theBinaryReader;
//// Create instances of the processing classes for each protocol
this.theICMPv6PacketProcessing = new ICMPv6Packet.Processing(theBinaryReader);
this.theTCPPacketProcessing =
new TCPPacket.Processing(
theDebugInformation,
theBinaryReader,
performLatencyAnalysisProcessing,
theLatencyAnalysisProcessing,
performBurstAnalysisProcessing,
theBurstAnalysisProcessing,
performTimeAnalysisProcessing,
theTimeAnalysisProcessing,
useAlternativeSequenceNumber);
this.theUDPDatagramProcessing =
new UDPDatagram.Processing(
theDebugInformation,
theBinaryReader,
performLatencyAnalysisProcessing,
theLatencyAnalysisProcessing,
performBurstAnalysisProcessing,
theBurstAnalysisProcessing,
performTimeAnalysisProcessing,
theTimeAnalysisProcessing,
useAlternativeSequenceNumber);
this.theEIGRPPacketProcessing = new EIGRPPacket.Processing(theBinaryReader);
}
/// <summary>
/// Processes an IP v6 packet
/// </summary>
/// <param name="theEthernetFrameLength">The length of the Ethernet frame</param>
/// <param name="thePacketNumber">The number for the packet read from the packet capture</param>
/// <param name="thePacketTimestamp">The timestamp for the packet read from the packet capture</param>
/// <returns>Boolean flag that indicates whether the IP v6 packet could be processed</returns>
public bool ProcessIPv6Packet(long theEthernetFrameLength, ulong thePacketNumber, double thePacketTimestamp)
{
bool theResult = true;
ushort theIPv6PacketPayloadLength;
byte theIPv6PacketProtocol;
// Process the IP v6 packet header
theResult = this.ProcessIPv6PacketHeader(
theEthernetFrameLength,
out theIPv6PacketPayloadLength,
out theIPv6PacketProtocol);
if (theResult)
{
// Process the payload of the IP v6 packet, supplying the length of the payload and the values for the source port and the destination port as returned by the processing of the IP v6 packet header
theResult = this.ProcessIPv6PacketPayload(
thePacketNumber,
thePacketTimestamp,
theIPv6PacketPayloadLength,
theIPv6PacketProtocol);
}
return theResult;
}
/// <summary>
/// Processes an IP v6 packet header
/// </summary>
/// <param name="theEthernetFrameLength">The length read from the packet capture for the Ethernet frame</param>
/// <param name="theIPv6PacketPayloadLength">The payload length of the IP v6 packet</param>
/// <param name="theIPv6PacketProtocol">The protocol for the IP v6 packet</param>
/// <returns>Boolean flag that indicates whether the IP v6 packet header could be processed</returns>
private bool ProcessIPv6PacketHeader(long theEthernetFrameLength, out ushort theIPv6PacketPayloadLength, out byte theIPv6PacketProtocol)
{
bool theResult = true;
// Provide a default value for the output parameter for the length of the IP v6 packet payload
theIPv6PacketPayloadLength = 0;
// Provide a default value for the output parameter for the protocol for the IP v6 packet
theIPv6PacketProtocol = 0;
// Read the values for the IP v6 packet header from the packet capture
// Read off and store the IP packet version and traffic class for use below
byte theVersionAndTrafficClass = this.theBinaryReader.ReadByte();
// Just read off the bytes for the IPv6 packet header traffic class and flow label from the packet capture so we can move on
this.theBinaryReader.ReadByte();
this.theBinaryReader.ReadUInt16();
// Set up the output parameter for the length of the payload of the IP v6 packet (e.g. a TCP packet), which is the total length of the IP v6 packet minus the length of the IP v6 packet header just calculated
theIPv6PacketPayloadLength =
(ushort)System.Net.IPAddress.NetworkToHostOrder(this.theBinaryReader.ReadInt16());
// Set up the output parameter for the protocol for the IP v6 packet
theIPv6PacketProtocol = this.theBinaryReader.ReadByte();
// Just read off the bytes for the IPv6 packet header hop limit from the packet capture so we can move on
this.theBinaryReader.ReadByte();
// Just read off the bytes for the IPv6 packet header hop limit from the packet capture so we can move on
this.theBinaryReader.ReadInt64(); // High bytes
this.theBinaryReader.ReadInt64(); // Low bytes
// Just read off the bytes for the IPv6 packet destination from the packet capture so we can move on
this.theBinaryReader.ReadInt64(); // High bytes
this.theBinaryReader.ReadInt64(); // Low bytes
// Determine the version of the IP v6 packet header
// Need to first extract the version value from the combined IP packet version and traffic class field
// We want the higher four bits from the combined IP packet version and traffic class field (as it's in a big endian representation) so do a bitwise OR with 0xF0 (i.e. 11110000 in binary) and shift down by four bits
ushort theIPv6PacketHeaderVersion =
(ushort)((theVersionAndTrafficClass & 0xF0) >> 4);
// Validate the IP v6 packet header
theResult = this.ValidateIPv6PacketHeader(
theEthernetFrameLength,
theIPv6PacketHeaderVersion,
theIPv6PacketPayloadLength);
if (theResult)
{
// Process the IP v6 packet based on the value indicated for the protocol in the the IP v6 packet header
switch (theIPv6PacketProtocol)
{
case (byte)Constants.Protocol.HopByHopOptions:
case (byte)Constants.Protocol.DestinationOptions:
{
// We have got an IP v6 packet containing an options extension header
// Set up the output parameter for the protocol for the IP v6 packet
// again, this time based on the value in the options extension header
theIPv6PacketProtocol = this.theBinaryReader.ReadByte();
// Read off and store the length of the options extension header from the packet capture for use below
byte theOptionsLength = this.theBinaryReader.ReadByte();
// Just read off the default bytes for the options and
// padding from the packet capture so we can move on
this.theBinaryReader.ReadUInt16();
this.theBinaryReader.ReadUInt32();
// Just read off the optional bytes for the options and padding
// (if necessary) from the packet capture so we can move on
this.theBinaryReader.ReadBytes(theOptionsLength);
// Reduce the length of the IP v6 packet to reflect that the bytes for the options extension header would have been included
theIPv6PacketPayloadLength -= (ushort)(8 + (8 * theOptionsLength));
break;
}
case (byte)Constants.Protocol.TCP:
case (byte)Constants.Protocol.UDP:
case (byte)Constants.Protocol.ICMPv6:
case (byte)Constants.Protocol.EIGRP:
{
// We have got an IP v6 packet containing a known protocol so continue processing
break;
}
default:
{
//// We have got an IP v6 packet containing an unknown protocol
//// Processing of packets with network data link types not enumerated above are obviously not currently supported!
this.theDebugInformation.WriteErrorEvent(
"The IP v6 packet contains an unexpected protocol of " +
string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:X}", theIPv6PacketProtocol) +
"!!!");
theResult = false;
break;
}
}
}
return theResult;
}
/// <summary>
/// Processes the payload of the IP v6 packet
/// </summary>
/// <param name="thePacketNumber">The number for the packet read from the packet capture</param>
/// <param name="thePacketTimestamp">The timestamp for the packet read from the packet capture</param>
/// <param name="theIPv6PacketPayloadLength">The length of the payload of the IP v6 packet</param>
/// <param name="theIPv6PacketProtocol">the protocol for the IP v6 packet</param>
/// <returns>Boolean flag that indicates whether the payload of the IP v6 packet could be processed</returns>
private bool ProcessIPv6PacketPayload(ulong thePacketNumber, double thePacketTimestamp, ushort theIPv6PacketPayloadLength, byte theIPv6PacketProtocol)
{
bool theResult = true;
// Process the IP v6 packet based on the value indicated for the protocol in the the IP v6 packet header
switch (theIPv6PacketProtocol)
{
case (byte)Constants.Protocol.TCP:
{
// We have got an IP v6 packet containing an TCP packet so process it
theResult = this.theTCPPacketProcessing.ProcessTCPPacket(
thePacketNumber,
thePacketTimestamp,
theIPv6PacketPayloadLength);
break;
}
case (byte)Constants.Protocol.UDP:
{
// We have got an IP v6 packet containing an UDP datagram so process it
theResult = this.theUDPDatagramProcessing.ProcessUDPDatagram(
thePacketNumber,
thePacketTimestamp,
theIPv6PacketPayloadLength);
break;
}
case (byte)Constants.Protocol.ICMPv6:
{
// We have got an IP v6 packet containing an ICMP v6 packet so process it
this.theICMPv6PacketProcessing.ProcessICMPv6Packet(
theIPv6PacketPayloadLength);
break;
}
case (byte)Constants.Protocol.EIGRP:
{
// We have got an IP v6 packet containing a Cisco EIGRP packet so process it
this.theEIGRPPacketProcessing.ProcessEIGRPPacket(
theIPv6PacketPayloadLength);
break;
}
default:
{
//// We have got an IP v6 packet containing an unknown protocol
//// Processing of packets with network data link types not enumerated above are obviously not currently supported!
this.theDebugInformation.WriteErrorEvent(
"The IP v6 packet contains an unexpected protocol of " +
string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:X}", theIPv6PacketProtocol) +
"!!!");
theResult = false;
break;
}
}
return theResult;
}
/// <summary>
/// Validates the IP v6 packet header
/// </summary>
/// <param name="theEthernetFrameLength">The length of the Ethernet frame</param>
/// <param name="theIPv6PacketHeaderVersion">The version of the IP v6 packet header</param>
/// <param name="theIPv6PacketPayloadLength">The payload length of the IP v6 packet</param>
/// <returns>Boolean flag that indicates whether the IP v6 packet header is valid</returns>
private bool ValidateIPv6PacketHeader(long theEthernetFrameLength, ushort theIPv6PacketHeaderVersion, ushort theIPv6PacketPayloadLength)
{
bool theResult = true;
// Validate the payload length in the IP v6 packet header
if ((theIPv6PacketPayloadLength + Constants.HeaderLength) > theEthernetFrameLength)
{
//// We have got an IP v6 packet containing a payload length that is higher than the payload in the Ethernet frame which is invalid
this.theDebugInformation.WriteErrorEvent(
"The IP v6 packet indicates a total length of " +
(theIPv6PacketPayloadLength + Constants.HeaderLength).ToString(System.Globalization.CultureInfo.CurrentCulture) +
" bytes that is greater than the length of " +
theEthernetFrameLength.ToString(System.Globalization.CultureInfo.CurrentCulture) +
" bytes in the Ethernet frame!!!");
theResult = false;
}
// Validate the version in the IP v6 packet header
if (theIPv6PacketHeaderVersion != Constants.HeaderVersion)
{
//// We have got an IP v6 packet header containing an unknown version
this.theDebugInformation.WriteErrorEvent(
"The IP v6 packet header contains an unexpected version of " +
theIPv6PacketHeaderVersion.ToString(System.Globalization.CultureInfo.CurrentCulture) +
"!!!");
theResult = false;
}
return theResult;
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2014 FUJIWARA, Yusuke
//
// 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 -- License Terms --
#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections;
using System.Collections.Generic;
#if !UNITY
using System.Diagnostics.Contracts;
#endif // !UNITY
namespace MsgPack
{
partial class MessagePackObjectDictionary
{
/// <summary>
/// Enumerates the elements of a <see cref="MessagePackObjectDictionary"/> in order.
/// </summary>
public struct Enumerator : IEnumerator<KeyValuePair<MessagePackObject, MessagePackObject>>, IDictionaryEnumerator
{
private const int BeforeHead = -1;
private const int IsDictionary = -2;
private const int End = -3;
private readonly MessagePackObjectDictionary _underlying;
private Dictionary<MessagePackObject, MessagePackObject>.Enumerator _enumerator;
private KeyValuePair<MessagePackObject, MessagePackObject> _current;
private int _position;
private int _initialVersion;
/// <summary>
/// Gets the element at the current position of the enumerator.
/// </summary>
/// <value>
/// The element in the underlying collection at the current position of the enumerator.
/// </value>
public KeyValuePair<MessagePackObject, MessagePackObject> Current
{
get
{
this.VerifyVersion();
return this._current;
}
}
/// <summary>
/// Gets the element at the current position of the enumerator.
/// </summary>
/// <value>
/// The element in the collection at the current position of the enumerator, as an <see cref="Object"/>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
object IEnumerator.Current
{
get { return this.GetCurrentStrict(); }
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
var entry = this.GetCurrentStrict();
return new DictionaryEntry( entry.Key, entry.Value );
}
}
object IDictionaryEnumerator.Key
{
get { return this.GetCurrentStrict().Key; }
}
object IDictionaryEnumerator.Value
{
get { return this.GetCurrentStrict().Value; }
}
internal KeyValuePair<MessagePackObject, MessagePackObject> GetCurrentStrict()
{
this.VerifyVersion();
if ( this._position == BeforeHead || this._position == End )
{
throw new InvalidOperationException( "The enumerator is positioned before the first element of the collection or after the last element." );
}
return this._current;
}
internal Enumerator( MessagePackObjectDictionary dictionary )
: this()
{
#if !UNITY
Contract.Assert( dictionary != null );
#endif // !UNITY
this = default( Enumerator );
this._underlying = dictionary;
this.ResetCore();
}
internal void VerifyVersion()
{
if ( this._underlying != null && this._underlying._version != this._initialVersion )
{
throw new InvalidOperationException( "The collection was modified after the enumerator was created." );
}
}
/// <summary>
/// Releases all resources used by the this instance.
/// </summary>
public void Dispose()
{
this._enumerator.Dispose();
}
/// <summary>
/// Advances the enumerator to the next element of the underlying collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
if ( this._position == End )
{
return false;
}
if ( this._position == IsDictionary )
{
if ( !this._enumerator.MoveNext() )
{
return false;
}
this._current = this._enumerator.Current;
return true;
}
if ( this._position == BeforeHead )
{
if ( this._underlying._keys.Count == 0 )
{
this._position = End;
return false;
}
// First
this._position = 0;
}
else
{
this._position++;
}
if ( this._position == this._underlying._keys.Count )
{
this._position = End;
return false;
}
this._current = new KeyValuePair<MessagePackObject, MessagePackObject>( this._underlying._keys[ this._position ], this._underlying._values[ this._position ] );
return true;
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
void IEnumerator.Reset()
{
this.ResetCore();
}
internal void ResetCore()
{
this._initialVersion = this._underlying._version;
this._current = default( KeyValuePair<MessagePackObject, MessagePackObject> );
this._initialVersion = this._underlying._version;
if ( this._underlying._dictionary != null )
{
this._enumerator = this._underlying._dictionary.GetEnumerator();
this._position = IsDictionary;
}
else
{
this._position = BeforeHead;
}
}
}
/// <summary>
/// Enumerates the elements of a <see cref="MessagePackObjectDictionary"/> in order.
/// </summary>
private struct DictionaryEnumerator : IDictionaryEnumerator
{
private IDictionaryEnumerator _underlying;
/// <summary>
/// Gets the element at the current position of the enumerator.
/// </summary>
/// <value>
/// The element in the collection at the current position of the enumerator, as an <see cref="Object"/>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
public object Current
{
get { return this._underlying.Entry; }
}
/// <summary>
/// Gets the element at the current position of the enumerator.
/// </summary>
/// <returns>
/// The element in the dictionary at the current position of the enumerator, as a <see cref="T:System.Collections.DictionaryEntry"/>.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
public DictionaryEntry Entry
{
get { return this._underlying.Entry; }
}
/// <summary>
/// Gets the key of the element at the current position of the enumerator.
/// </summary>
/// <returns>
/// The key of the element in the dictionary at the current position of the enumerator.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
public object Key
{
get { return this.Entry.Key; }
}
/// <summary>
/// Gets the value of the element at the current position of the enumerator.
/// </summary>
/// <returns>
/// The value of the element in the dictionary at the current position of the enumerator.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
public object Value
{
get { return this.Entry.Value; }
}
internal DictionaryEnumerator( MessagePackObjectDictionary dictionary )
: this()
{
#if !UNITY
Contract.Assert( dictionary != null );
#endif // !UNITY
this._underlying = new Enumerator( dictionary );
}
/// <summary>
/// Advances the enumerator to the next element of the underlying collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
return this._underlying.MoveNext();
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
void IEnumerator.Reset()
{
this._underlying.Reset();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace System.Net.Test.Common
{
public sealed partial class LoopbackServer
{
internal enum AuthenticationProtocols
{
Basic,
Digest,
None
}
public async Task<List<string>> AcceptConnectionPerformAuthenticationAndCloseAsync(string authenticateHeaders)
{
List<string> lines = null;
await AcceptConnectionAsync(async connection =>
{
string headerName = _options.IsProxy ? "Proxy-Authorization" : "Authorization";
lines = await connection.ReadRequestHeaderAsync();
if (GetRequestHeaderValue(lines, headerName) == null)
{
await connection.SendResponseAsync( _options.IsProxy ?
HttpStatusCode.ProxyAuthenticationRequired : HttpStatusCode.Unauthorized, authenticateHeaders);
lines = await connection.ReadRequestHeaderAsync();
}
Debug.Assert(lines.Count > 0);
int index = lines[0] != null ? lines[0].IndexOf(' ') : -1;
string requestMethod = null;
if (index != -1)
{
requestMethod = lines[0].Substring(0, index);
}
// Read the authorization header from client.
AuthenticationProtocols protocol = AuthenticationProtocols.None;
string clientResponse = null;
for (int i = 1; i < lines.Count; i++)
{
if (lines[i].StartsWith(headerName))
{
clientResponse = lines[i];
if (lines[i].Contains(nameof(AuthenticationProtocols.Basic)))
{
protocol = AuthenticationProtocols.Basic;
break;
}
else if (lines[i].Contains(nameof(AuthenticationProtocols.Digest)))
{
protocol = AuthenticationProtocols.Digest;
break;
}
}
}
bool success = false;
switch (protocol)
{
case AuthenticationProtocols.Basic:
success = IsBasicAuthTokenValid(clientResponse, _options);
break;
case AuthenticationProtocols.Digest:
// Read the request content.
success = IsDigestAuthTokenValid(clientResponse, requestMethod, _options);
break;
}
if (success)
{
await connection.SendResponseAsync(additionalHeaders: "Connection: close\r\n");
}
else
{
await connection.SendResponseAsync(HttpStatusCode.Unauthorized, "Connection: close\r\n" + authenticateHeaders);
}
});
return lines;
}
internal static bool IsBasicAuthTokenValid(string clientResponse, LoopbackServer.Options options)
{
string clientHash = clientResponse.Substring(clientResponse.IndexOf(nameof(AuthenticationProtocols.Basic), StringComparison.OrdinalIgnoreCase) +
nameof(AuthenticationProtocols.Basic).Length).Trim();
string userPass = string.IsNullOrEmpty(options.Domain) ? options.Username + ":" + options.Password : options.Domain + "\\" + options.Username + ":" + options.Password;
return clientHash == Convert.ToBase64String(Encoding.UTF8.GetBytes(userPass));
}
internal static bool IsDigestAuthTokenValid(string clientResponse, string requestMethod, LoopbackServer.Options options)
{
string clientHash = clientResponse.Substring(clientResponse.IndexOf(nameof(AuthenticationProtocols.Digest), StringComparison.OrdinalIgnoreCase) +
nameof(AuthenticationProtocols.Digest).Length).Trim();
string[] values = clientHash.Split(',');
string username = null, uri = null, realm = null, nonce = null, response = null, algorithm = null, cnonce = null, opaque = null, qop = null, nc = null;
bool userhash = false;
for (int i = 0; i < values.Length; i++)
{
string trimmedValue = values[i].Trim();
if (trimmedValue.Contains(nameof(username)))
{
// Username is a quoted string.
int startIndex = trimmedValue.IndexOf('"');
if (startIndex != -1)
{
startIndex += 1;
username = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex - 1);
}
// Username is mandatory.
if (string.IsNullOrEmpty(username))
return false;
}
else if (trimmedValue.Contains(nameof(userhash)) && trimmedValue.Contains("true"))
{
userhash = true;
}
else if (trimmedValue.Contains(nameof(uri)))
{
int startIndex = trimmedValue.IndexOf('"');
if (startIndex != -1)
{
startIndex += 1;
uri = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex - 1);
}
// Request uri is mandatory.
if (string.IsNullOrEmpty(uri))
return false;
}
else if (trimmedValue.Contains(nameof(realm)))
{
// Realm is a quoted string.
int startIndex = trimmedValue.IndexOf('"');
if (startIndex != -1)
{
startIndex += 1;
realm = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex - 1);
}
// Realm is mandatory.
if (string.IsNullOrEmpty(realm))
return false;
}
else if (trimmedValue.Contains(nameof(cnonce)))
{
// CNonce is a quoted string.
int startIndex = trimmedValue.IndexOf('"');
if (startIndex != -1)
{
startIndex += 1;
cnonce = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex - 1);
}
}
else if (trimmedValue.Contains(nameof(nonce)))
{
// Nonce is a quoted string.
int startIndex = trimmedValue.IndexOf('"');
if (startIndex != -1)
{
startIndex += 1;
nonce = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex - 1);
}
// Nonce is mandatory.
if (string.IsNullOrEmpty(nonce))
return false;
}
else if (trimmedValue.Contains(nameof(response)))
{
// response is a quoted string.
int startIndex = trimmedValue.IndexOf('"');
if (startIndex != -1)
{
startIndex += 1;
response = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex - 1);
}
// Response is mandatory.
if (string.IsNullOrEmpty(response))
return false;
}
else if (trimmedValue.Contains(nameof(algorithm)))
{
int startIndex = trimmedValue.IndexOf('=');
if (startIndex != -1)
{
startIndex += 1;
algorithm = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex).Trim();
}
}
else if (trimmedValue.Contains(nameof(opaque)))
{
// Opaque is a quoted string.
int startIndex = trimmedValue.IndexOf('"');
if (startIndex != -1)
{
startIndex += 1;
opaque = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex - 1);
}
}
else if (trimmedValue.Contains(nameof(qop)))
{
int startIndex = trimmedValue.IndexOf('"');
if (startIndex != -1)
{
startIndex += 1;
qop = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex - 1);
}
else if ((startIndex = trimmedValue.IndexOf('=')) != -1)
{
startIndex += 1;
qop = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex).Trim();
}
}
else if (trimmedValue.Contains(nameof(nc)))
{
int startIndex = trimmedValue.IndexOf('=');
if (startIndex != -1)
{
startIndex += 1;
nc = trimmedValue.Substring(startIndex, trimmedValue.Length - startIndex).Trim();
}
}
}
// Verify username.
if (userhash && ComputeHash(options.Username + ":" + realm, algorithm) != username)
{
return false;
}
if (!userhash && options.Username != username)
{
return false;
}
if (string.IsNullOrEmpty(algorithm))
algorithm = "MD5";
// Calculate response and compare with the client response hash.
string a1 = options.Username + ":" + realm + ":" + options.Password;
if (algorithm.EndsWith("sess", StringComparison.OrdinalIgnoreCase))
{
a1 = ComputeHash(a1, algorithm) + ":" + nonce;
if (cnonce != null)
a1 += ":" + cnonce;
}
string a2 = requestMethod + ":" + uri;
if (!string.IsNullOrEmpty(qop) && qop.Equals("auth-int"))
{
// Request content is empty.
a2 = a2 + ":" + ComputeHash(string.Empty, algorithm);
}
string serverResponseHash = ComputeHash(a1, algorithm) + ":" + nonce + ":";
if (nc != null)
serverResponseHash += nc + ":";
if (cnonce != null)
serverResponseHash += cnonce + ":";
if (qop != null)
serverResponseHash += qop + ":";
serverResponseHash += ComputeHash(a2, algorithm);
serverResponseHash = ComputeHash(serverResponseHash, algorithm);
return response == serverResponseHash;
}
private static string ComputeHash(string data, string algorithm)
{
// Disable MD5 insecure warning.
#pragma warning disable CA5351
using (HashAlgorithm hash = algorithm.StartsWith("SHA-256", StringComparison.OrdinalIgnoreCase) ? SHA256.Create() : (HashAlgorithm)MD5.Create())
#pragma warning restore CA5351
{
Encoding enc = Encoding.UTF8;
byte[] result = hash.ComputeHash(enc.GetBytes(data));
StringBuilder sb = new StringBuilder(result.Length * 2);
foreach (byte b in result)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Controls.DataGridColumn.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Controls
{
abstract public partial class DataGridColumn : System.Windows.DependencyObject
{
#region Methods and constructors
protected virtual new void CancelCellEdit(System.Windows.FrameworkElement editingElement, Object uneditedValue)
{
Contract.Requires(editingElement != null);
}
protected virtual new bool CommitCellEdit(System.Windows.FrameworkElement editingElement)
{
Contract.Requires(editingElement != null);
return default(bool);
}
protected DataGridColumn()
{
}
protected abstract System.Windows.FrameworkElement GenerateEditingElement(DataGridCell cell, Object dataItem);
protected abstract System.Windows.FrameworkElement GenerateElement(DataGridCell cell, Object dataItem);
public System.Windows.FrameworkElement GetCellContent(Object dataItem)
{
return default(System.Windows.FrameworkElement);
}
public System.Windows.FrameworkElement GetCellContent(DataGridRow dataGridRow)
{
return default(System.Windows.FrameworkElement);
}
protected void NotifyPropertyChanged(string propertyName)
{
}
protected virtual new bool OnCoerceIsReadOnly(bool baseValue)
{
return default(bool);
}
public virtual new Object OnCopyingCellClipboardContent(Object item)
{
return default(Object);
}
public virtual new void OnPastingCellClipboardContent(Object item, Object cellContent)
{
}
protected virtual new Object PrepareCellForEdit(System.Windows.FrameworkElement editingElement, System.Windows.RoutedEventArgs editingEventArgs)
{
return default(Object);
}
protected internal virtual new void RefreshCellContent(System.Windows.FrameworkElement element, string propertyName)
{
}
#endregion
#region Properties and indexers
public double ActualWidth
{
get
{
return default(double);
}
private set
{
}
}
public bool CanUserReorder
{
get
{
return default(bool);
}
set
{
}
}
public bool CanUserResize
{
get
{
return default(bool);
}
set
{
}
}
public bool CanUserSort
{
get
{
return default(bool);
}
set
{
}
}
public System.Windows.Style CellStyle
{
get
{
return default(System.Windows.Style);
}
set
{
}
}
public virtual new System.Windows.Data.BindingBase ClipboardContentBinding
{
get
{
return default(System.Windows.Data.BindingBase);
}
set
{
}
}
internal protected DataGrid DataGridOwner
{
get
{
return default(DataGrid);
}
internal set
{
}
}
public int DisplayIndex
{
get
{
return default(int);
}
set
{
}
}
public System.Windows.Style DragIndicatorStyle
{
get
{
return default(System.Windows.Style);
}
set
{
}
}
public Object Header
{
get
{
return default(Object);
}
set
{
}
}
public string HeaderStringFormat
{
get
{
return default(string);
}
set
{
}
}
public System.Windows.Style HeaderStyle
{
get
{
return default(System.Windows.Style);
}
set
{
}
}
public System.Windows.DataTemplate HeaderTemplate
{
get
{
return default(System.Windows.DataTemplate);
}
set
{
}
}
public DataTemplateSelector HeaderTemplateSelector
{
get
{
return default(DataTemplateSelector);
}
set
{
}
}
public bool IsAutoGenerated
{
get
{
return default(bool);
}
internal set
{
}
}
public bool IsFrozen
{
get
{
return default(bool);
}
internal set
{
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
set
{
}
}
public double MaxWidth
{
get
{
return default(double);
}
set
{
}
}
public double MinWidth
{
get
{
return default(double);
}
set
{
}
}
public Nullable<System.ComponentModel.ListSortDirection> SortDirection
{
get
{
return default(Nullable<System.ComponentModel.ListSortDirection>);
}
set
{
}
}
public string SortMemberPath
{
get
{
return default(string);
}
set
{
}
}
public System.Windows.Visibility Visibility
{
get
{
return default(System.Windows.Visibility);
}
set
{
}
}
public DataGridLength Width
{
get
{
return default(DataGridLength);
}
set
{
}
}
#endregion
#region Events
public event EventHandler<DataGridCellClipboardEventArgs> CopyingCellClipboardContent
{
add
{
}
remove
{
}
}
public event EventHandler<DataGridCellClipboardEventArgs> PastingCellClipboardContent
{
add
{
}
remove
{
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty ActualWidthProperty;
public readonly static System.Windows.DependencyProperty CanUserReorderProperty;
public readonly static System.Windows.DependencyProperty CanUserResizeProperty;
public readonly static System.Windows.DependencyProperty CanUserSortProperty;
public readonly static System.Windows.DependencyProperty CellStyleProperty;
public readonly static System.Windows.DependencyProperty DisplayIndexProperty;
public readonly static System.Windows.DependencyProperty DragIndicatorStyleProperty;
public readonly static System.Windows.DependencyProperty HeaderProperty;
public readonly static System.Windows.DependencyProperty HeaderStringFormatProperty;
public readonly static System.Windows.DependencyProperty HeaderStyleProperty;
public readonly static System.Windows.DependencyProperty HeaderTemplateProperty;
public readonly static System.Windows.DependencyProperty HeaderTemplateSelectorProperty;
public readonly static System.Windows.DependencyProperty IsAutoGeneratedProperty;
public readonly static System.Windows.DependencyProperty IsFrozenProperty;
public readonly static System.Windows.DependencyProperty IsReadOnlyProperty;
public readonly static System.Windows.DependencyProperty MaxWidthProperty;
public readonly static System.Windows.DependencyProperty MinWidthProperty;
public readonly static System.Windows.DependencyProperty SortDirectionProperty;
public readonly static System.Windows.DependencyProperty SortMemberPathProperty;
public readonly static System.Windows.DependencyProperty VisibilityProperty;
public readonly static System.Windows.DependencyProperty WidthProperty;
#endregion
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// NewAccountSummary
/// </summary>
[DataContract]
public partial class NewAccountSummary : IEquatable<NewAccountSummary>, IValidatableObject
{
public NewAccountSummary()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="NewAccountSummary" /> class.
/// </summary>
/// <param name="AccountId">The account ID associated with the envelope..</param>
/// <param name="AccountIdGuid">The GUID associated with the account ID..</param>
/// <param name="AccountName">The account name for the new account..</param>
/// <param name="ApiPassword">Contains a token that can be used for authentication in API calls instead of using the user name and password..</param>
/// <param name="BaseUrl">The URL that should be used for successive calls to this account. It includes the protocal (https), the DocuSign server where the account is located, and the account number. Use this Url to make API calls against this account. Many of the API calls provide Uri's that are relative to this baseUrl..</param>
/// <param name="BillingPlanPreview">BillingPlanPreview.</param>
/// <param name="UserId">Specifies the user ID of the new user..</param>
public NewAccountSummary(string AccountId = default(string), string AccountIdGuid = default(string), string AccountName = default(string), string ApiPassword = default(string), string BaseUrl = default(string), BillingPlanPreview BillingPlanPreview = default(BillingPlanPreview), string UserId = default(string))
{
this.AccountId = AccountId;
this.AccountIdGuid = AccountIdGuid;
this.AccountName = AccountName;
this.ApiPassword = ApiPassword;
this.BaseUrl = BaseUrl;
this.BillingPlanPreview = BillingPlanPreview;
this.UserId = UserId;
}
/// <summary>
/// The account ID associated with the envelope.
/// </summary>
/// <value>The account ID associated with the envelope.</value>
[DataMember(Name="accountId", EmitDefaultValue=false)]
public string AccountId { get; set; }
/// <summary>
/// The GUID associated with the account ID.
/// </summary>
/// <value>The GUID associated with the account ID.</value>
[DataMember(Name="accountIdGuid", EmitDefaultValue=false)]
public string AccountIdGuid { get; set; }
/// <summary>
/// The account name for the new account.
/// </summary>
/// <value>The account name for the new account.</value>
[DataMember(Name="accountName", EmitDefaultValue=false)]
public string AccountName { get; set; }
/// <summary>
/// Contains a token that can be used for authentication in API calls instead of using the user name and password.
/// </summary>
/// <value>Contains a token that can be used for authentication in API calls instead of using the user name and password.</value>
[DataMember(Name="apiPassword", EmitDefaultValue=false)]
public string ApiPassword { get; set; }
/// <summary>
/// The URL that should be used for successive calls to this account. It includes the protocal (https), the DocuSign server where the account is located, and the account number. Use this Url to make API calls against this account. Many of the API calls provide Uri's that are relative to this baseUrl.
/// </summary>
/// <value>The URL that should be used for successive calls to this account. It includes the protocal (https), the DocuSign server where the account is located, and the account number. Use this Url to make API calls against this account. Many of the API calls provide Uri's that are relative to this baseUrl.</value>
[DataMember(Name="baseUrl", EmitDefaultValue=false)]
public string BaseUrl { get; set; }
/// <summary>
/// Gets or Sets BillingPlanPreview
/// </summary>
[DataMember(Name="billingPlanPreview", EmitDefaultValue=false)]
public BillingPlanPreview BillingPlanPreview { get; set; }
/// <summary>
/// Specifies the user ID of the new user.
/// </summary>
/// <value>Specifies the user ID of the new user.</value>
[DataMember(Name="userId", EmitDefaultValue=false)]
public string UserId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class NewAccountSummary {\n");
sb.Append(" AccountId: ").Append(AccountId).Append("\n");
sb.Append(" AccountIdGuid: ").Append(AccountIdGuid).Append("\n");
sb.Append(" AccountName: ").Append(AccountName).Append("\n");
sb.Append(" ApiPassword: ").Append(ApiPassword).Append("\n");
sb.Append(" BaseUrl: ").Append(BaseUrl).Append("\n");
sb.Append(" BillingPlanPreview: ").Append(BillingPlanPreview).Append("\n");
sb.Append(" UserId: ").Append(UserId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as NewAccountSummary);
}
/// <summary>
/// Returns true if NewAccountSummary instances are equal
/// </summary>
/// <param name="other">Instance of NewAccountSummary to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(NewAccountSummary other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.AccountId == other.AccountId ||
this.AccountId != null &&
this.AccountId.Equals(other.AccountId)
) &&
(
this.AccountIdGuid == other.AccountIdGuid ||
this.AccountIdGuid != null &&
this.AccountIdGuid.Equals(other.AccountIdGuid)
) &&
(
this.AccountName == other.AccountName ||
this.AccountName != null &&
this.AccountName.Equals(other.AccountName)
) &&
(
this.ApiPassword == other.ApiPassword ||
this.ApiPassword != null &&
this.ApiPassword.Equals(other.ApiPassword)
) &&
(
this.BaseUrl == other.BaseUrl ||
this.BaseUrl != null &&
this.BaseUrl.Equals(other.BaseUrl)
) &&
(
this.BillingPlanPreview == other.BillingPlanPreview ||
this.BillingPlanPreview != null &&
this.BillingPlanPreview.Equals(other.BillingPlanPreview)
) &&
(
this.UserId == other.UserId ||
this.UserId != null &&
this.UserId.Equals(other.UserId)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.AccountId != null)
hash = hash * 59 + this.AccountId.GetHashCode();
if (this.AccountIdGuid != null)
hash = hash * 59 + this.AccountIdGuid.GetHashCode();
if (this.AccountName != null)
hash = hash * 59 + this.AccountName.GetHashCode();
if (this.ApiPassword != null)
hash = hash * 59 + this.ApiPassword.GetHashCode();
if (this.BaseUrl != null)
hash = hash * 59 + this.BaseUrl.GetHashCode();
if (this.BillingPlanPreview != null)
hash = hash * 59 + this.BillingPlanPreview.GetHashCode();
if (this.UserId != null)
hash = hash * 59 + this.UserId.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System.Text;
using System;
using CultureInfo = System.Globalization.CultureInfo;
using System.Diagnostics.SymbolStore;
using System.Reflection;
using System.Security;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
public sealed class MethodBuilder : MethodInfo
{
#region Private Data Members
// Identity
internal String m_strName; // The name of the method
private MethodToken m_tkMethod; // The token of this method
private ModuleBuilder m_module;
internal TypeBuilder m_containingType;
// IL
private int[] m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups.
private byte[] m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise.
internal LocalSymInfo m_localSymInfo; // keep track debugging local information
internal ILGenerator m_ilGenerator; // Null if not used.
private byte[] m_ubBody; // The IL for the method
private ExceptionHandler[] m_exceptions; // Exception handlers or null if there are none.
private const int DefaultMaxStack = 16;
private int m_maxStack = DefaultMaxStack;
// Flags
internal bool m_bIsBaked;
private bool m_bIsGlobalMethod;
private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not.
// Attributes
private MethodAttributes m_iAttributes;
private CallingConventions m_callingConvention;
private MethodImplAttributes m_dwMethodImplFlags;
// Parameters
private SignatureHelper m_signature;
internal Type[] m_parameterTypes;
private ParameterBuilder m_retParam;
private Type m_returnType;
private Type[] m_returnTypeRequiredCustomModifiers;
private Type[] m_returnTypeOptionalCustomModifiers;
private Type[][] m_parameterTypeRequiredCustomModifiers;
private Type[][] m_parameterTypeOptionalCustomModifiers;
// Generics
private GenericTypeParameterBuilder[] m_inst;
private bool m_bIsGenMethDef;
#endregion
#region Constructor
internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
Init(name, attributes, callingConvention,
returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
mod, type, bIsGlobalMethod);
}
private void Init(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name[0] == '\0')
throw new ArgumentException(SR.Argument_IllegalName, nameof(name));
if (mod == null)
throw new ArgumentNullException(nameof(mod));
if (parameterTypes != null)
{
foreach (Type t in parameterTypes)
{
if (t == null)
throw new ArgumentNullException(nameof(parameterTypes));
}
}
m_strName = name;
m_module = mod;
m_containingType = type;
//
//if (returnType == null)
//{
// m_returnType = typeof(void);
//}
//else
{
m_returnType = returnType;
}
if ((attributes & MethodAttributes.Static) == 0)
{
// turn on the has this calling convention
callingConvention = callingConvention | CallingConventions.HasThis;
}
else if ((attributes & MethodAttributes.Virtual) != 0)
{
// A method can't be both static and virtual
throw new ArgumentException(SR.Arg_NoStaticVirtual);
}
#if !FEATURE_DEFAULT_INTERFACES
if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName)
{
if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface)
{
// methods on interface have to be abstract + virtual except special name methods such as type initializer
if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) !=
(MethodAttributes.Abstract | MethodAttributes.Virtual) &&
(attributes & MethodAttributes.Static) == 0)
throw new ArgumentException(SR.Argument_BadAttributeOnInterfaceMethod);
}
}
#endif
m_callingConvention = callingConvention;
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length);
}
else
{
m_parameterTypes = null;
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
// m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
// returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
// parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
m_iAttributes = attributes;
m_bIsGlobalMethod = bIsGlobalMethod;
m_bIsBaked = false;
m_fInitLocals = true;
m_localSymInfo = new LocalSymInfo();
m_ubBody = null;
m_ilGenerator = null;
// Default is managed IL. Manged IL has bit flag 0x0020 set off
m_dwMethodImplFlags = MethodImplAttributes.IL;
}
#endregion
#region Internal Members
internal void CheckContext(params Type[][] typess)
{
m_module.CheckContext(typess);
}
internal void CheckContext(params Type[] types)
{
m_module.CheckContext(types);
}
internal void CreateMethodBodyHelper(ILGenerator il)
{
// Sets the IL of the method. An ILGenerator is passed as an argument and the method
// queries this instance to get all of the information which it needs.
if (il == null)
{
throw new ArgumentNullException(nameof(il));
}
__ExceptionInfo[] excp;
int counter = 0;
int[] filterAddrs;
int[] catchAddrs;
int[] catchEndAddrs;
Type[] catchClass;
int[] type;
int numCatch;
int start, end;
ModuleBuilder dynMod = (ModuleBuilder)m_module;
m_containingType.ThrowIfCreated();
if (m_bIsBaked)
{
throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody);
}
if (il.m_methodBuilder != this && il.m_methodBuilder != null)
{
// you don't need to call DefineBody when you get your ILGenerator
// through MethodBuilder::GetILGenerator.
//
throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage);
}
ThrowIfShouldNotHaveBody();
if (il.m_ScopeTree.m_iOpenScopeCount != 0)
{
// There are still unclosed local scope
throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope);
}
m_ubBody = il.BakeByteArray();
m_mdMethodFixups = il.GetTokenFixups();
//Okay, now the fun part. Calculate all of the exceptions.
excp = il.GetExceptions();
int numExceptions = CalculateNumberOfExceptions(excp);
if (numExceptions > 0)
{
m_exceptions = new ExceptionHandler[numExceptions];
for (int i = 0; i < excp.Length; i++)
{
filterAddrs = excp[i].GetFilterAddresses();
catchAddrs = excp[i].GetCatchAddresses();
catchEndAddrs = excp[i].GetCatchEndAddresses();
catchClass = excp[i].GetCatchClass();
numCatch = excp[i].GetNumberOfCatches();
start = excp[i].GetStartAddress();
end = excp[i].GetEndAddress();
type = excp[i].GetExceptionTypes();
for (int j = 0; j < numCatch; j++)
{
int tkExceptionClass = 0;
if (catchClass[j] != null)
{
tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token;
}
switch (type[j])
{
case __ExceptionInfo.None:
case __ExceptionInfo.Fault:
case __ExceptionInfo.Filter:
m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
break;
case __ExceptionInfo.Finally:
m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass);
break;
}
}
}
}
m_bIsBaked = true;
if (dynMod.GetSymWriter() != null)
{
// set the debugging information such as scope and line number
// if it is in a debug module
//
SymbolToken tk = new SymbolToken(MetadataTokenInternal);
ISymbolWriter symWriter = dynMod.GetSymWriter();
// call OpenMethod to make this method the current method
symWriter.OpenMethod(tk);
// call OpenScope because OpenMethod no longer implicitly creating
// the top-levelsmethod scope
//
symWriter.OpenScope(0);
if (m_symCustomAttrs != null)
{
foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs)
dynMod.GetSymWriter().SetSymAttribute(
new SymbolToken(MetadataTokenInternal),
symCustomAttr.m_name,
symCustomAttr.m_data);
}
if (m_localSymInfo != null)
m_localSymInfo.EmitLocalSymInfo(symWriter);
il.m_ScopeTree.EmitScopeTree(symWriter);
il.m_LineNumberInfo.EmitLineNumberInfo(symWriter);
symWriter.CloseScope(il.ILOffset);
symWriter.CloseMethod();
}
}
// This is only called from TypeBuilder.CreateType after the method has been created
internal void ReleaseBakedStructures()
{
if (!m_bIsBaked)
{
// We don't need to do anything here if we didn't baked the method body
return;
}
m_ubBody = null;
m_localSymInfo = null;
m_mdMethodFixups = null;
m_localSignature = null;
m_exceptions = null;
}
internal override Type[] GetParameterTypes()
{
if (m_parameterTypes == null)
m_parameterTypes = Array.Empty<Type>();
return m_parameterTypes;
}
internal static Type GetMethodBaseReturnType(MethodBase method)
{
MethodInfo mi = null;
ConstructorInfo ci = null;
if ((mi = method as MethodInfo) != null)
{
return mi.ReturnType;
}
else if ((ci = method as ConstructorInfo) != null)
{
return ci.GetReturnType();
}
else
{
Debug.Fail("We should never get here!");
return null;
}
}
internal byte[] GetBody()
{
// Returns the il bytes of this method.
// This il is not valid until somebody has called BakeByteArray
return m_ubBody;
}
internal int[] GetTokenFixups()
{
return m_mdMethodFixups;
}
internal SignatureHelper GetMethodSignature()
{
if (m_parameterTypes == null)
m_parameterTypes = Array.Empty<Type>();
m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0,
m_returnType == null ? typeof(void) : m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers,
m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers);
return m_signature;
}
// Returns a buffer whose initial signatureLength bytes contain encoded local signature.
internal byte[] GetLocalSignature(out int signatureLength)
{
if (m_localSignature != null)
{
signatureLength = m_localSignature.Length;
return m_localSignature;
}
if (m_ilGenerator != null)
{
if (m_ilGenerator.m_localCount != 0)
{
// If user is using ILGenerator::DeclareLocal, then get local signaturefrom there.
return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength);
}
}
return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength);
}
internal int GetMaxStack()
{
if (m_ilGenerator != null)
{
return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount;
}
else
{
// this is the case when client provide an array of IL byte stream rather than going through ILGenerator.
return m_maxStack;
}
}
internal ExceptionHandler[] GetExceptionHandlers()
{
return m_exceptions;
}
internal int ExceptionHandlerCount
{
get { return m_exceptions != null ? m_exceptions.Length : 0; }
}
internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
{
int num = 0;
if (excp == null)
{
return 0;
}
for (int i = 0; i < excp.Length; i++)
{
num += excp[i].GetNumberOfCatches();
}
return num;
}
internal bool IsTypeCreated()
{
return (m_containingType != null && m_containingType.IsCreated());
}
internal TypeBuilder GetTypeBuilder()
{
return m_containingType;
}
internal ModuleBuilder GetModuleBuilder()
{
return m_module;
}
#endregion
#region Object Overrides
public override bool Equals(Object obj)
{
if (!(obj is MethodBuilder))
{
return false;
}
if (!(this.m_strName.Equals(((MethodBuilder)obj).m_strName)))
{
return false;
}
if (m_iAttributes != (((MethodBuilder)obj).m_iAttributes))
{
return false;
}
SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature();
if (thatSig.Equals(GetMethodSignature()))
{
return true;
}
return false;
}
public override int GetHashCode()
{
return this.m_strName.GetHashCode();
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(1000);
sb.Append("Name: " + m_strName + " " + Environment.NewLine);
sb.Append("Attributes: " + (int)m_iAttributes + Environment.NewLine);
sb.Append("Method Signature: " + GetMethodSignature() + Environment.NewLine);
sb.Append(Environment.NewLine);
return sb.ToString();
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get
{
return m_strName;
}
}
internal int MetadataTokenInternal
{
get
{
return GetToken().Token;
}
}
public override Module Module
{
get
{
return m_containingType.Module;
}
}
public override Type DeclaringType
{
get
{
if (m_containingType.m_isHiddenGlobalType == true)
return null;
return m_containingType;
}
}
public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
get
{
return null;
}
}
public override Type ReflectedType
{
get
{
return DeclaringType;
}
}
#endregion
#region MethodBase Overrides
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return m_dwMethodImplFlags;
}
public override MethodAttributes Attributes
{
get { return m_iAttributes; }
}
public override CallingConventions CallingConvention
{
get { return m_callingConvention; }
}
public override RuntimeMethodHandle MethodHandle
{
get { throw new NotSupportedException(SR.NotSupported_DynamicModule); }
}
public override bool IsSecurityCritical
{
get { return true; }
}
public override bool IsSecuritySafeCritical
{
get { return false; }
}
public override bool IsSecurityTransparent
{
get { return false; }
}
#endregion
#region MethodInfo Overrides
public override MethodInfo GetBaseDefinition()
{
return this;
}
public override Type ReturnType
{
get
{
return m_returnType;
}
}
public override ParameterInfo[] GetParameters()
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated);
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes);
return rmi.GetParameters();
}
public override ParameterInfo ReturnParameter
{
get
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated);
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes);
return rmi.ReturnParameter;
}
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
#endregion
#region Generic Members
public override bool IsGenericMethodDefinition { get { return m_bIsGenMethDef; } }
public override bool ContainsGenericParameters { get { throw new NotSupportedException(); } }
public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; }
public override bool IsGenericMethod { get { return m_inst != null; } }
public override Type[] GetGenericArguments() { return m_inst; }
public override MethodInfo MakeGenericMethod(params Type[] typeArguments)
{
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments);
}
public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names)
{
if (names == null)
throw new ArgumentNullException(nameof(names));
if (names.Length == 0)
throw new ArgumentException(SR.Arg_EmptyArray, nameof(names));
if (m_inst != null)
throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet);
for (int i = 0; i < names.Length; i++)
if (names[i] == null)
throw new ArgumentNullException(nameof(names));
if (m_tkMethod.Token != 0)
throw new InvalidOperationException(SR.InvalidOperation_MethodBuilderBaked);
m_bIsGenMethDef = true;
m_inst = new GenericTypeParameterBuilder[names.Length];
for (int i = 0; i < names.Length; i++)
m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this));
return m_inst;
}
internal void ThrowIfGeneric() { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException(); }
#endregion
#region Public Members
public MethodToken GetToken()
{
// We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498
// we only "tokenize" a method when requested. But the order in which the methods are tokenized
// didn't change: the same order the MethodBuilders are constructed. The recursion introduced
// will overflow the stack when there are many methods on the same type (10000 in my experiment).
// The change also introduced race conditions. Before the code change GetToken is called from
// the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it
// could be called more than once on the the same method introducing duplicate (invalid) tokens.
// I don't fully understand this change. So I will keep the logic and only fix the recursion and
// the race condition.
if (m_tkMethod.Token != 0)
{
return m_tkMethod;
}
MethodBuilder currentMethod = null;
MethodToken currentToken = new MethodToken(0);
int i;
// We need to lock here to prevent a method from being "tokenized" twice.
// We don't need to synchronize this with Type.DefineMethod because it only appends newly
// constructed MethodBuilders to the end of m_listMethods
lock (m_containingType.m_listMethods)
{
if (m_tkMethod.Token != 0)
{
return m_tkMethod;
}
// If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller
// than the index of the current method.
for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i)
{
currentMethod = m_containingType.m_listMethods[i];
currentToken = currentMethod.GetTokenNoLock();
if (currentMethod == this)
break;
}
m_containingType.m_lastTokenizedMethod = i;
}
Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods");
Debug.Assert(currentToken.Token != 0, "The token should not be 0");
return currentToken;
}
private MethodToken GetTokenNoLock()
{
Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized");
int sigLength;
byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength);
int token = TypeBuilder.DefineMethod(m_module.GetNativeHandle(), m_containingType.MetadataTokenInternal, m_strName, sigBytes, sigLength, Attributes);
m_tkMethod = new MethodToken(token);
if (m_inst != null)
foreach (GenericTypeParameterBuilder tb in m_inst)
if (!tb.m_type.IsCreated()) tb.m_type.CreateType();
TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), token, m_dwMethodImplFlags);
return m_tkMethod;
}
public void SetParameters(params Type[] parameterTypes)
{
CheckContext(parameterTypes);
SetSignature(null, null, null, parameterTypes, null, null);
}
public void SetReturnType(Type returnType)
{
CheckContext(returnType);
SetSignature(returnType, null, null, null, null, null);
}
public void SetSignature(
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
{
// We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked.
// But we cannot because that would be a breaking change from V2.
if (m_tkMethod.Token != 0)
return;
CheckContext(returnType);
CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
CheckContext(parameterTypeRequiredCustomModifiers);
CheckContext(parameterTypeOptionalCustomModifiers);
ThrowIfGeneric();
if (returnType != null)
{
m_returnType = returnType;
}
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length);
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers;
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
}
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName)
{
if (position < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
ThrowIfGeneric();
m_containingType.ThrowIfCreated();
if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length))
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
attributes = attributes & ~ParameterAttributes.ReservedMask;
return new ParameterBuilder(this, position, attributes, strParamName);
}
private List<SymCustomAttr> m_symCustomAttrs;
private struct SymCustomAttr
{
public String m_name;
public byte[] m_data;
}
public void SetImplementationFlags(MethodImplAttributes attributes)
{
ThrowIfGeneric();
m_containingType.ThrowIfCreated();
m_dwMethodImplFlags = attributes;
m_canBeRuntimeImpl = true;
TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), MetadataTokenInternal, attributes);
}
public ILGenerator GetILGenerator()
{
ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
if (m_ilGenerator == null)
m_ilGenerator = new ILGenerator(this);
return m_ilGenerator;
}
public ILGenerator GetILGenerator(int size)
{
ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
if (m_ilGenerator == null)
m_ilGenerator = new ILGenerator(this, size);
return m_ilGenerator;
}
private void ThrowIfShouldNotHaveBody()
{
if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL ||
(m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 ||
(m_iAttributes & MethodAttributes.PinvokeImpl) != 0 ||
m_isDllImport)
{
// cannot attach method body if methodimpl is marked not marked as managed IL
//
throw new InvalidOperationException(SR.InvalidOperation_ShouldNotHaveMethodBody);
}
}
public bool InitLocals
{
// Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false.
get { ThrowIfGeneric(); return m_fInitLocals; }
set { ThrowIfGeneric(); m_fInitLocals = value; }
}
public Module GetModule()
{
return GetModuleBuilder();
}
public String Signature
{
get
{
return GetMethodSignature().ToString();
}
}
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
ThrowIfGeneric();
TypeBuilder.DefineCustomAttribute(m_module, MetadataTokenInternal,
((ModuleBuilder)m_module).GetConstructorToken(con).Token,
binaryAttribute,
false, false);
if (IsKnownCA(con))
ParseCA(con, binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
throw new ArgumentNullException(nameof(customBuilder));
ThrowIfGeneric();
customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataTokenInternal);
if (IsKnownCA(customBuilder.m_con))
ParseCA(customBuilder.m_con, customBuilder.m_blob);
}
// this method should return true for any and every ca that requires more work
// than just setting the ca
private bool IsKnownCA(ConstructorInfo con)
{
Type caType = con.DeclaringType;
if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) return true;
else if (caType == typeof(DllImportAttribute)) return true;
else return false;
}
private void ParseCA(ConstructorInfo con, byte[] blob)
{
Type caType = con.DeclaringType;
if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute))
{
// dig through the blob looking for the MethodImplAttributes flag
// that must be in the MethodCodeType field
// for now we simply set a flag that relaxes the check when saving and
// allows this method to have no body when any kind of MethodImplAttribute is present
m_canBeRuntimeImpl = true;
}
else if (caType == typeof(DllImportAttribute))
{
m_canBeRuntimeImpl = true;
m_isDllImport = true;
}
}
internal bool m_canBeRuntimeImpl = false;
internal bool m_isDllImport = false;
#endregion
}
internal class LocalSymInfo
{
// This class tracks the local variable's debugging information
// and namespace information with a given active lexical scope.
#region Internal Data Members
internal String[] m_strName;
internal byte[][] m_ubSignature;
internal int[] m_iLocalSlot;
internal int[] m_iStartOffset;
internal int[] m_iEndOffset;
internal int m_iLocalSymCount; // how many entries in the arrays are occupied
internal String[] m_namespace;
internal int m_iNameSpaceCount;
internal const int InitialSize = 16;
#endregion
#region Constructor
internal LocalSymInfo()
{
// initialize data variables
m_iLocalSymCount = 0;
m_iNameSpaceCount = 0;
}
#endregion
#region Private Members
private void EnsureCapacityNamespace()
{
if (m_iNameSpaceCount == 0)
{
m_namespace = new String[InitialSize];
}
else if (m_iNameSpaceCount == m_namespace.Length)
{
String[] strTemp = new String[checked(m_iNameSpaceCount * 2)];
Array.Copy(m_namespace, 0, strTemp, 0, m_iNameSpaceCount);
m_namespace = strTemp;
}
}
private void EnsureCapacity()
{
if (m_iLocalSymCount == 0)
{
// First time. Allocate the arrays.
m_strName = new String[InitialSize];
m_ubSignature = new byte[InitialSize][];
m_iLocalSlot = new int[InitialSize];
m_iStartOffset = new int[InitialSize];
m_iEndOffset = new int[InitialSize];
}
else if (m_iLocalSymCount == m_strName.Length)
{
// the arrays are full. Enlarge the arrays
// why aren't we just using lists here?
int newSize = checked(m_iLocalSymCount * 2);
int[] temp = new int[newSize];
Array.Copy(m_iLocalSlot, 0, temp, 0, m_iLocalSymCount);
m_iLocalSlot = temp;
temp = new int[newSize];
Array.Copy(m_iStartOffset, 0, temp, 0, m_iLocalSymCount);
m_iStartOffset = temp;
temp = new int[newSize];
Array.Copy(m_iEndOffset, 0, temp, 0, m_iLocalSymCount);
m_iEndOffset = temp;
String[] strTemp = new String[newSize];
Array.Copy(m_strName, 0, strTemp, 0, m_iLocalSymCount);
m_strName = strTemp;
byte[][] ubTemp = new byte[newSize][];
Array.Copy(m_ubSignature, 0, ubTemp, 0, m_iLocalSymCount);
m_ubSignature = ubTemp;
}
}
#endregion
#region Internal Members
internal void AddLocalSymInfo(String strName, byte[] signature, int slot, int startOffset, int endOffset)
{
// make sure that arrays are large enough to hold addition info
EnsureCapacity();
m_iStartOffset[m_iLocalSymCount] = startOffset;
m_iEndOffset[m_iLocalSymCount] = endOffset;
m_iLocalSlot[m_iLocalSymCount] = slot;
m_strName[m_iLocalSymCount] = strName;
m_ubSignature[m_iLocalSymCount] = signature;
checked { m_iLocalSymCount++; }
}
internal void AddUsingNamespace(String strNamespace)
{
EnsureCapacityNamespace();
m_namespace[m_iNameSpaceCount] = strNamespace;
checked { m_iNameSpaceCount++; }
}
internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter)
{
int i;
for (i = 0; i < m_iLocalSymCount; i++)
{
symWriter.DefineLocalVariable(
m_strName[i],
FieldAttributes.PrivateScope,
m_ubSignature[i],
SymAddressKind.ILOffset,
m_iLocalSlot[i],
0, // addr2 is not used yet
0, // addr3 is not used
m_iStartOffset[i],
m_iEndOffset[i]);
}
for (i = 0; i < m_iNameSpaceCount; i++)
{
symWriter.UsingNamespace(m_namespace[i]);
}
}
#endregion
}
/// <summary>
/// Describes exception handler in a method body.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal readonly struct ExceptionHandler : IEquatable<ExceptionHandler>
{
// Keep in sync with unmanged structure.
internal readonly int m_exceptionClass;
internal readonly int m_tryStartOffset;
internal readonly int m_tryEndOffset;
internal readonly int m_filterOffset;
internal readonly int m_handlerStartOffset;
internal readonly int m_handlerEndOffset;
internal readonly ExceptionHandlingClauseOptions m_kind;
#region Constructors
internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset,
int kind, int exceptionTypeToken)
{
Debug.Assert(tryStartOffset >= 0);
Debug.Assert(tryEndOffset >= 0);
Debug.Assert(filterOffset >= 0);
Debug.Assert(handlerStartOffset >= 0);
Debug.Assert(handlerEndOffset >= 0);
Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind));
Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0);
m_tryStartOffset = tryStartOffset;
m_tryEndOffset = tryEndOffset;
m_filterOffset = filterOffset;
m_handlerStartOffset = handlerStartOffset;
m_handlerEndOffset = handlerEndOffset;
m_kind = (ExceptionHandlingClauseOptions)kind;
m_exceptionClass = exceptionTypeToken;
}
private static bool IsValidKind(ExceptionHandlingClauseOptions kind)
{
switch (kind)
{
case ExceptionHandlingClauseOptions.Clause:
case ExceptionHandlingClauseOptions.Filter:
case ExceptionHandlingClauseOptions.Finally:
case ExceptionHandlingClauseOptions.Fault:
return true;
default:
return false;
}
}
#endregion
#region Equality
public override int GetHashCode()
{
return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind;
}
public override bool Equals(Object obj)
{
return obj is ExceptionHandler && Equals((ExceptionHandler)obj);
}
public bool Equals(ExceptionHandler other)
{
return
other.m_exceptionClass == m_exceptionClass &&
other.m_tryStartOffset == m_tryStartOffset &&
other.m_tryEndOffset == m_tryEndOffset &&
other.m_filterOffset == m_filterOffset &&
other.m_handlerStartOffset == m_handlerStartOffset &&
other.m_handlerEndOffset == m_handlerEndOffset &&
other.m_kind == m_kind;
}
public static bool operator ==(ExceptionHandler left, ExceptionHandler right)
{
return left.Equals(right);
}
public static bool operator !=(ExceptionHandler left, ExceptionHandler right)
{
return !left.Equals(right);
}
#endregion
}
}
| |
/*
* MindTouch DekiScript - embeddable web-oriented scripting runtime
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using log4net;
using MindTouch.Deki.Script.Compiler;
using MindTouch.Deki.Script.Expr;
using MindTouch.Deki.Script.Runtime;
using MindTouch.Deki.Script.Runtime.Library;
using MindTouch.Deki.Script.Runtime.TargetInvocation;
using MindTouch.Dream;
using MindTouch.Tasking;
using MindTouch.Xml;
namespace MindTouch.Deki.Script {
using Yield = IEnumerator<IYield>;
public class DekiScriptRuntime {
//--- Constants ---
public const string DEFAULT_ID = "$";
public const string ARGS_ID = "args";
public const string ENV_ID = "__env";
public const string COUNT_ID = "__count";
public const string INDEX_ID = "__index";
public const string ON_SAVE_PATTERN = "save:";
public const string ON_SUBST_PATTERN = "subst:";
public const string ON_EDIT_PATTERN = "edit:";
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
private static readonly DekiScriptList _emptyList = new DekiScriptList();
private static readonly Dictionary<XUri, DekiScriptInvocationTargetDescriptor> _commonFunctions;
private static readonly DekiScriptEnv _commonEnv;
//--- Class Constructor ---
static DekiScriptRuntime() {
// register built-in functions
_commonFunctions = new Dictionary<XUri, DekiScriptInvocationTargetDescriptor>();
foreach(MethodInfo method in typeof(DekiScriptLibrary).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy)) {
// check if it has the DekiScriptFunction attribute
DekiScriptFunctionAttribute functionAttribute = (DekiScriptFunctionAttribute)Attribute.GetCustomAttribute(method, typeof(DekiScriptFunctionAttribute));
if(functionAttribute != null) {
var parameters = from param in method.GetParameters()
let attr = (DekiScriptParamAttribute[])param.GetCustomAttributes(typeof(DekiScriptParamAttribute), false)
select ((attr != null) && (attr.Length > 0)) ? new DekiScriptNativeInvocationTarget.Parameter(attr[0].Hint, attr[0].Optional) : null;
var target = new DekiScriptNativeInvocationTarget(null, method, parameters.ToArray());
var function = new DekiScriptInvocationTargetDescriptor(target.Access, functionAttribute.IsProperty, functionAttribute.IsIdempotent, functionAttribute.Name ?? method.Name, target.Parameters, target.ReturnType, functionAttribute.Description, functionAttribute.Transform, target);
_commonFunctions[new XUri("native:///").At(function.SystemName)] = function;
}
}
// build common env
DekiScriptMap common = new DekiScriptMap();
// add global constants
common.AddNativeValueAt("num.e", Math.E);
common.AddNativeValueAt("num.pi", Math.PI);
common.AddNativeValueAt("num.epsilon", double.Epsilon);
common.AddNativeValueAt("num.positiveinfinity", double.PositiveInfinity);
common.AddNativeValueAt("num.negativeinfinity", double.NegativeInfinity);
common.AddNativeValueAt("num.nan", double.NaN);
// add global functions & properties
foreach(var function in _commonFunctions) {
common.AddNativeValueAt(function.Value.Name, function.Key);
}
_commonEnv = new DekiScriptEnv(common);
}
//--- Class Methods ---
public static bool IsProperty(DekiScriptLiteral value) {
if(value.ScriptType == DekiScriptType.URI) {
return (((DekiScriptUri)value).Value.LastSegment ?? string.Empty).StartsWithInvariant("$");
}
return false;
}
public static Exception UnwrapAsyncException(XUri uri, Exception exception) {
// unroll target and async invocation exceptions
while(((exception is TargetInvocationException)) && (exception.InnerException != null)) {
exception = exception.InnerException;
}
return exception;
}
internal static XDoc CreateWarningFromException(DekiScriptList callstack, Location location, Exception exception) {
// unwrap nested async exception
exception = UnwrapAsyncException(null, exception);
// determine exception
XDoc result;
if(exception is DreamAbortException) {
DreamAbortException e = (DreamAbortException)exception;
if(e.Response.ContentType.IsXml) {
result = CreateWarningElement(callstack, string.Format("{1}, a web exception was thrown (status: {0})", (int)e.Response.Status, location), new XMessage(e.Response).ToPrettyString());
} else {
result = CreateWarningElement(callstack, string.Format("{1}, a web exception was thrown (status: {0})", (int)e.Response.Status, location), e.Response.AsText());
}
} else if(exception is DekiScriptException) {
result = CreateWarningElement(callstack, exception.Message, exception.GetCoroutineStackTrace());
} else {
result = CreateWarningElement(callstack, string.Format("{0}: {1}", exception.Message, location), exception.GetCoroutineStackTrace());
}
return result;
}
public static XDoc CreateWarningElement(DekiScriptList callstack, String description, string message) {
if(callstack != null) {
StringBuilder stacktrace = new StringBuilder();
foreach(var entry in from item in callstack.Value let entry = item.AsString() where entry != null select entry) {
stacktrace.AppendFormat(" at {0}\n", entry);
}
if(stacktrace.Length > 0) {
if(message == null) {
message = "Callstack:\n" + stacktrace;
} else {
message = "Callstack:\n" + stacktrace + "\n" + message;
}
}
}
XDoc result = new XDoc("div");
result.Start("span").Attr("class", "warning").Value(description).End();
if(message != null) {
string id = StringUtil.CreateAlphaNumericKey(8);
result.Value(" ");
result.Start("span").Attr("style", "cursor: pointer;").Attr("onclick", string.Format("$('#{0}').toggle()", id)).Value("(click for details)").End();
result.Start("pre").Attr("id", id).Attr("style", "display: none;").Value(message).End();
}
return result;
}
//--- Fields ---
private readonly Dictionary<XUri, DekiScriptInvocationTargetDescriptor> _functions;
//--- Constructors ---
public DekiScriptRuntime() {
_functions = new Dictionary<XUri, DekiScriptInvocationTargetDescriptor>(_commonFunctions);
}
//--- Properties ---
public Dictionary<XUri, DekiScriptInvocationTargetDescriptor> Functions { get { return _functions; } }
//--- Methdos ---
public virtual void RegisterExtensionFunctions(Dictionary<XUri, DekiScriptInvocationTargetDescriptor> functions) {
lock(_functions) {
foreach(var entry in functions) {
_functions[entry.Key] = entry.Value;
}
}
}
public virtual DekiScriptInvocationTargetDescriptor ResolveRegisteredFunctionUri(XUri uri) {
DekiScriptInvocationTargetDescriptor descriptor;
// check registered functions
if(_functions.TryGetValue(uri, out descriptor)) {
return descriptor;
}
return null;
}
public virtual DekiScriptEnv CreateEnv() {
return _commonEnv.NewScope();
}
public virtual DekiScriptLiteral Evaluate(DekiScriptExpression expr, DekiScriptEvalMode mode, DekiScriptEnv env) {
DekiScriptExpressionEvaluationState state = new DekiScriptExpressionEvaluationState(mode, env, this);
try {
return state.Pop(expr.VisitWith(DekiScriptExpressionEvaluation.Instance, state));
} catch(DekiScriptReturnException e) {
state.Push(e.Value);
return state.PopAll();
}
}
public virtual DekiScriptLiteral EvaluateProperty(Location location, DekiScriptLiteral value, DekiScriptEnv env) {
if(IsProperty(value)) {
DekiScriptUri uri = (DekiScriptUri)value;
try {
value = Invoke(uri.Value, uri.Arguments.IsNil ? _emptyList : uri.Arguments, env);
} catch(DekiScriptFatalException) {
throw;
} catch(Exception e) {
var descriptor = ResolveRegisteredFunctionUri(uri.Value);
throw new DekiScriptInvokeException(location, uri.Value, (descriptor != null) ? descriptor.Name : uri.Value.ToString(), e);
}
}
return value;
}
public virtual DekiScriptLiteral Invoke(XUri uri, DekiScriptLiteral args, DekiScriptEnv env) {
DekiScriptInvocationTargetDescriptor descriptor;
var target = _functions.TryGetValue(uri, out descriptor) ? descriptor.Target : FindTarget(uri);
// invoke function directly
try {
return target.Invoke(this, args);
} catch(Exception e) {
throw UnwrapAsyncException(uri, e).Rethrow();
}
}
public virtual Plug PreparePlug(Plug plug) {
return plug;
}
public virtual DekiScriptLiteral ResolveMissingName(string name) {
return null;
}
protected virtual IDekiScriptInvocationTarget FindTarget(XUri uri) {
string last_segment = uri.LastSegment ?? string.Empty;
if(last_segment.EndsWithInvariant(".rpc")) {
string methodName = last_segment.Substring(0, last_segment.Length - 4);
return new DekiScriptXmlRpcInvocationTarget(uri.WithoutLastSegment(), methodName);
}
if(last_segment.EndsWithInvariant(".jsp")) {
return new DekiScriptHttpGetInvocationTarget(uri);
}
return new DekiScriptRemoteInvocationTarget(uri);
}
}
}
| |
// 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.Text.Utf8;
namespace Json.Net.Tests
{
public struct JsonReader : IDisposable
{
private Utf8String _str;
private int _index;
private int _insideObject;
private int _insideArray;
public JsonTokenType TokenType;
private bool _jsonStartIsObject;
public enum JsonTokenType
{
// Start = 0 state reserved for internal use
ObjectStart = 1,
ObjectEnd = 2,
ArrayStart = 3,
ArrayEnd = 4,
Property = 5,
Value = 6
};
public enum JsonValueType
{
String,
Number,
Object,
Array,
True,
False,
Null
}
public JsonReader(Utf8String str)
{
_str = str.Trim();
_index = 0;
_insideObject = 0;
_insideArray = 0;
TokenType = 0;
_jsonStartIsObject = (byte)_str[0] == '{';
}
public JsonReader(string str)
{
_str = new Utf8String(str).Trim();
_index = 0;
_insideObject = 0;
_insideArray = 0;
TokenType = 0;
_jsonStartIsObject = (byte)_str[0] == '{';
}
public void Dispose()
{
}
public bool Read()
{
var canRead = _index < _str.Length;
if (canRead) MoveToNextTokenType();
return canRead;
}
public Utf8String GetName()
{
SkipEmpty();
var str = ReadStringValue();
_index++;
return str;
}
public JsonDb.JsonValueType GetJsonDb.JsonValueType()
{
var nextByte = (byte)_str[_index];
while (Utf8String.IsWhiteSpace(nextByte))
{
_index++;
nextByte = (byte)_str[_index];
}
if (nextByte == '"')
{
return JsonDb.JsonValueType.String;
}
if (nextByte == '{')
{
return JsonDb.JsonValueType.Object;
}
if (nextByte == '[')
{
return JsonDb.JsonValueType.Array;
}
if (nextByte == 't')
{
return JsonDb.JsonValueType.True;
}
if (nextByte == 'f')
{
return JsonDb.JsonValueType.False;
}
if (nextByte == 'n')
{
return JsonDb.JsonValueType.Null;
}
if (nextByte == '-' || (nextByte >= '0' && nextByte <= '9'))
{
return JsonDb.JsonValueType.Number;
}
throw new FormatException("Invalid json, tried to read char '" + nextByte + "'.");
}
public Utf8String GetValue()
{
var type = GetJsonDb.JsonValueType();
SkipEmpty();
switch (type)
{
case JsonDb.JsonValueType.String:
return ReadStringValue();
case JsonDb.JsonValueType.Number:
return ReadNumberValue();
case JsonDb.JsonValueType.True:
return ReadTrueValue();
case JsonDb.JsonValueType.False:
return ReadFalseValue();
case JsonDb.JsonValueType.Null:
return ReadNullValue();
case JsonDb.JsonValueType.Object:
case JsonDb.JsonValueType.Array:
return Utf8String.Empty;
default:
throw new ArgumentException("Invalid json value type '" + type + "'.");
}
}
private Utf8String ReadStringValue()
{
_index++;
var count = _index;
do
{
while ((byte)_str[count] != '"')
{
count++;
}
count++;
} while (AreNumOfBackSlashesAtEndOfStringOdd(count - 2));
var strLength = count - _index;
var resultString = _str.Substring(_index, strLength - 1);
_index += strLength;
SkipEmpty();
return resultString;
}
private bool AreNumOfBackSlashesAtEndOfStringOdd(int count)
{
var length = count - _index;
if (length < 0) return false;
var nextByte = (byte)_str[count];
if (nextByte != '\\') return false;
var numOfBackSlashes = 0;
while (nextByte == '\\')
{
numOfBackSlashes++;
if ((length - numOfBackSlashes) < 0) return numOfBackSlashes % 2 != 0;
nextByte = (byte)_str[count - numOfBackSlashes];
}
return numOfBackSlashes % 2 != 0;
}
private Utf8String ReadNumberValue()
{
var count = _index;
var nextByte = (byte)_str[count];
if (nextByte == '-')
{
count++;
}
nextByte = (byte)_str[count];
while (nextByte >= '0' && nextByte <= '9')
{
count++;
nextByte = (byte)_str[count];
}
if (nextByte == '.')
{
count++;
}
nextByte = (byte)_str[count];
while (nextByte >= '0' && nextByte <= '9')
{
count++;
nextByte = (byte)_str[count];
}
if (nextByte == 'e' || nextByte == 'E')
{
count++;
nextByte = (byte)_str[count];
if (nextByte == '-' || nextByte == '+')
{
count++;
}
nextByte = (byte)_str[count];
while (nextByte >= '0' && nextByte <= '9')
{
count++;
nextByte = (byte)_str[count];
}
}
var length = count - _index;
var resultStr = _str.Substring(_index, count - _index);
_index += length;
SkipEmpty();
return resultStr;
}
private Utf8String ReadTrueValue()
{
var trueString = _str.Substring(_index, 4);
if ((byte)trueString[1] != 'r' || (byte)trueString[2] != 'u' || (byte)trueString[3] != 'e')
{
throw new FormatException("Invalid json, tried to read 'true'.");
}
_index += 4;
SkipEmpty();
return trueString;
}
private Utf8String ReadFalseValue()
{
var falseString = _str.Substring(_index, 5);
if ((byte)falseString[1] != 'a' || (byte)falseString[2] != 'l' || (byte)falseString[3] != 's' || (byte)falseString[4] != 'e')
{
throw new FormatException("Invalid json, tried to read 'false'.");
}
_index += 5;
SkipEmpty();
return falseString;
}
private Utf8String ReadNullValue()
{
var nullString = _str.Substring(_index, 4);
if ((byte)nullString[1] != 'u' || (byte)nullString[2] != 'l' || (byte)nullString[3] != 'l')
{
throw new FormatException("Invalid json, tried to read 'null'.");
}
_index += 4;
SkipEmpty();
return nullString;
}
private void SkipEmpty()
{
var nextByte = (byte)_str[_index];
while (Utf8String.IsWhiteSpace(nextByte))
{
_index++;
nextByte = (byte)_str[_index];
}
}
private void MoveToNextTokenType()
{
var nextByte = (byte)_str[_index];
while (Utf8String.IsWhiteSpace(nextByte))
{
_index++;
nextByte = (byte)_str[_index];
}
switch (TokenType)
{
case JsonTokenType.ObjectStart:
if (nextByte != '}')
{
TokenType = JsonTokenType.Property;
return;
}
break;
case JsonTokenType.ObjectEnd:
if (nextByte == ',')
{
_index++;
if (_insideObject == _insideArray)
{
TokenType = !_jsonStartIsObject ? JsonTokenType.Property : JsonTokenType.Value;
return;
}
TokenType = _insideObject > _insideArray ? JsonTokenType.Property : JsonTokenType.Value;
return;
}
break;
case JsonTokenType.ArrayStart:
if (nextByte != ']')
{
TokenType = JsonTokenType.Value;
return;
}
break;
case JsonTokenType.ArrayEnd:
if (nextByte == ',')
{
_index++;
if (_insideObject == _insideArray)
{
TokenType = !_jsonStartIsObject ? JsonTokenType.Property : JsonTokenType.Value;
return;
}
TokenType = _insideObject > _insideArray ? JsonTokenType.Property : JsonTokenType.Value;
return;
}
break;
case JsonTokenType.Property:
if (nextByte == ',')
{
_index++;
return;
}
break;
case JsonTokenType.Value:
if (nextByte == ',')
{
_index++;
return;
}
break;
}
_index++;
switch (nextByte)
{
case (byte)'{':
_insideObject++;
TokenType = JsonTokenType.ObjectStart;
return;
case (byte)'}':
_insideObject--;
TokenType = JsonTokenType.ObjectEnd;
return;
case (byte)'[':
_insideArray++;
TokenType = JsonTokenType.ArrayStart;
return;
case (byte)']':
_insideArray--;
TokenType = JsonTokenType.ArrayEnd;
return;
default:
throw new FormatException("Unable to get next token type. Check json format.");
}
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using Its.Log.Instrumentation.Extensions;
using NUnit.Framework;
using Moq;
using Assert = NUnit.Framework.Assert;
namespace Its.Log.Instrumentation.UnitTests
{
[TestFixture]
public class LogEventsTests
{
[SetUp]
[TearDown]
public void SetUpAndTearDown()
{
Extension.EnableAll();
Log.Formatters.Clear();
Log.UnsubscribeAllFromEntryPosted();
}
[Test]
public virtual void Log_Enter_using_block_generates_one_start_and_one_stop_event()
{
var log = new List<LogEntry>();
using (Log.Events().Subscribe(log.Add))
using (Log.Enter(() => { }))
{
}
Assert.That(log[0].EventType, Is.EqualTo(TraceEventType.Start));
Assert.That(log[1].EventType, Is.EqualTo(TraceEventType.Stop));
}
[Test]
public virtual void Multiple_subscribed_observers_receive_updates()
{
var observer1 = new Mock<IObserver<LogEntry>>();
var observer2 = new Mock<IObserver<LogEntry>>();
using (observer1.Object.SubscribeToLogEvents())
using (observer2.Object.SubscribeToLogEvents())
{
Log.Write("Test");
}
observer1.Verify(
o => o.OnNext(It.IsAny<LogEntry>()),
Times.Once());
observer2.Verify(
o => o.OnNext(It.IsAny<LogEntry>()),
Times.Once());
}
[Test]
public virtual void Observer_can_be_safely_unsubscribed_more_times_than_it_was_subscribed()
{
var observer = new Mock<IObserver<LogEntry>>();
var subscription = observer.Object.SubscribeToLogEvents();
subscription.Dispose();
subscription.Dispose();
}
[Test]
public virtual void Subscribed_observer_receives_updates()
{
var observer = new Mock<IObserver<LogEntry>>();
using (observer.Object.SubscribeToLogEvents())
{
Log.Write("test");
}
observer.Verify(
o => o.OnNext(It.IsAny<LogEntry>()),
Times.Once());
}
[Test]
public virtual void When_error_events_observer_throws_no_exception_is_thrown_to_Log_Write()
{
var badObserver = new Mock<IObserver<LogEntry>>();
badObserver
.Setup(o => o.OnNext(It.IsAny<LogEntry>()))
.Throws(new Exception("This is a test exception"));
using (badObserver.Object.SubscribeToLogEvents())
using (badObserver.Object.SubscribeToLogInternalErrors())
{
Log.Write("hello");
}
}
[Test]
public virtual void When_extension_property_throws_then_no_exception_bubbles_up_to_caller_and_error_event_is_published()
{
Log.Formatters.RegisterPropertiesFormatter<LogEntry>(e => e.Extensions);
var logObserver = new Mock<IObserver<LogEntry>>();
logObserver
.Setup(o => o.OnNext(It.IsAny<LogEntry>()));
var errorObserver = new Mock<IObserver<LogEntry>>();
errorObserver
.Setup(o => o.OnNext(It.IsAny<LogEntry>()));
using (TestHelper.LogToConsole()) // required in order to construct the extension and trigger its exception
using (logObserver.Object.SubscribeToLogEvents())
using (errorObserver.Object.SubscribeToLogInternalErrors())
{
Log.With<ExtensionThatThrowsInProperty>(e => { }).Write("test");
}
logObserver.VerifyAll();
errorObserver.Verify(o => o.OnNext(It.IsAny<LogEntry>()));
}
[Test]
public virtual void When_Log_Enter_accessor_func_throws_error_event_is_published()
{
// this exception will be thrown from the first mock and the second should see it in the error event
var testException = new Exception();
Func<object> thrower = () => { throw testException; };
bool errorSignaled = false;
using (TestHelper.LogToConsole()) // required in order to invoke GetInfo() and trigger the extension's exception
using (Log.Events().Subscribe(e => Console.WriteLine(e.ToLogString())))
using (TestHelper.InternalErrors().Subscribe(e => errorSignaled = true))
{
using (Log.Enter(() => new { SomeProperty = thrower() }))
{
}
}
Assert.That(errorSignaled);
}
[Test]
public virtual void When_Log_Enter_throws_no_exception_bubbles_up_to_caller()
{
var logObserver = new Mock<IObserver<LogEntry>>();
logObserver
.Setup(o => o.OnNext(It.IsAny<LogEntry>()));
using (logObserver.Object.SubscribeToLogEvents())
using (Log.Enter(() => { throw new MethodAccessException(); }))
{
}
logObserver.VerifyAll();
}
[Test]
public virtual void When_Log_With_extension_throws_error_event_is_published()
{
var errorObserver = new Mock<IObserver<LogEntry>>();
errorObserver
.Setup(o => o.OnNext(It.Is<LogEntry>((LogEntry e) => e.Subject is Exception)));
using (errorObserver.Object.SubscribeToLogInternalErrors())
{
Log.With<ExtensionThatThrowsInCtor>(e => { }).Write("test");
}
errorObserver.VerifyAll();
}
[Test]
public virtual void When_Log_With_extension_throws_no_exception_bubbles_up_to_caller()
{
Log.With<ExtensionThatThrowsInCtor>(e => { }).Write("test");
}
[Test]
public virtual void When_Log_With_params_accessor_func_throws_error_event_is_published()
{
// this exception will be thrown from the first mock and the second should see it in the error event
var testException = new Exception();
// subscribe to log events
var logObserver = new Mock<IObserver<LogEntry>>();
logObserver
.Setup(e => e.OnNext(It.IsAny<LogEntry>()));
// subscribe to error events
var errorObserver = new Mock<IObserver<LogEntry>>();
errorObserver
.Setup(o => o.OnNext(It.Is<LogEntry>(e => e.Subject is Exception)));
using (logObserver.Object.SubscribeToLogEvents())
using (errorObserver.Object.SubscribeToLogInternalErrors())
{
Func<object> thrower = () => { throw testException; };
Log.WithParams(() => new { SomeProperty = thrower() }).Write("test");
}
logObserver.VerifyAll();
}
[Test]
public virtual void When_subscriber_throws_other_subscribers_still_receive_events()
{
var lastObserver = new Mock<IObserver<LogEntry>>();
lastObserver
.Setup(o => o.OnNext(It.IsAny<LogEntry>()));
var firstObserver = new Mock<IObserver<LogEntry>>();
firstObserver
.Setup(o => o.OnNext(It.IsAny<LogEntry>()));
using (Log.Events().Subscribe(firstObserver.Object))
using (Log.Events().Subscribe(e => { throw new Exception("Test exception"); }))
using (Log.Events().Subscribe(lastObserver.Object))
{
Log.Write("test");
}
lastObserver.VerifyAll();
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using Xunit;
namespace System.Threading.Tasks.Tests
{
public static class ParallelLoopResultTests
{
[Fact]
public static void ForPLRTests()
{
ParallelLoopResult plr =
Parallel.For(1, 0, delegate (int i, ParallelLoopState ps)
{
if (i == 10) ps.Stop();
});
PLRcheck(plr, "For-Empty", true, null);
plr =
Parallel.For(0, 100, delegate (int i, ParallelLoopState ps)
{
//Thread.Sleep(20);
if (i == 10) ps.Stop();
});
PLRcheck(plr, "For-Stop", false, null);
plr =
Parallel.For(0, 100, delegate (int i, ParallelLoopState ps)
{
//Thread.Sleep(20);
if (i == 10) ps.Break();
});
PLRcheck(plr, "For-Break", false, 10);
plr =
Parallel.For(0, 100, delegate (int i, ParallelLoopState ps)
{
//Thread.Sleep(20);
});
PLRcheck(plr, "For-Completion", true, null);
}
[Fact]
public static void ForPLR64Tests()
{
ParallelLoopResult plr =
Parallel.For(1L, 0L, delegate (long i, ParallelLoopState ps)
{
if (i == 10) ps.Stop();
});
PLRcheck(plr, "For64-Empty", true, null);
plr =
Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps)
{
//Thread.Sleep(20);
if (i == 10) ps.Stop();
});
PLRcheck(plr, "For64-Stop", false, null);
plr =
Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps)
{
//Thread.Sleep(20);
if (i == 10) ps.Break();
});
PLRcheck(plr, "For64-Break", false, 10);
plr =
Parallel.For(0L, 100L, delegate (long i, ParallelLoopState ps)
{
//Thread.Sleep(20);
});
PLRcheck(plr, "For64-Completion", true, null);
}
[Fact]
public static void ForEachPLRTests()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
ParallelLoopResult plr =
Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps)
{
if (kvp.Value.Equals("Purple")) ps.Stop();
});
PLRcheck(plr, "ForEach-Empty", true, null);
dict.Add("Apple", "Red");
dict.Add("Banana", "Yellow");
dict.Add("Pear", "Green");
dict.Add("Plum", "Red");
dict.Add("Grape", "Green");
dict.Add("Cherry", "Red");
dict.Add("Carrot", "Orange");
dict.Add("Eggplant", "Purple");
plr =
Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps)
{
if (kvp.Value.Equals("Purple")) ps.Stop();
});
PLRcheck(plr, "ForEach-Stop", false, null);
plr =
Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps)
{
if (kvp.Value.Equals("Purple")) ps.Break();
});
PLRcheck(plr, "ForEach-Break", false, 7); // right??
plr =
Parallel.ForEach(dict, delegate (KeyValuePair<string, string> kvp, ParallelLoopState ps)
{
//if(kvp.Value.Equals("Purple")) ps.Stop();
});
PLRcheck(plr, "ForEach-Complete", true, null);
}
[Fact]
public static void PartitionerForEachPLRTests()
{
//
// Now try testing Partitionable, OrderablePartitionable
//
List<int> intlist = new List<int>();
for (int i = 0; i < 20; i++)
intlist.Add(i * i);
MyPartitioner<int> mp = new MyPartitioner<int>(intlist);
ParallelLoopResult plr =
Parallel.ForEach(mp, delegate (int item, ParallelLoopState ps)
{
if (item == 0) ps.Stop();
});
PLRcheck(plr, "Partitioner-ForEach-Stop", false, null);
plr = Parallel.ForEach(mp, delegate (int item, ParallelLoopState ps) { });
PLRcheck(plr, "Partitioner-ForEach-Complete", true, null);
}
[Fact]
public static void OrderablePartitionerForEachTests()
{
List<int> intlist = new List<int>();
for (int i = 0; i < 20; i++)
intlist.Add(i * i);
OrderablePartitioner<int> mop = Partitioner.Create(intlist, true);
ParallelLoopResult plr =
Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index)
{
if (index == 2) ps.Stop();
});
PLRcheck(plr, "OrderablePartitioner-ForEach-Stop", false, null);
plr =
Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index)
{
if (index == 2) ps.Break();
});
PLRcheck(plr, "OrderablePartitioner-ForEach-Break", false, 2);
plr =
Parallel.ForEach(mop, delegate (int item, ParallelLoopState ps, long index)
{
});
PLRcheck(plr, "OrderablePartitioner-ForEach-Complete", true, null);
}
private static void PLRcheck(ParallelLoopResult plr, string ttype, bool shouldComplete, int? expectedLBI)
{
Assert.Equal(shouldComplete, plr.IsCompleted);
Assert.Equal(expectedLBI, plr.LowestBreakIteration);
}
// Generalized test for testing For-loop results
private static void ForPLRTest(
Action<int, ParallelLoopState> body,
string desc,
bool excExpected,
bool shouldComplete,
bool shouldStop,
bool shouldBreak)
{
ForPLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false);
}
private static void ForPLRTest(
Action<int, ParallelLoopState> body,
ParallelOptions parallelOptions,
string desc,
bool excExpected,
bool shouldComplete,
bool shouldStop,
bool shouldBreak,
bool shouldCancel)
{
try
{
ParallelLoopResult plr = Parallel.For(0, 1, parallelOptions, body);
Assert.False(shouldCancel);
Assert.False(excExpected);
Assert.Equal(shouldComplete, plr.IsCompleted);
Assert.Equal(shouldStop, plr.LowestBreakIteration == null);
Assert.Equal(shouldBreak, plr.LowestBreakIteration != null);
}
catch (OperationCanceledException)
{
Assert.True(shouldCancel);
}
catch (AggregateException)
{
Assert.True(excExpected);
}
}
// ... and a 64-bit version
private static void For64PLRTest(
Action<long, ParallelLoopState> body,
string desc,
bool excExpected,
bool shouldComplete,
bool shouldStop,
bool shouldBreak)
{
For64PLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false);
}
private static void For64PLRTest(
Action<long, ParallelLoopState> body,
ParallelOptions parallelOptions,
string desc,
bool excExpected,
bool shouldComplete,
bool shouldStop,
bool shouldBreak,
bool shouldCancel)
{
try
{
ParallelLoopResult plr = Parallel.For(0L, 1L, parallelOptions, body);
Assert.False(shouldCancel);
Assert.False(excExpected);
Assert.Equal(shouldComplete, plr.IsCompleted);
Assert.Equal(shouldStop, plr.LowestBreakIteration == null);
Assert.Equal(shouldBreak, plr.LowestBreakIteration != null);
}
catch (OperationCanceledException)
{
Assert.True(shouldCancel);
}
catch (AggregateException)
{
Assert.True(excExpected);
}
}
// Generalized test for testing ForEach-loop results
private static void ForEachPLRTest(
Action<KeyValuePair<int, string>, ParallelLoopState> body,
string desc,
bool excExpected,
bool shouldComplete,
bool shouldStop,
bool shouldBreak)
{
ForEachPLRTest(body, new ParallelOptions(), desc, excExpected, shouldComplete, shouldStop, shouldBreak, false);
}
private static void ForEachPLRTest(
Action<KeyValuePair<int, string>, ParallelLoopState> body,
ParallelOptions parallelOptions,
string desc,
bool excExpected,
bool shouldComplete,
bool shouldStop,
bool shouldBreak,
bool shouldCancel)
{
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "one");
try
{
ParallelLoopResult plr = Parallel.ForEach(dict, parallelOptions, body);
Assert.False(shouldCancel);
Assert.False(excExpected);
Assert.Equal(shouldComplete, plr.IsCompleted);
Assert.Equal(shouldStop, plr.LowestBreakIteration == null);
Assert.Equal(shouldBreak, plr.LowestBreakIteration != null);
}
catch (OperationCanceledException)
{
Assert.True(shouldCancel);
}
catch (AggregateException)
{
Assert.True(excExpected);
}
}
// Generalized test for testing Partitioner ForEach-loop results
private static void PartitionerForEachPLRTest(
Action<int, ParallelLoopState> body,
string desc,
bool excExpected,
bool shouldComplete,
bool shouldStop,
bool shouldBreak)
{
List<int> list = new List<int>();
for (int i = 0; i < 20; i++) list.Add(i);
MyPartitioner<int> mp = new MyPartitioner<int>(list);
try
{
ParallelLoopResult plr =
Parallel.ForEach(mp, body);
Assert.False(excExpected);
Assert.Equal(shouldComplete, plr.IsCompleted);
Assert.Equal(shouldStop, plr.LowestBreakIteration == null);
Assert.Equal(shouldBreak, plr.LowestBreakIteration != null);
}
catch (AggregateException)
{
Assert.True(excExpected);
}
}
// Generalized test for testing OrderablePartitioner ForEach-loop results
private static void OrderablePartitionerForEachPLRTest(
Action<int, ParallelLoopState, long> body,
string desc,
bool excExpected,
bool shouldComplete,
bool shouldStop,
bool shouldBreak)
{
List<int> list = new List<int>();
for (int i = 0; i < 20; i++) list.Add(i);
OrderablePartitioner<int> mop = Partitioner.Create(list, true);
try
{
ParallelLoopResult plr = Parallel.ForEach(mop, body);
Assert.False(excExpected);
Assert.Equal(shouldComplete, plr.IsCompleted);
Assert.Equal(shouldStop, plr.LowestBreakIteration == null);
Assert.Equal(shouldBreak, plr.LowestBreakIteration != null);
}
catch (AggregateException)
{
Assert.True(excExpected);
}
}
// Perform tests on various combinations of Stop()/Break()
[Fact]
public static void SimultaneousStopBreakTests()
{
//
// Test 32-bit Parallel.For()
//
ForPLRTest(delegate (int i, ParallelLoopState ps)
{
ps.Stop();
ps.Break();
},
"Break After Stop",
true,
false,
false,
false);
ForPLRTest(delegate (int i, ParallelLoopState ps)
{
ps.Break();
ps.Stop();
},
"Stop After Break",
true,
false,
false,
false);
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions options = new ParallelOptions();
options.CancellationToken = cts.Token;
ForPLRTest(delegate (int i, ParallelLoopState ps)
{
ps.Break();
cts.Cancel();
},
options,
"Cancel After Break",
false,
false,
false,
false,
true);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
ForPLRTest(delegate (int i, ParallelLoopState ps)
{
ps.Stop();
cts.Cancel();
},
options,
"Cancel After Stop",
false,
false,
false,
false,
true);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
ForPLRTest(delegate (int i, ParallelLoopState ps)
{
cts.Cancel();
ps.Stop();
},
options,
"Stop After Cancel",
false,
false,
false,
false,
true);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
ForPLRTest(delegate (int i, ParallelLoopState ps)
{
cts.Cancel();
ps.Break();
},
options,
"Break After Cancel",
false,
false,
false,
false,
true);
ForPLRTest(delegate (int i, ParallelLoopState ps)
{
ps.Break();
try
{
ps.Stop();
}
catch { }
},
"Stop(caught) after Break",
false,
false,
false,
true);
ForPLRTest(delegate (int i, ParallelLoopState ps)
{
ps.Stop();
try
{
ps.Break();
}
catch { }
},
"Break(caught) after Stop",
false,
false,
true,
false);
//
// Test "vanilla" Parallel.ForEach
//
ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps)
{
ps.Break();
ps.Stop();
},
"Stop-After-Break",
true,
false,
false,
false);
ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps)
{
ps.Stop();
ps.Break();
},
"Break-after-Stop",
true,
false,
false,
false);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps)
{
ps.Break();
cts.Cancel();
},
options,
"Cancel After Break",
false,
false,
false,
false,
true);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps)
{
ps.Stop();
cts.Cancel();
},
options,
"Cancel After Stop",
false,
false,
false,
false,
true);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps)
{
cts.Cancel();
ps.Stop();
},
options,
"Stop After Cancel",
false,
false,
false,
false,
true);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps)
{
cts.Cancel();
ps.Break();
},
options,
"Break After Cancel",
false,
false,
false,
false,
true);
ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps)
{
ps.Break();
try
{
ps.Stop();
}
catch { }
},
"Stop(caught)-after-Break",
false,
false,
false,
true);
ForEachPLRTest(delegate (KeyValuePair<int, string> kvp, ParallelLoopState ps)
{
ps.Stop();
try
{
ps.Break();
}
catch { }
},
"Break(caught)-after-Stop",
false,
false,
true,
false);
//
// Test Parallel.ForEach w/ Partitioner
//
PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps)
{
ps.Break();
ps.Stop();
},
"Stop-After-Break",
true,
false,
false,
false);
PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps)
{
ps.Stop();
ps.Break();
},
"Break-after-Stop",
true,
false,
false,
false);
PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps)
{
ps.Break();
try
{
ps.Stop();
}
catch { }
},
"Stop(caught)-after-Break",
false,
false,
false,
true);
PartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps)
{
ps.Stop();
try
{
ps.Break();
}
catch { }
},
"Break(caught)-after-Stop",
false,
false,
true,
false);
//
// Test Parallel.ForEach w/ OrderablePartitioner
//
OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index)
{
ps.Break();
ps.Stop();
},
"Stop-After-Break",
true,
false,
false,
false);
OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index)
{
ps.Stop();
ps.Break();
},
"Break-after-Stop",
true,
false,
false,
false);
OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index)
{
ps.Break();
try
{
ps.Stop();
}
catch { }
},
"Stop(caught)-after-Break",
false,
false,
false,
true);
OrderablePartitionerForEachPLRTest(delegate (int i, ParallelLoopState ps, long index)
{
ps.Stop();
try
{
ps.Break();
}
catch { }
},
"Break(caught)-after-Stop",
false,
false,
true,
false);
//
// Test 64-bit Parallel.For
//
For64PLRTest(delegate (long i, ParallelLoopState ps)
{
ps.Stop();
ps.Break();
},
"Break After Stop",
true,
false,
false,
false);
For64PLRTest(delegate (long i, ParallelLoopState ps)
{
ps.Break();
ps.Stop();
},
"Stop After Break",
true,
false,
false,
false);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
For64PLRTest(delegate (long i, ParallelLoopState ps)
{
ps.Break();
cts.Cancel();
},
options,
"Cancel After Break",
false,
false,
false,
false,
true);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
For64PLRTest(delegate (long i, ParallelLoopState ps)
{
ps.Stop();
cts.Cancel();
},
options,
"Cancel After Stop",
false,
false,
false,
false,
true);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
For64PLRTest(delegate (long i, ParallelLoopState ps)
{
cts.Cancel();
ps.Stop();
},
options,
"Stop after Cancel",
false,
false,
false,
false,
true);
cts = new CancellationTokenSource();
options = new ParallelOptions();
options.CancellationToken = cts.Token;
For64PLRTest(delegate (long i, ParallelLoopState ps)
{
cts.Cancel();
ps.Break();
},
options,
"Break after Cancel",
false,
false,
false,
false,
true);
For64PLRTest(delegate (long i, ParallelLoopState ps)
{
ps.Break();
try
{
ps.Stop();
}
catch { }
},
"Stop(caught) after Break",
false,
false,
false,
true);
For64PLRTest(delegate (long i, ParallelLoopState ps)
{
ps.Stop();
try
{
ps.Break();
}
catch { }
},
"Break(caught) after Stop",
false,
false,
true,
false);
}
#region Helper Classes and Methods
//
// Utility class for use w/ Partitioner-style ForEach testing.
// Created by Cindy Song.
//
public class MyPartitioner<TSource> : Partitioner<TSource>
{
private IList<TSource> _data;
public MyPartitioner(IList<TSource> data)
{
_data = data;
}
override public IList<IEnumerator<TSource>> GetPartitions(int partitionCount)
{
if (partitionCount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(partitionCount));
}
IEnumerator<TSource>[] partitions
= new IEnumerator<TSource>[partitionCount];
IEnumerable<KeyValuePair<long, TSource>> partitionEnumerable = Partitioner.Create(_data, true).GetOrderableDynamicPartitions();
for (int i = 0; i < partitionCount; i++)
{
partitions[i] = DropIndices(partitionEnumerable.GetEnumerator());
}
return partitions;
}
override public IEnumerable<TSource> GetDynamicPartitions()
{
return DropIndices(Partitioner.Create(_data, true).GetOrderableDynamicPartitions());
}
private static IEnumerable<TSource> DropIndices(IEnumerable<KeyValuePair<long, TSource>> source)
{
foreach (KeyValuePair<long, TSource> pair in source)
{
yield return pair.Value;
}
}
private static IEnumerator<TSource> DropIndices(IEnumerator<KeyValuePair<long, TSource>> source)
{
while (source.MoveNext())
{
yield return source.Current.Value;
}
}
public override bool SupportsDynamicPartitions
{
get { return true; }
}
}
#endregion
}
}
| |
/*
Copyright (c) 2004-2009 Deepak Nataraj. All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S)
AND ALL OTHER CONTRIBUTORS 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 ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using GOBaseLibrary.Interfaces;
namespace GOBaseLibrary.Common
{
public enum GossipType { DIGEST, FULL_MESSAGE };
/// <summary>
/// represents a concrete IGossip object
/// </summary>
[Serializable]
[QS.Fx.Reflection.ValueClass("6`1", "Rumor")]
public class Rumor : IGossip
{
private String id;
private GossipType type;
private Group sourceGroup;
private Group destinationGroup;
private Node sourceNode;
private Node destinationNode;
private String payLoad;
private string version;
private int hopCount;
private bool mark;
private double receivedTimestamp; // set to timestamp when the rumor is received
private int size;
private double utility;
private long age;
private long timeReceived;
public Rumor() { size = this.GetSize(); }
public Rumor(String uniqueID, String payload)
{
type = GossipType.FULL_MESSAGE;
id = uniqueID;
payLoad = payload;
mark = false;
receivedTimestamp = -1;
size = this.GetSize();
}
[XmlElement]
public String Id { get { return id; } set { id = value; } }
[XmlElement]
public GossipType Type { get { return type; } set { type = value; } }
[XmlElement]
public Group SourceGroup { get { return sourceGroup; } set { sourceGroup = value; } }
[XmlElement]
public Group DestinationGroup { get { return destinationGroup; } set { destinationGroup = value; } }
[XmlElement]
public Node SourceNode { get { return sourceNode; } set { sourceNode = value; } }
[XmlElement]
public Node DestinationNode { get { return destinationNode; } set { destinationNode = value; } }
[XmlElement]
public String PayLoad { get { return payLoad; } set { payLoad = value; } } // Content that has to be rumored
[XmlElement]
public String Version { get { return version; } set { version = value; } }
[XmlElement]
public int HopCount { get { return hopCount; } set { hopCount = value; } } // time to live
[XmlElement]
public bool Mark { get { return mark; } set { mark = value; } } // mark for deletion etc.,.
[XmlElement]
public int Size { get { return this.GetSize(); } }
[XmlElement]
public double Utility { get { return utility; } set { utility = value; } }
public double ReceivedTimestamp { get { return this.receivedTimestamp; } }
[XmlElement]
public long Age { get { return this.age; } set { this.age = value; } }
[XmlElement]
public long ReceivedTS { get { return this.timeReceived; } }
public int GetSize()
{
MemoryStream outStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(outStream);
/*
* <Int32> number of rumors in this message
* <String> rumor id
* <Int32> hopcount
* <String> source group
* <String> destination group
* <String> source node
* <String> destination node
* <String> payload
* */
writer.Write((int)this.type);
if (this.id != null)
writer.Write(this.Id);
writer.Write(this.HopCount);
if (this.payLoad != null)
writer.Write(this.PayLoad);
if (this.sourceGroup != null)
writer.Write(this.SourceGroup.Id);
if (this.destinationGroup != null)
writer.Write(this.DestinationGroup.Id);
if (this.sourceNode != null)
writer.Write(this.SourceNode.Id);
if (this.destinationNode != null)
writer.Write(this.DestinationNode.Id);
return (int) outStream.Length;
}
public void StampTheTime()
{
double now = Utils.ConvertToUnixTimestamp(DateTime.Now);
this.receivedTimestamp = now;
this.timeReceived = DateTime.Now.Ticks;
}
public double GetTimestamp()
{
Debug.WriteLineIf(Utils.debugSwitch.Verbose,"Rumor::GetTimestamp: returning " + this.receivedTimestamp + "[" + DateTime.Now + "]");
return this.receivedTimestamp;
}
/// <summary>
/// check if the timestamp on the rumor has expired or not
/// </summary>
/// <param name="interval">timestamp expiry in milliseconds</param>
/// <returns>true if timestamp has expired, false otherwise</returns>
public bool IsTimerExpired(double interval)
{
double now = Utils.ConvertToUnixTimestamp(DateTime.Now);
bool retValue = now > this.receivedTimestamp + interval;
Debug.WriteLineIf(Utils.debugSwitch.Verbose,"Rumor::IsExpired: rumor[" + this.id + "], interval is " + interval
+ ", returning " + retValue + "["
+ Utils.ConvertFromUnixTimestamp(this.receivedTimestamp) + "]");
return retValue;
}
/// <summary>
/// set a timer which fires up later to pass 'this' to the callback specified
/// </summary>
/// <param name="_timerDelegate">callback function to call when the timer expires</param>
/// <param name="interval">amount of time elapsed in milliseconds, before which the callback is invoked</param>
public void StartTTLTicks(TimerCallback _timerDelegate, long interval)
{
if (_timerDelegate == null)
{
throw new Exception("timercallback is undefined");
}
new Timer(_timerDelegate, this, interval, Timeout.Infinite);
}
// deep copy in separate memory space
public object Clone()
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Position = 0;
object obj = bf.Deserialize(ms);
ms.Close();
return obj;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Configuration;
using Orleans.GrainDirectory;
using Orleans.Internal;
namespace Orleans.Runtime.GrainDirectory
{
/// <summary>
/// Implementation of <see cref="IGrainLocator"/> that uses <see cref="IGrainDirectory"/> stores.
/// </summary>
internal class CachedGrainLocator : IGrainLocator, ILifecycleParticipant<ISiloLifecycle>, CachedGrainLocator.ITestAccessor
{
private readonly GrainDirectoryResolver grainDirectoryResolver;
private readonly IGrainDirectoryCache cache;
private readonly CancellationTokenSource shutdownToken = new CancellationTokenSource();
private readonly IClusterMembershipService clusterMembershipService;
private Task listenToClusterChangeTask;
internal interface ITestAccessor
{
MembershipVersion LastMembershipVersion { get; set; }
}
MembershipVersion ITestAccessor.LastMembershipVersion { get; set; }
public CachedGrainLocator(
GrainDirectoryResolver grainDirectoryResolver,
IClusterMembershipService clusterMembershipService)
{
this.grainDirectoryResolver = grainDirectoryResolver;
this.clusterMembershipService = clusterMembershipService;
this.cache = new LRUBasedGrainDirectoryCache(GrainDirectoryOptions.DEFAULT_CACHE_SIZE, GrainDirectoryOptions.DEFAULT_MAXIMUM_CACHE_TTL);
}
public async ValueTask<ActivationAddress> Lookup(GrainId grainId)
{
var grainType = grainId.Type;
if (grainType.IsClient() || grainType.IsSystemTarget())
{
ThrowUnsupportedGrainType(grainId);
}
// Check cache first
if (TryLocalLookup(grainId, out var cachedResult))
{
return cachedResult;
}
var entry = await GetGrainDirectory(grainId.Type).Lookup(grainId);
// Nothing found
if (entry is null)
{
return null;
}
var entryAddress = entry.ToActivationAddress();
ActivationAddress result;
// Check if the entry is pointing to a dead silo
if (IsKnownDeadSilo(entry))
{
// Remove it from the directory
await GetGrainDirectory(grainId.Type).Unregister(entry);
result = null;
}
else
{
// Add to the local cache and return it
this.cache.AddOrUpdate(entryAddress, 0);
result = entryAddress;
}
return result;
}
public async Task<ActivationAddress> Register(ActivationAddress address)
{
var grainType = address.Grain.Type;
if (grainType.IsClient() || grainType.IsSystemTarget())
{
ThrowUnsupportedGrainType(address.Grain);
}
var grainAddress = address.ToGrainAddress();
grainAddress.MembershipVersion = this.clusterMembershipService.CurrentSnapshot.Version;
var result = await GetGrainDirectory(grainType).Register(grainAddress);
var activationAddress = result.ToActivationAddress();
// Check if the entry point to a dead silo
if (IsKnownDeadSilo(result))
{
// Remove outdated entry and retry to register
await GetGrainDirectory(grainType).Unregister(result);
result = await GetGrainDirectory(grainType).Register(grainAddress);
activationAddress = result.ToActivationAddress();
}
// Cache update
this.cache.AddOrUpdate(activationAddress, (int) result.MembershipVersion.Value);
return activationAddress;
}
public bool TryLocalLookup(GrainId grainId, out ActivationAddress result)
{
var grainType = grainId.Type;
if (grainType.IsClient() || grainType.IsSystemTarget())
{
ThrowUnsupportedGrainType(grainId);
}
if (this.cache.LookUp(grainId, out result, out var version))
{
// If the silo is dead, remove the entry
if (IsKnownDeadSilo(result.Silo, new MembershipVersion(version)))
{
result = default;
this.cache.Remove(grainId);
}
else
{
// Entry found and valid -> return it
return true;
}
}
return false;
}
public async Task Unregister(ActivationAddress address, UnregistrationCause cause)
{
try
{
await GetGrainDirectory(address.Grain.Type).Unregister(address.ToGrainAddress());
}
finally
{
this.cache.Remove(address.Grain);
}
}
public void Participate(ISiloLifecycle lifecycle)
{
Task OnStart(CancellationToken ct)
{
this.listenToClusterChangeTask = ListenToClusterChange();
return Task.CompletedTask;
};
async Task OnStop(CancellationToken ct)
{
this.shutdownToken.Cancel();
if (listenToClusterChangeTask != default && !ct.IsCancellationRequested)
await listenToClusterChangeTask.WithCancellation(ct);
};
lifecycle.Subscribe(nameof(CachedGrainLocator), ServiceLifecycleStage.RuntimeGrainServices, OnStart, OnStop);
}
private IGrainDirectory GetGrainDirectory(GrainType grainType) => this.grainDirectoryResolver.Resolve(grainType);
private async Task ListenToClusterChange()
{
var previousSnapshot = this.clusterMembershipService.CurrentSnapshot;
((ITestAccessor)this).LastMembershipVersion = previousSnapshot.Version;
var updates = this.clusterMembershipService.MembershipUpdates.WithCancellation(this.shutdownToken.Token);
await foreach (var snapshot in updates)
{
// Active filtering: detect silos that went down and try to clean proactively the directory
var changes = snapshot.CreateUpdate(previousSnapshot).Changes;
var deadSilos = changes
.Where(member => member.Status.IsTerminating())
.Select(member => member.SiloAddress)
.ToList();
if (deadSilos.Count > 0)
{
var tasks = new List<Task>();
foreach (var directory in this.grainDirectoryResolver.Directories)
{
tasks.Add(directory.UnregisterSilos(deadSilos));
}
await Task.WhenAll(tasks).WithCancellation(this.shutdownToken.Token);
}
((ITestAccessor)this).LastMembershipVersion = snapshot.Version;
}
}
private bool IsKnownDeadSilo(GrainAddress grainAddress)
=> IsKnownDeadSilo(grainAddress.SiloAddress, grainAddress.MembershipVersion);
private bool IsKnownDeadSilo(SiloAddress siloAddress, MembershipVersion membershipVersion)
{
var current = this.clusterMembershipService.CurrentSnapshot;
// Check if the target silo is in the cluster
if (current.Members.TryGetValue(siloAddress, out var value))
{
// It is, check if it's alive
return value.Status.IsTerminating();
}
// We didn't find it in the cluster. If the silo entry is too old, it has been cleaned in the membership table: the entry isn't valid anymore.
// Otherwise, maybe the membership service isn't up to date yet. The entry should be valid
return current.Version > membershipVersion;
}
private static void ThrowUnsupportedGrainType(GrainId grainId) => throw new InvalidOperationException($"Unsupported grain type for grain {grainId}");
}
internal static class AddressHelpers
{
public static ActivationAddress ToActivationAddress(this GrainAddress addr)
{
return ActivationAddress.GetAddress(
addr.SiloAddress,
addr.GrainId,
ActivationId.GetActivationId(UniqueKey.Parse(addr.ActivationId.AsSpan())));
}
public static GrainAddress ToGrainAddress(this ActivationAddress addr)
{
return new GrainAddress
{
SiloAddress = addr.Silo,
GrainId = addr.Grain,
ActivationId = (addr.Activation.Key.ToHexString())
};
}
}
}
| |
//
// DetailsSource.cs
//
// Authors:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Unix;
using Hyena;
using Hyena.Collections;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Configuration;
using Banshee.Database;
using Banshee.Gui;
using Banshee.Library;
using Banshee.MediaEngine;
using Banshee.PlaybackController;
using Banshee.Playlist;
using Banshee.Preferences;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Sources.Gui;
using IA=InternetArchive;
namespace Banshee.InternetArchive
{
public class DetailsSource : Banshee.Sources.Source, ITrackModelSource, IDurationAggregator, IFileSizeAggregator, IUnmapableSource
{
private Item item;
private MemoryTrackListModel track_model;
private LazyLoadSourceContents<DetailsView> gui;
public Item Item {
get { return item; }
}
public DetailsSource (string id, string title, string mediaType) : this (Item.LoadOrCreate (id, title, mediaType)) {}
public DetailsSource (Item item) : base (item.Title, item.Title, 195, "internet-archive-" + item.Id)
{
this.item = item;
track_model = new MemoryTrackListModel ();
track_model.Reloaded += delegate { OnUpdated (); };
Properties.SetString ("ActiveSourceUIResource", "DetailsSourceActiveUI.xml");
Properties.SetString ("GtkActionPath", "/IaDetailsSourcePopup");
Properties.SetString ("UnmapSourceActionLabel", Catalog.GetString ("Close Item"));
Properties.SetString ("UnmapSourceActionIconName", "gtk-close");
SetIcon ();
gui = new LazyLoadSourceContents<DetailsView> (this, item);
Properties.Set<ISourceContents> ("Nereid.SourceContents", gui);
}
private bool details_loaded;
internal void LoadDetails ()
{
if (details_loaded) {
return;
}
details_loaded = true;
if (item.Details == null) {
SetStatus (Catalog.GetString ("Getting item details from the Internet Archive"), false, true, null);
Load ();
} else {
gui.Contents.UpdateDetails ();
}
}
private void SetIcon ()
{
if (item.MediaType == null)
return;
var media_type = IA.MediaType.Options.FirstOrDefault (mt =>
item.MediaType.Contains (mt.Id) || mt.Children.Any (c => item.MediaType.Contains (c.Id))
);
if (media_type == null)
return;
if (media_type.Id == "audio") {
Properties.SetStringList ("Icon.Name", "audio-x-generic", "audio");
} else if (media_type.Id == "movies") {
Properties.SetStringList ("Icon.Name", "video-x-generic", "video");
} else if (media_type.Id == "texts") {
Properties.SetStringList ("Icon.Name", "x-office-document", "document");
} else if (media_type.Id == "education") {
Properties.SetStringList ("Icon.Name", "video-x-generic", "video");
}
}
private void Load ()
{
ThreadAssist.SpawnFromMain (ThreadedLoad);
}
private void ThreadedLoad ()
{
try {
item.LoadDetails ();
ThreadAssist.ProxyToMain (delegate {
ClearMessages ();
if (item.Details != null) {
gui.Contents.UpdateDetails ();
}
});
} catch (Exception e) {
Hyena.Log.Exception ("Error loading IA item details", e);
ThreadAssist.ProxyToMain (delegate {
var web_e = e as System.Net.WebException;
if (web_e != null && web_e.Status == System.Net.WebExceptionStatus.Timeout) {
SetStatus (Catalog.GetString ("Timed out getting item details from the Internet Archive"), true);
CurrentMessage.AddAction (new MessageAction (Catalog.GetString ("Try Again"), (o, a) => Load ()));
} else {
SetStatus (Catalog.GetString ("Error getting item details from the Internet Archive"), true);
}
});
}
}
public void Reload ()
{
}
public override string PreferencesPageId {
get { return Parent.PreferencesPageId; }
}
public override int Count {
get { return 0; }
}
public override int FilteredCount {
get { return track_model.Count; }
}
public TimeSpan Duration {
get {
TimeSpan duration = TimeSpan.Zero;
foreach (var t in track_model) {
duration += t.Duration;
}
return duration;
}
}
public long FileSize {
get {
// Mono on openSUSE 11.0 doesn't like this
// return track_model.Sum (t => t.FileSize);
long result = 0;
foreach (var t in track_model)
result += t.FileSize;
return result;
}
}
#region ITrackModelSource
public TrackListModel TrackModel {
get { return track_model; }
}
public bool HasDependencies { get { return false; } }
public void RemoveTracks (Selection selection) {}
public void DeleteTracks (Selection selection) {}
public bool ConfirmRemoveTracks { get { return false; } }
public bool Indexable { get { return false; } }
public bool ShowBrowser {
get { return false; }
}
public bool CanPlay {
get { return true; }
}
public bool CanShuffle {
get { return false; }
}
public bool CanRepeat {
get { return true; }
}
public bool CanAddTracks {
get { return false; }
}
public bool CanRemoveTracks {
get { return false; }
}
public bool CanDeleteTracks {
get { return false; }
}
#endregion
public bool CanUnmap { get { return true; } }
public bool ConfirmBeforeUnmap { get { return false; } }
public bool Unmap ()
{
// If we were the active source, switch to the Search source
if (this == ServiceManager.SourceManager.ActiveSource) {
ServiceManager.SourceManager.SetActiveSource ((Parent as HomeSource).SearchSource);
}
item.Delete ();
Parent.RemoveChildSource (this);
return true;
}
public override bool HasEditableTrackProperties {
get { return false; }
}
public override bool HasViewableTrackProperties {
get { return false; }
}
public override bool CanSearch {
get { return false; }
}
}
}
| |
using System.Collections.Generic;
using Avalonia;
using Avalonia.Media;
namespace WalletWasabi.Fluent.Controls
{
public partial class LineChart
{
// Area
public static readonly StyledProperty<Thickness> AreaMarginProperty =
AvaloniaProperty.Register<LineChart, Thickness>(nameof(AreaMargin));
public static readonly StyledProperty<IBrush?> AreaFillProperty =
AvaloniaProperty.Register<LineChart, IBrush?>(nameof(AreaFill));
public static readonly StyledProperty<IBrush?> AreaStrokeProperty =
AvaloniaProperty.Register<LineChart, IBrush?>(nameof(AreaStroke));
public static readonly StyledProperty<double> AreaStrokeThicknessProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(AreaStrokeThickness), 1.0);
public static readonly StyledProperty<IDashStyle?> AreaStrokeDashStyleProperty =
AvaloniaProperty.Register<LineChart, IDashStyle?>(nameof(AreaStrokeDashStyle), null);
public static readonly StyledProperty<PenLineCap> AreaStrokeLineCapProperty =
AvaloniaProperty.Register<LineChart, PenLineCap>(nameof(AreaStrokeLineCap), PenLineCap.Flat);
public static readonly StyledProperty<PenLineJoin> AreaStrokeLineJoinProperty =
AvaloniaProperty.Register<LineChart, PenLineJoin>(nameof(AreaStrokeLineJoin), PenLineJoin.Miter);
public static readonly StyledProperty<double> AreaStrokeMiterLimitProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(AreaStrokeMiterLimit), 10.0);
public static readonly StyledProperty<double> AreaMinViableHeightProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(AreaMinViableHeight), double.MinValue);
public static readonly StyledProperty<double> AreaMinViableWidthProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(AreaMinViableWidth), double.MinValue);
// XAxis
public static readonly StyledProperty<IList<double>?> XAxisValuesProperty =
AvaloniaProperty.Register<LineChart, IList<double>?>(nameof(XAxisValues));
public static readonly StyledProperty<IList<string>?> XAxisLabelsProperty =
AvaloniaProperty.Register<LineChart, IList<string>?>(nameof(XAxisLabels));
public static readonly StyledProperty<double> XAxisOpacityProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisOpacity));
public static readonly StyledProperty<Point> XAxisOffsetProperty =
AvaloniaProperty.Register<LineChart, Point>(nameof(XAxisOffset));
public static readonly StyledProperty<IBrush?> XAxisStrokeProperty =
AvaloniaProperty.Register<LineChart, IBrush?>(nameof(XAxisStroke));
public static readonly StyledProperty<double> XAxisStrokeThicknessProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisStrokeThickness));
public static readonly StyledProperty<double> XAxisArrowSizeProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisArrowSize));
public static readonly StyledProperty<double> XAxisMinViableHeightProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisMinViableHeight), double.MinValue);
public static readonly StyledProperty<double> XAxisMinViableWidthProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisMinViableWidth), double.MinValue);
// XAxis Label
public static readonly StyledProperty<IBrush?> XAxisLabelForegroundProperty =
AvaloniaProperty.Register<LineChart, IBrush?>(nameof(XAxisLabelForeground));
public static readonly StyledProperty<double> XAxisLabelOpacityProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisLabelOpacity));
public static readonly StyledProperty<Point> XAxisLabelOffsetProperty =
AvaloniaProperty.Register<LineChart, Point>(nameof(XAxisLabelOffset));
public static readonly StyledProperty<Size> XAxisLabelSizeProperty =
AvaloniaProperty.Register<LineChart, Size>(nameof(XAxisLabelSize));
public static readonly StyledProperty<TextAlignment> XAxisLabelAlignmentProperty =
AvaloniaProperty.Register<LineChart, TextAlignment>(nameof(XAxisLabelAlignment));
public static readonly StyledProperty<double> XAxisLabelAngleProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisLabelAngle));
public static readonly StyledProperty<FontFamily> XAxisLabelFontFamilyProperty =
AvaloniaProperty.Register<LineChart, FontFamily>(nameof(XAxisLabelFontFamily));
public static readonly StyledProperty<FontStyle> XAxisLabelFontStyleProperty =
AvaloniaProperty.Register<LineChart, FontStyle>(nameof(XAxisLabelFontStyle));
public static readonly StyledProperty<FontWeight> XAxisLabelFontWeightProperty =
AvaloniaProperty.Register<LineChart, FontWeight>(nameof(XAxisLabelFontWeight));
public static readonly StyledProperty<double> XAxisLabelFontSizeProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisLabelFontSize));
// XAxis Title
public static readonly StyledProperty<string> XAxisTitleProperty =
AvaloniaProperty.Register<LineChart, string>(nameof(XAxisTitle));
public static readonly StyledProperty<IBrush?> XAxisTitleForegroundProperty =
AvaloniaProperty.Register<LineChart, IBrush?>(nameof(XAxisTitleForeground));
public static readonly StyledProperty<double> XAxisTitleOpacityProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisTitleOpacity));
public static readonly StyledProperty<Point> XAxisTitleOffsetProperty =
AvaloniaProperty.Register<LineChart, Point>(nameof(XAxisTitleOffset));
public static readonly StyledProperty<Size> XAxisTitleSizeProperty =
AvaloniaProperty.Register<LineChart, Size>(nameof(XAxisTitleSize));
public static readonly StyledProperty<TextAlignment> XAxisTitleAlignmentProperty =
AvaloniaProperty.Register<LineChart, TextAlignment>(nameof(XAxisTitleAlignment));
public static readonly StyledProperty<double> XAxisTitleAngleProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisTitleAngle));
public static readonly StyledProperty<FontFamily> XAxisTitleFontFamilyProperty =
AvaloniaProperty.Register<LineChart, FontFamily>(nameof(XAxisTitleFontFamily));
public static readonly StyledProperty<FontStyle> XAxisTitleFontStyleProperty =
AvaloniaProperty.Register<LineChart, FontStyle>(nameof(XAxisTitleFontStyle));
public static readonly StyledProperty<FontWeight> XAxisTitleFontWeightProperty =
AvaloniaProperty.Register<LineChart, FontWeight>(nameof(XAxisTitleFontWeight));
public static readonly StyledProperty<double> XAxisTitleFontSizeProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisTitleFontSize));
// YAxis
public static readonly StyledProperty<IList<double>?> YAxisValuesProperty =
AvaloniaProperty.Register<LineChart, IList<double>?>(nameof(YAxisValues));
public static readonly StyledProperty<bool> YAxisLogarithmicScaleProperty =
AvaloniaProperty.Register<LineChart, bool>(nameof(YAxisLogarithmicScale));
public static readonly StyledProperty<double> XAxisCurrentValueProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisCurrentValue));
public static readonly StyledProperty<double> XAxisMinValueProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisMinValue));
public static readonly StyledProperty<double> XAxisMaxValueProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(XAxisMaxValue));
public static readonly StyledProperty<double> YAxisOpacityProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(YAxisOpacity));
public static readonly StyledProperty<Point> YAxisOffsetProperty =
AvaloniaProperty.Register<LineChart, Point>(nameof(YAxisOffset));
public static readonly StyledProperty<IBrush?> YAxisStrokeProperty =
AvaloniaProperty.Register<LineChart, IBrush?>(nameof(YAxisStroke));
public static readonly StyledProperty<double> YAxisStrokeThicknessProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(YAxisStrokeThickness));
public static readonly StyledProperty<double> YAxisArrowSizeProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(YAxisArrowSize));
public static readonly StyledProperty<double> YAxisMinViableHeightProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(YAxisMinViableHeight), double.MinValue);
public static readonly StyledProperty<double> YAxisMinViableWidthProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(YAxisMinViableWidth), double.MinValue);
// YAxis Title
public static readonly StyledProperty<string> YAxisTitleProperty =
AvaloniaProperty.Register<LineChart, string>(nameof(YAxisTitle));
public static readonly StyledProperty<IBrush?> YAxisTitleForegroundProperty =
AvaloniaProperty.Register<LineChart, IBrush?>(nameof(YAxisTitleForeground));
public static readonly StyledProperty<double> YAxisTitleOpacityProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(YAxisTitleOpacity));
public static readonly StyledProperty<Point> YAxisTitleOffsetProperty =
AvaloniaProperty.Register<LineChart, Point>(nameof(YAxisTitleOffset));
public static readonly StyledProperty<Size> YAxisTitleSizeProperty =
AvaloniaProperty.Register<LineChart, Size>(nameof(YAxisTitleSize));
public static readonly StyledProperty<TextAlignment> YAxisTitleAlignmentProperty =
AvaloniaProperty.Register<LineChart, TextAlignment>(nameof(YAxisTitleAlignment));
public static readonly StyledProperty<double> YAxisTitleAngleProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(YAxisTitleAngle));
public static readonly StyledProperty<FontFamily> YAxisTitleFontFamilyProperty =
AvaloniaProperty.Register<LineChart, FontFamily>(nameof(YAxisTitleFontFamily));
public static readonly StyledProperty<FontStyle> YAxisTitleFontStyleProperty =
AvaloniaProperty.Register<LineChart, FontStyle>(nameof(YAxisTitleFontStyle));
public static readonly StyledProperty<FontWeight> YAxisTitleFontWeightProperty =
AvaloniaProperty.Register<LineChart, FontWeight>(nameof(YAxisTitleFontWeight));
public static readonly StyledProperty<double> YAxisTitleFontSizeProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(YAxisTitleFontSize));
// Cursor
public static readonly StyledProperty<IBrush?> CursorStrokeProperty =
AvaloniaProperty.Register<LineChart, IBrush?>(nameof(CursorStroke));
public static readonly StyledProperty<double> CursorStrokeThicknessProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(CursorStrokeThickness), 1.0);
public static readonly StyledProperty<IDashStyle?> CursorStrokeDashStyleProperty =
AvaloniaProperty.Register<LineChart, IDashStyle?>(nameof(CursorStrokeDashStyle), null);
public static readonly StyledProperty<PenLineCap> CursorStrokeLineCapProperty =
AvaloniaProperty.Register<LineChart, PenLineCap>(nameof(CursorStrokeLineCap), PenLineCap.Flat);
public static readonly StyledProperty<PenLineJoin> CursorStrokeLineJoinProperty =
AvaloniaProperty.Register<LineChart, PenLineJoin>(nameof(CursorStrokeLineJoin), PenLineJoin.Miter);
public static readonly StyledProperty<double> CursorStrokeMiterLimitProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(CursorStrokeMiterLimit), 10.0);
// Border
public static readonly StyledProperty<IBrush?> BorderBrushProperty =
AvaloniaProperty.Register<LineChart, IBrush?>(nameof(BorderBrush));
public static readonly StyledProperty<double> BorderThicknessProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(BorderThickness));
public static readonly StyledProperty<double> BorderRadiusXProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(BorderRadiusX));
public static readonly StyledProperty<double> BorderRadiusYProperty =
AvaloniaProperty.Register<LineChart, double>(nameof(BorderRadiusY));
// Fields
private bool _captured;
// ctor
static LineChart()
{
AffectsMeasure<LineChart>(AreaMarginProperty);
AffectsRender<LineChart>(
AreaMarginProperty,
AreaFillProperty,
AreaStrokeProperty,
AreaStrokeThicknessProperty,
AreaStrokeDashStyleProperty,
AreaStrokeLineCapProperty,
AreaStrokeLineJoinProperty,
AreaStrokeMiterLimitProperty,
XAxisValuesProperty,
XAxisLabelsProperty,
XAxisOpacityProperty,
XAxisOffsetProperty,
XAxisStrokeProperty,
XAxisStrokeThicknessProperty,
XAxisArrowSizeProperty,
XAxisLabelForegroundProperty,
XAxisLabelOpacityProperty,
XAxisLabelOffsetProperty,
XAxisLabelSizeProperty,
XAxisLabelAlignmentProperty,
XAxisLabelAngleProperty,
XAxisLabelFontFamilyProperty,
XAxisLabelFontStyleProperty,
XAxisLabelFontWeightProperty,
XAxisLabelFontSizeProperty,
XAxisTitleProperty,
XAxisTitleForegroundProperty,
XAxisTitleOpacityProperty,
XAxisTitleOffsetProperty,
XAxisTitleSizeProperty,
XAxisTitleAlignmentProperty,
XAxisTitleAngleProperty,
XAxisTitleFontFamilyProperty,
XAxisTitleFontStyleProperty,
XAxisTitleFontWeightProperty,
XAxisTitleFontSizeProperty,
YAxisValuesProperty,
YAxisLogarithmicScaleProperty,
XAxisCurrentValueProperty,
XAxisMinValueProperty,
XAxisMaxValueProperty,
YAxisOpacityProperty,
YAxisOffsetProperty,
YAxisStrokeProperty,
YAxisStrokeThicknessProperty,
YAxisArrowSizeProperty,
YAxisTitleProperty,
YAxisTitleForegroundProperty,
YAxisTitleOpacityProperty,
YAxisTitleOffsetProperty,
YAxisTitleSizeProperty,
YAxisTitleAlignmentProperty,
YAxisTitleAngleProperty,
YAxisTitleFontFamilyProperty,
YAxisTitleFontStyleProperty,
YAxisTitleFontWeightProperty,
YAxisTitleFontSizeProperty,
CursorStrokeProperty,
CursorStrokeThicknessProperty,
CursorStrokeDashStyleProperty,
CursorStrokeLineCapProperty,
CursorStrokeLineJoinProperty,
CursorStrokeMiterLimitProperty,
BorderBrushProperty,
BorderThicknessProperty,
BorderRadiusXProperty,
BorderRadiusYProperty);
}
// Area
public Thickness AreaMargin
{
get => GetValue(AreaMarginProperty);
set => SetValue(AreaMarginProperty, value);
}
public IBrush? AreaFill
{
get => GetValue(AreaFillProperty);
set => SetValue(AreaFillProperty, value);
}
public IBrush? AreaStroke
{
get => GetValue(AreaStrokeProperty);
set => SetValue(AreaStrokeProperty, value);
}
public double AreaStrokeThickness
{
get => GetValue(AreaStrokeThicknessProperty);
set => SetValue(AreaStrokeThicknessProperty, value);
}
public IDashStyle? AreaStrokeDashStyle
{
get => GetValue(AreaStrokeDashStyleProperty);
set => SetValue(AreaStrokeDashStyleProperty, value);
}
public PenLineCap AreaStrokeLineCap
{
get => GetValue(AreaStrokeLineCapProperty);
set => SetValue(AreaStrokeLineCapProperty, value);
}
public PenLineJoin AreaStrokeLineJoin
{
get => GetValue(AreaStrokeLineJoinProperty);
set => SetValue(AreaStrokeLineJoinProperty, value);
}
public double AreaStrokeMiterLimit
{
get => GetValue(AreaStrokeMiterLimitProperty);
set => SetValue(AreaStrokeMiterLimitProperty, value);
}
public double AreaMinViableHeight
{
get => GetValue(AreaMinViableHeightProperty);
set => SetValue(AreaMinViableHeightProperty, value);
}
public double AreaMinViableWidth
{
get => GetValue(AreaMinViableWidthProperty);
set => SetValue(AreaMinViableWidthProperty, value);
}
// XAxis
public double XAxisCurrentValue
{
get => GetValue(XAxisCurrentValueProperty);
set => SetValue(XAxisCurrentValueProperty, value);
}
public double XAxisMinValue
{
get => GetValue(XAxisMinValueProperty);
set => SetValue(XAxisMinValueProperty, value);
}
public double XAxisMaxValue
{
get => GetValue(XAxisMaxValueProperty);
set => SetValue(XAxisMaxValueProperty, value);
}
public IList<string>? XAxisLabels
{
get => GetValue(XAxisLabelsProperty);
set => SetValue(XAxisLabelsProperty, value);
}
public IList<double>? XAxisValues
{
get => GetValue(XAxisValuesProperty);
set => SetValue(XAxisValuesProperty, value);
}
public double XAxisOpacity
{
get => GetValue(XAxisOpacityProperty);
set => SetValue(XAxisOpacityProperty, value);
}
public Point XAxisOffset
{
get => GetValue(XAxisOffsetProperty);
set => SetValue(XAxisOffsetProperty, value);
}
public IBrush? XAxisStroke
{
get => GetValue(XAxisStrokeProperty);
set => SetValue(XAxisStrokeProperty, value);
}
public double XAxisStrokeThickness
{
get => GetValue(XAxisStrokeThicknessProperty);
set => SetValue(XAxisStrokeThicknessProperty, value);
}
public double XAxisArrowSize
{
get => GetValue(XAxisArrowSizeProperty);
set => SetValue(XAxisArrowSizeProperty, value);
}
public double XAxisMinViableHeight
{
get => GetValue(XAxisMinViableHeightProperty);
set => SetValue(XAxisMinViableHeightProperty, value);
}
public double XAxisMinViableWidth
{
get => GetValue(XAxisMinViableWidthProperty);
set => SetValue(XAxisMinViableWidthProperty, value);
}
// XAxis Label
public IBrush? XAxisLabelForeground
{
get => GetValue(XAxisLabelForegroundProperty);
set => SetValue(XAxisLabelForegroundProperty, value);
}
public double XAxisLabelOpacity
{
get => GetValue(XAxisLabelOpacityProperty);
set => SetValue(XAxisLabelOpacityProperty, value);
}
public double XAxisLabelAngle
{
get => GetValue(XAxisLabelAngleProperty);
set => SetValue(XAxisLabelAngleProperty, value);
}
public Point XAxisLabelOffset
{
get => GetValue(XAxisLabelOffsetProperty);
set => SetValue(XAxisLabelOffsetProperty, value);
}
public Size XAxisLabelSize
{
get => GetValue(XAxisLabelSizeProperty);
set => SetValue(XAxisLabelSizeProperty, value);
}
public TextAlignment XAxisLabelAlignment
{
get => GetValue(XAxisLabelAlignmentProperty);
set => SetValue(XAxisLabelAlignmentProperty, value);
}
public FontFamily XAxisLabelFontFamily
{
get => GetValue(XAxisLabelFontFamilyProperty);
set => SetValue(XAxisLabelFontFamilyProperty, value);
}
public FontStyle XAxisLabelFontStyle
{
get => GetValue(XAxisLabelFontStyleProperty);
set => SetValue(XAxisLabelFontStyleProperty, value);
}
public FontWeight XAxisLabelFontWeight
{
get => GetValue(XAxisLabelFontWeightProperty);
set => SetValue(XAxisLabelFontWeightProperty, value);
}
public double XAxisLabelFontSize
{
get => GetValue(XAxisLabelFontSizeProperty);
set => SetValue(XAxisLabelFontSizeProperty, value);
}
// XAxis Title
public string XAxisTitle
{
get => GetValue(XAxisTitleProperty);
set => SetValue(XAxisTitleProperty, value);
}
public IBrush? XAxisTitleForeground
{
get => GetValue(XAxisTitleForegroundProperty);
set => SetValue(XAxisTitleForegroundProperty, value);
}
public double XAxisTitleOpacity
{
get => GetValue(XAxisTitleOpacityProperty);
set => SetValue(XAxisTitleOpacityProperty, value);
}
public double XAxisTitleAngle
{
get => GetValue(XAxisTitleAngleProperty);
set => SetValue(XAxisTitleAngleProperty, value);
}
public Point XAxisTitleOffset
{
get => GetValue(XAxisTitleOffsetProperty);
set => SetValue(XAxisTitleOffsetProperty, value);
}
public Size XAxisTitleSize
{
get => GetValue(XAxisTitleSizeProperty);
set => SetValue(XAxisTitleSizeProperty, value);
}
public TextAlignment XAxisTitleAlignment
{
get => GetValue(XAxisTitleAlignmentProperty);
set => SetValue(XAxisTitleAlignmentProperty, value);
}
public FontFamily XAxisTitleFontFamily
{
get => GetValue(XAxisTitleFontFamilyProperty);
set => SetValue(XAxisTitleFontFamilyProperty, value);
}
public FontStyle XAxisTitleFontStyle
{
get => GetValue(XAxisTitleFontStyleProperty);
set => SetValue(XAxisTitleFontStyleProperty, value);
}
public FontWeight XAxisTitleFontWeight
{
get => GetValue(XAxisTitleFontWeightProperty);
set => SetValue(XAxisTitleFontWeightProperty, value);
}
public double XAxisTitleFontSize
{
get => GetValue(XAxisTitleFontSizeProperty);
set => SetValue(XAxisTitleFontSizeProperty, value);
}
// YAxis
public IList<double>? YAxisValues
{
get => GetValue(YAxisValuesProperty);
set => SetValue(YAxisValuesProperty, value);
}
public bool YAxisLogarithmicScale
{
get => GetValue(YAxisLogarithmicScaleProperty);
set => SetValue(YAxisLogarithmicScaleProperty, value);
}
public double YAxisOpacity
{
get => GetValue(YAxisOpacityProperty);
set => SetValue(YAxisOpacityProperty, value);
}
public Point YAxisOffset
{
get => GetValue(YAxisOffsetProperty);
set => SetValue(YAxisOffsetProperty, value);
}
public IBrush? YAxisStroke
{
get => GetValue(YAxisStrokeProperty);
set => SetValue(YAxisStrokeProperty, value);
}
public double YAxisStrokeThickness
{
get => GetValue(YAxisStrokeThicknessProperty);
set => SetValue(YAxisStrokeThicknessProperty, value);
}
public double YAxisArrowSize
{
get => GetValue(YAxisArrowSizeProperty);
set => SetValue(YAxisArrowSizeProperty, value);
}
public double YAxisMinViableHeight
{
get => GetValue(YAxisMinViableHeightProperty);
set => SetValue(YAxisMinViableHeightProperty, value);
}
public double YAxisMinViableWidth
{
get => GetValue(YAxisMinViableWidthProperty);
set => SetValue(YAxisMinViableWidthProperty, value);
}
// YAxis Title
public string YAxisTitle
{
get => GetValue(YAxisTitleProperty);
set => SetValue(YAxisTitleProperty, value);
}
public IBrush? YAxisTitleForeground
{
get => GetValue(YAxisTitleForegroundProperty);
set => SetValue(YAxisTitleForegroundProperty, value);
}
public double YAxisTitleOpacity
{
get => GetValue(YAxisTitleOpacityProperty);
set => SetValue(YAxisTitleOpacityProperty, value);
}
public double YAxisTitleAngle
{
get => GetValue(YAxisTitleAngleProperty);
set => SetValue(YAxisTitleAngleProperty, value);
}
public Point YAxisTitleOffset
{
get => GetValue(YAxisTitleOffsetProperty);
set => SetValue(YAxisTitleOffsetProperty, value);
}
public Size YAxisTitleSize
{
get => GetValue(YAxisTitleSizeProperty);
set => SetValue(YAxisTitleSizeProperty, value);
}
public TextAlignment YAxisTitleAlignment
{
get => GetValue(YAxisTitleAlignmentProperty);
set => SetValue(YAxisTitleAlignmentProperty, value);
}
public FontFamily YAxisTitleFontFamily
{
get => GetValue(YAxisTitleFontFamilyProperty);
set => SetValue(YAxisTitleFontFamilyProperty, value);
}
public FontStyle YAxisTitleFontStyle
{
get => GetValue(YAxisTitleFontStyleProperty);
set => SetValue(YAxisTitleFontStyleProperty, value);
}
public FontWeight YAxisTitleFontWeight
{
get => GetValue(YAxisTitleFontWeightProperty);
set => SetValue(YAxisTitleFontWeightProperty, value);
}
public double YAxisTitleFontSize
{
get => GetValue(YAxisTitleFontSizeProperty);
set => SetValue(YAxisTitleFontSizeProperty, value);
}
// Cursor
public IBrush? CursorStroke
{
get => GetValue(CursorStrokeProperty);
set => SetValue(CursorStrokeProperty, value);
}
public double CursorStrokeThickness
{
get => GetValue(CursorStrokeThicknessProperty);
set => SetValue(CursorStrokeThicknessProperty, value);
}
public IDashStyle? CursorStrokeDashStyle
{
get => GetValue(CursorStrokeDashStyleProperty);
set => SetValue(CursorStrokeDashStyleProperty, value);
}
public PenLineCap CursorStrokeLineCap
{
get => GetValue(CursorStrokeLineCapProperty);
set => SetValue(CursorStrokeLineCapProperty, value);
}
public PenLineJoin CursorStrokeLineJoin
{
get => GetValue(CursorStrokeLineJoinProperty);
set => SetValue(CursorStrokeLineJoinProperty, value);
}
public double CursorStrokeMiterLimit
{
get => GetValue(CursorStrokeMiterLimitProperty);
set => SetValue(CursorStrokeMiterLimitProperty, value);
}
// Border
public IBrush? BorderBrush
{
get => GetValue(BorderBrushProperty);
set => SetValue(BorderBrushProperty, value);
}
public double BorderThickness
{
get => GetValue(BorderThicknessProperty);
set => SetValue(BorderThicknessProperty, value);
}
public double BorderRadiusX
{
get => GetValue(BorderRadiusXProperty);
set => SetValue(BorderRadiusXProperty, value);
}
public double BorderRadiusY
{
get => GetValue(BorderRadiusYProperty);
set => SetValue(BorderRadiusYProperty, value);
}
}
}
| |
namespace CSharpCLI {
using System;
using System.Text;
/// <summary>
/// Communication buffer used by Java Gigabase CLI to communicate with server
/// </summary>
internal class ComBuffer {
static Encoding encoder = new UTF8Encoding();
internal static int packShort(byte[] buf, int offs, int val) {
buf[offs++] = (byte)(val >> 8);
buf[offs++] = (byte)val;
return offs;
}
internal static int packInt(byte[] buf, int offs, int val) {
buf[offs++] = (byte)(val >> 24);
buf[offs++] = (byte)(val >> 16);
buf[offs++] = (byte)(val >> 8);
buf[offs++] = (byte)val;
return offs;
}
internal static int packLong(byte[] buf, int offs, long val) {
return packInt(buf, packInt(buf, offs, (int)(val >> 32)), (int)val);
}
internal static int packFloat(byte[] buf, int offs, float value) {
return packInt(buf, offs, BitConverter.ToInt32(BitConverter.GetBytes(value), 0));
}
internal static int packDouble(byte[] buf, int offs, double value) {
return packLong(buf, offs, BitConverter.DoubleToInt64Bits(value));
}
internal static short unpackShort(byte[] buf, int offs) {
return (short)((buf[offs] << 8) + ( buf[offs+1] & 0xFF));
}
internal static int unpackInt(byte[] buf, int offs) {
return (buf[offs] << 24) + (( buf[offs+1] & 0xFF) << 16)
+ ((buf[offs+2] & 0xFF) << 8) + ( buf[offs+3] & 0xFF);
}
internal static long unpackLong(byte[] buf, int offs) {
return ((long)unpackInt(buf, offs) << 32)
+ ((long)unpackInt(buf, offs+4) & 0xFFFFFFFFL);
}
internal static float unpackFloat(byte[] buf, int offs) {
return BitConverter.ToSingle(BitConverter.GetBytes(unpackInt(buf, offs)), 0);
}
internal static double unpackDouble(byte[] buf, int offs) {
return BitConverter.Int64BitsToDouble(unpackLong(buf, offs));
}
internal ComBuffer(Connection.CLICommand cmd, int id) {
int size = 12;
buf = new byte[size];
pos = 0;
putInt(size);
putInt((int)cmd);
putInt(id);
}
internal ComBuffer(Connection.CLICommand cmd) : this(cmd, 0) {}
internal void reset(int size) {
if (buf.Length < size) {
buf = new byte[size];
}
pos = 0;
}
internal void end() {
packInt(buf, 0, pos);
}
internal void extend(int len) {
if (pos + len > buf.Length) {
int newLen = pos + len > len*2 ? pos + len : len*2;
byte[] newBuf = new byte[newLen];
System.Array.Copy(buf, 0, newBuf, 0, buf.Length);
buf = newBuf;
}
}
internal void putByte(int val) {
extend(1);
buf[pos++] = (byte)val;
}
internal void putShort(int val) {
extend(2);
pos = packShort(buf, pos, val);
}
internal void putInt(int val) {
extend(4);
pos = packInt(buf, pos, val);
}
internal void putLong(long val) {
extend(8);
pos = packLong(buf, pos, val);
}
internal void putDouble(double val) {
extend(8);
pos = packDouble(buf, pos, val);
}
internal void putFloat(float val) {
extend(4);
pos = packFloat(buf, pos, val);
}
internal void putRectangle(Rectangle r) {
extend(16);
pos = packInt(buf, pos, r.x0);
pos = packInt(buf, pos, r.y0);
pos = packInt(buf, pos, r.x1);
pos = packInt(buf, pos, r.y1);
}
internal void putAsciiz(String str) {
if (str != null) {
byte[] bytes = encoder.GetBytes(str);
int len = bytes.Length;
int i, j;
extend(len+1);
byte[] dst = buf;
for (i = pos, j = 0; j < len; dst[i++] = bytes[j++]);
dst[i++] = (byte)'\0';
pos = i;
} else {
extend(1);
buf[pos++] = (byte)'\0';
}
}
internal void putByteArray(byte[] arr) {
int len = arr == null ? 0 : arr.Length;
extend(len+4);
pos = packInt(buf, pos, len);
System.Array.Copy(arr, 0, buf, pos, len);
pos += len;
}
internal void putString(String str) {
if (str == null) {
extend(5);
pos = packInt(buf, pos, 1);
} else {
byte[] bytes = encoder.GetBytes(str);
int len = bytes.Length;
extend(len+5);
pos = packInt(buf, pos, len+1);
System.Array.Copy(bytes, 0, buf, pos, len);
pos += len;
}
buf[pos++] = (byte)'\0';
}
internal byte getByte() {
return buf[pos++];
}
internal short getShort() {
short value = unpackShort(buf, pos);
pos += 2;
return value;
}
internal int getInt() {
int value = unpackInt(buf, pos);
pos += 4;
return value;
}
internal long getLong() {
long value = unpackLong(buf, pos);
pos += 8;
return value;
}
internal float getFloat() {
float value = unpackFloat(buf, pos);
pos += 4;
return value;
}
internal double getDouble() {
double value = unpackDouble(buf, pos);
pos += 8;
return value;
}
internal string getAsciiz() {
byte[] p = buf;
int i = pos, j = i;
while (p[j++] != '\0');
pos = j;
return encoder.GetString(p, i, j-i-1);
}
internal string getString() {
int len = getInt();
String value = encoder.GetString(buf, pos, len-1);
pos += len;
return value;
}
internal Rectangle getRectangle() {
Rectangle r = new Rectangle(unpackInt(buf, pos),
unpackInt(buf, pos+4),
unpackInt(buf, pos+8),
unpackInt(buf, pos+12));
pos += 16;
return r;
}
internal byte[] buf;
internal int pos;
}
}
| |
using Orleans.Serialization.Configuration;
using Orleans.Serialization.Session;
using Orleans.Serialization.Utilities;
using Microsoft.Extensions.DependencyInjection;
using System;
using Xunit;
using Microsoft.Extensions.Options;
namespace Orleans.Serialization.UnitTests
{
public class PolymorphismTests
{
private readonly ServiceProvider _serviceProvider;
public PolymorphismTests()
{
_serviceProvider = new ServiceCollection().AddSerializer()
.AddSingleton<IConfigureOptions<TypeManifestOptions>, TypeConfigurationProvider>()
.BuildServiceProvider();
}
private class TypeConfigurationProvider : IConfigureOptions<TypeManifestOptions>
{
public void Configure(TypeManifestOptions configuration)
{
configuration.WellKnownTypeIds[1000] = typeof(SomeBaseClass);
configuration.WellKnownTypeIds[1001] = typeof(SomeSubClass);
configuration.WellKnownTypeIds[1002] = typeof(OtherSubClass);
configuration.WellKnownTypeIds[1003] = typeof(SomeSubClassChild);
}
}
[Fact]
public void ExceptionsAreSerializable()
{
InvalidOperationException exception;
AggregateException aggregateException;
try
{
throw new InvalidOperationException("This is exceptional!");
}
catch (InvalidOperationException ex)
{
exception = ex;
exception.Data.Add("Hi", "yes?");
try
{
throw new AggregateException("This is insane!", ex);
}
catch (AggregateException ag)
{
aggregateException = ag;
}
}
var result = RoundTripToExpectedType<Exception, InvalidOperationException>(exception);
Assert.Equal(exception.Message, result.Message);
Assert.Contains(exception.StackTrace, result.StackTrace);
Assert.Equal(exception.InnerException, result.InnerException);
Assert.NotNull(result.Data);
var data = result.Data;
Assert.True(data.Count == 1);
Assert.Equal("yes?", data["Hi"]);
var agResult = RoundTripToExpectedType<Exception, AggregateException>(aggregateException);
Assert.Equal(aggregateException.Message, agResult.Message);
Assert.Contains(aggregateException.StackTrace, agResult.StackTrace);
var inner = Assert.IsType<InvalidOperationException>(agResult.InnerException);
Assert.Equal(exception.Message, inner.Message);
}
[Fact]
public void GeneratedSerializersRoundTripThroughSerializer_Polymorphic()
{
var original = new SomeSubClass
{ SbcString = "Shaggy", SbcInteger = 13, SscString = "Zoinks!", SscInteger = -1 };
var getSubClassSerializerResult = RoundTripToExpectedType<SomeSubClass, SomeSubClass>(original);
Assert.Equal(original.SscString, getSubClassSerializerResult.SscString);
Assert.Equal(original.SscInteger, getSubClassSerializerResult.SscInteger);
var getBaseClassSerializerResult = RoundTripToExpectedType<SomeBaseClass, SomeSubClass>(original);
Assert.Equal(original.SscString, getBaseClassSerializerResult.SscString);
Assert.Equal(original.SscInteger, getBaseClassSerializerResult.SscInteger);
}
[Fact]
public void GeneratedSerializersRoundTripThroughSerializer_PolymorphicMultiHierarchy()
{
var someSubClass = new SomeSubClass
{ SbcString = "Shaggy", SbcInteger = 13, SscString = "Zoinks!", SscInteger = -1 };
var otherSubClass = new OtherSubClass
{ SbcString = "sbcs", SbcInteger = 2000, OtherSubClassString = "oscs", OtherSubClassInt = 1000 };
var someSubClassChild = new SomeSubClassChild
{ SbcString = "a", SbcInteger = 0, SscString = "Zoinks!", SscInteger = -1, SomeSubClassChildString = "string!", SomeSubClassChildInt = 5858 };
var someSubClassResult = RoundTripToExpectedType<SomeBaseClass, SomeSubClass>(someSubClass);
Assert.Equal(someSubClass.SscString, someSubClassResult.SscString);
Assert.Equal(someSubClass.SscInteger, someSubClassResult.SscInteger);
Assert.Equal(someSubClass.SbcString, someSubClassResult.SbcString);
Assert.Equal(someSubClass.SbcInteger, someSubClassResult.SbcInteger);
var otherSubClassResult = RoundTripToExpectedType<SomeBaseClass, OtherSubClass>(otherSubClass);
Assert.Equal(otherSubClass.OtherSubClassString, otherSubClassResult.OtherSubClassString);
Assert.Equal(otherSubClass.OtherSubClassInt, otherSubClassResult.OtherSubClassInt);
Assert.Equal(otherSubClass.SbcString, otherSubClassResult.SbcString);
Assert.Equal(otherSubClass.SbcInteger, otherSubClassResult.SbcInteger);
var someSubClassChildResult = RoundTripToExpectedType<SomeBaseClass, SomeSubClassChild>(someSubClassChild);
Assert.Equal(someSubClassChild.SomeSubClassChildString, someSubClassChildResult.SomeSubClassChildString);
Assert.Equal(someSubClassChild.SomeSubClassChildInt, someSubClassChildResult.SomeSubClassChildInt);
Assert.Equal(someSubClassChild.SscString, someSubClassChildResult.SscString);
Assert.Equal(someSubClassChild.SscInteger, someSubClassChildResult.SscInteger);
Assert.Equal(someSubClassChild.SbcString, someSubClassChildResult.SbcString);
Assert.Equal(someSubClassChild.SbcInteger, someSubClassChildResult.SbcInteger);
}
[Fact]
public void DeepCopyPolymorphicTypes()
{
var someBaseClass = new SomeBaseClass
{ SbcString = "Shaggy", SbcInteger = 13 };
var someSubClass = new SomeSubClass
{ SbcString = "Shaggy", SbcInteger = 13, SscString = "Zoinks!", SscInteger = -1 };
var otherSubClass = new OtherSubClass
{ SbcString = "sbcs", SbcInteger = 2000, OtherSubClassString = "oscs", OtherSubClassInt = 1000 };
var someSubClassChild = new SomeSubClassChild
{ SbcString = "a", SbcInteger = 0, SscString = "Zoinks!", SscInteger = -1, SomeSubClassChildString = "string!", SomeSubClassChildInt = 5858 };
var someBaseClassResult = DeepCopy(someBaseClass);
Assert.Equal(someBaseClass.SbcString, someBaseClassResult.SbcString);
Assert.Equal(someBaseClass.SbcInteger, someBaseClassResult.SbcInteger);
var someSubClassResult = DeepCopy(someSubClass);
Assert.Equal(someSubClass.SscString, someSubClassResult.SscString);
Assert.Equal(someSubClass.SscInteger, someSubClassResult.SscInteger);
Assert.Equal(someSubClass.SbcString, someSubClassResult.SbcString);
Assert.Equal(someSubClass.SbcInteger, someSubClassResult.SbcInteger);
var otherSubClassResult = DeepCopy(otherSubClass);
Assert.Equal(otherSubClass.OtherSubClassString, otherSubClassResult.OtherSubClassString);
Assert.Equal(otherSubClass.OtherSubClassInt, otherSubClassResult.OtherSubClassInt);
Assert.Equal(otherSubClass.SbcString, otherSubClassResult.SbcString);
Assert.Equal(otherSubClass.SbcInteger, otherSubClassResult.SbcInteger);
var someSubClassChildResult = DeepCopy(someSubClassChild);
Assert.Equal(someSubClassChild.SomeSubClassChildString, someSubClassChildResult.SomeSubClassChildString);
Assert.Equal(someSubClassChild.SomeSubClassChildInt, someSubClassChildResult.SomeSubClassChildInt);
Assert.Equal(someSubClassChild.SscString, someSubClassChildResult.SscString);
Assert.Equal(someSubClassChild.SscInteger, someSubClassChildResult.SscInteger);
Assert.Equal(someSubClassChild.SbcString, someSubClassChildResult.SbcString);
Assert.Equal(someSubClassChild.SbcInteger, someSubClassChildResult.SbcInteger);
}
private TActual RoundTripToExpectedType<TBase, TActual>(TActual original)
where TActual : TBase
{
var serializer = _serviceProvider.GetService<Serializer<TBase>>();
var array = serializer.SerializeToArray(original);
string formatted;
{
using var session = _serviceProvider.GetRequiredService<SerializerSessionPool>().GetSession();
formatted = BitStreamFormatter.Format(array, session);
}
return (TActual)serializer.Deserialize(array);
}
private T DeepCopy<T>(T original)
{
var deepCopier = _serviceProvider.GetService<DeepCopier<T>>();
return deepCopier.Copy(original);
}
[Id(1000)]
[GenerateSerializer]
public class SomeBaseClass
{
[Id(0)]
public string SbcString { get; set; }
[Id(1)]
public int SbcInteger { get; set; }
}
[Id(1001)]
[GenerateSerializer]
public class SomeSubClass : SomeBaseClass
{
[Id(0)]
public int SscInteger { get; set; }
[Id(1)]
public string SscString { get; set; }
}
[Id(1002)]
[GenerateSerializer]
public class OtherSubClass : SomeBaseClass
{
[Id(0)]
public int OtherSubClassInt { get; set; }
[Id(1)]
public string OtherSubClassString { get; set; }
}
[Id(1003)]
[GenerateSerializer]
public class SomeSubClassChild : SomeSubClass
{
[Id(0)]
public int SomeSubClassChildInt { get; set; }
[Id(1)]
public string SomeSubClassChildString { get; set; }
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation.Language;
using System.Runtime.Serialization;
namespace System.Management.Automation
{
/// <summary>
/// Defines the exception thrown when a syntax error occurs while parsing msh script text.
/// </summary>
[Serializable]
public class ParseException : RuntimeException
{
private const string errorIdString = "Parse";
private readonly ParseError[] _errors;
/// <summary>
/// The list of parser errors.
/// </summary>
public ParseError[] Errors
{
get { return _errors; }
}
#region Serialization
/// <summary>
/// Initializes a new instance of the ParseException class and defines the serialization information,
/// and streaming context.
/// </summary>
/// <param name="info">The serialization information to use when initializing this object.</param>
/// <param name="context">The streaming context to use when initializing this object.</param>
/// <returns>Constructed object.</returns>
protected ParseException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
_errors = (ParseError[])info.GetValue("Errors", typeof(ParseError[]));
}
/// <summary>
/// Add private data for serialization.
/// </summary>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new PSArgumentNullException(nameof(info));
}
base.GetObjectData(info, context);
info.AddValue("Errors", _errors);
}
#endregion Serialization
#region ctor
/// <summary>
/// Initializes a new instance of the class ParseException.
/// </summary>
/// <returns>Constructed object.</returns>
public ParseException() : base()
{
base.SetErrorId(errorIdString);
base.SetErrorCategory(ErrorCategory.ParserError);
}
/// <summary>
/// Initializes a new instance of the ParseException class and defines the error message.
/// </summary>
/// <param name="message">The error message to use when initializing this object.</param>
/// <returns>Constructed object.</returns>
public ParseException(string message) : base(message)
{
base.SetErrorId(errorIdString);
base.SetErrorCategory(ErrorCategory.ParserError);
}
/// <summary>
/// Initializes a new instance of the ParseException class and defines the error message and
/// errorID.
/// </summary>
/// <param name="message">The error message to use when initializing this object.</param>
/// <param name="errorId">The errorId to use when initializing this object.</param>
/// <returns>Constructed object.</returns>
internal ParseException(string message, string errorId) : base(message)
{
base.SetErrorId(errorId);
base.SetErrorCategory(ErrorCategory.ParserError);
}
/// <summary>
/// Initializes a new instance of the ParseException class and defines the error message,
/// error ID and inner exception.
/// </summary>
/// <param name="message">The error message to use when initializing this object.</param>
/// <param name="errorId">The errorId to use when initializing this object.</param>
/// <param name="innerException">The inner exception to use when initializing this object.</param>
/// <returns>Constructed object.</returns>
internal ParseException(string message, string errorId, Exception innerException)
: base(message, innerException)
{
base.SetErrorId(errorId);
base.SetErrorCategory(ErrorCategory.ParserError);
}
/// <summary>
/// Initializes a new instance of the ParseException class and defines the error message and
/// inner exception.
/// </summary>
/// <param name="message">The error message to use when initializing this object.</param>
/// <param name="innerException">The inner exception to use when initializing this object.</param>
/// <returns>Constructed object.</returns>
public ParseException(string message,
Exception innerException)
: base(message, innerException)
{
base.SetErrorId(errorIdString);
base.SetErrorCategory(ErrorCategory.ParserError);
}
/// <summary>
/// Initializes a new instance of the ParseException class with a collection of error messages.
/// </summary>
/// <param name="errors">The collection of error messages.</param>
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",
Justification = "ErrorRecord is not overridden in classes deriving from ParseException")]
public ParseException(Language.ParseError[] errors)
{
if ((errors == null) || (errors.Length == 0))
{
throw new ArgumentNullException(nameof(errors));
}
_errors = errors;
// Arbitrarily choose the first error message for the ErrorId.
base.SetErrorId(_errors[0].ErrorId);
base.SetErrorCategory(ErrorCategory.ParserError);
if (errors[0].Extent != null)
this.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errors[0].Extent));
}
#endregion ctor
/// <summary>
/// The error message to display.
/// </summary>
public override string Message
{
get
{
if (_errors == null)
{
return base.Message;
}
// Report at most the first 10 errors
var errorsToReport = (_errors.Length > 10)
? _errors.Take(10).Select(static e => e.ToString()).Append(ParserStrings.TooManyErrors)
: _errors.Select(static e => e.ToString());
return string.Join(Environment.NewLine + Environment.NewLine, errorsToReport);
}
}
}
/// <summary>
/// Defines the exception thrown when a incomplete parse error occurs while parsing msh script text.
/// </summary>
/// <remarks>
/// This is a variation on a parsing error that indicates that the parse was incomplete
/// rather than irrecoverably wrong. A host can catch this exception and then prompt for additional
/// input to complete the parse.
/// </remarks>
[Serializable]
public class IncompleteParseException
: ParseException
{
#region private
private const string errorIdString = "IncompleteParse";
#endregion
#region ctor
#region Serialization
/// <summary>
/// Initializes a new instance of the IncompleteParseException class and defines the serialization information,
/// and streaming context.
/// </summary>
/// <param name="info">The serialization information to use when initializing this object.</param>
/// <param name="context">The streaming context to use when initializing this object.</param>
/// <returns>Constructed object.</returns>
protected IncompleteParseException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
/// <summary>
/// Initializes a new instance of the class IncompleteParseException.
/// </summary>
/// <returns>Constructed object.</returns>
public IncompleteParseException() : base()
{
// Error category is set in base constructor
base.SetErrorId(errorIdString);
}
/// <summary>
/// Initializes a new instance of the IncompleteParseException class and defines the error message.
/// </summary>
/// <param name="message">The error message to use when initializing this object.</param>
/// <returns>Constructed object.</returns>
public IncompleteParseException(string message) : base(message)
{
// Error category is set in base constructor
base.SetErrorId(errorIdString);
}
/// <summary>
/// Initializes a new instance of the IncompleteParseException class and defines the error message and
/// errorID.
/// </summary>
/// <param name="message">The error message to use when initializing this object.</param>
/// <param name="errorId">The errorId to use when initializing this object.</param>
/// <returns>Constructed object.</returns>
internal IncompleteParseException(string message, string errorId) : base(message, errorId)
{
// Error category is set in base constructor
}
/// <summary>
/// Initializes a new instance of the IncompleteParseException class and defines the error message,
/// error ID and inner exception.
/// </summary>
/// <param name="message">The error message to use when initializing this object.</param>
/// <param name="errorId">The errorId to use when initializing this object.</param>
/// <param name="innerException">The inner exception to use when initializing this object.</param>
/// <returns>Constructed object.</returns>
internal IncompleteParseException(string message, string errorId, Exception innerException)
: base(message, errorId, innerException)
{
// Error category is set in base constructor
}
/// <summary>
/// Initializes a new instance of the IncompleteParseException class and defines the error message and
/// inner exception.
/// </summary>
/// <param name="message">The error message to use when initializing this object.</param>
/// <param name="innerException">The inner exception to use when initializing this object.</param>
/// <returns>Constructed object.</returns>
public IncompleteParseException(string message,
Exception innerException)
: base(message, innerException)
{
// Error category is set in base constructor
base.SetErrorId(errorIdString);
}
#endregion ctor
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.RDS.Model
{
/// <summary>
/// <para> Contains the result of a successful invocation of the following actions: </para>
/// <ul>
/// <li> CreateDBInstance </li>
/// <li> DeleteDBInstance </li>
/// <li> ModifyDBInstance </li>
///
/// </ul>
/// <para>This data type is used as a response element in the DescribeDBInstances action.</para>
/// </summary>
public class DBInstance
{
private string dBInstanceIdentifier;
private string dBInstanceClass;
private string engine;
private string dBInstanceStatus;
private string masterUsername;
private string dBName;
private Endpoint endpoint;
private int? allocatedStorage;
private DateTime? instanceCreateTime;
private string preferredBackupWindow;
private int? backupRetentionPeriod;
private List<DBSecurityGroupMembership> dBSecurityGroups = new List<DBSecurityGroupMembership>();
private List<VpcSecurityGroupMembership> vpcSecurityGroups = new List<VpcSecurityGroupMembership>();
private List<DBParameterGroupStatus> dBParameterGroups = new List<DBParameterGroupStatus>();
private string availabilityZone;
private DBSubnetGroup dBSubnetGroup;
private string preferredMaintenanceWindow;
private PendingModifiedValues pendingModifiedValues;
private DateTime? latestRestorableTime;
private bool? multiAZ;
private string engineVersion;
private bool? autoMinorVersionUpgrade;
private string readReplicaSourceDBInstanceIdentifier;
private List<string> readReplicaDBInstanceIdentifiers = new List<string>();
private string licenseModel;
private int? iops;
private List<OptionGroupMembership> optionGroupMemberships = new List<OptionGroupMembership>();
private string characterSetName;
private string secondaryAvailabilityZone;
private bool? publiclyAccessible;
private List<DBInstanceStatusInfo> statusInfos = new List<DBInstanceStatusInfo>();
/// <summary>
/// Contains a user-supplied database identifier. This is the unique key that identifies a DB Instance.
///
/// </summary>
public string DBInstanceIdentifier
{
get { return this.dBInstanceIdentifier; }
set { this.dBInstanceIdentifier = value; }
}
/// <summary>
/// Sets the DBInstanceIdentifier property
/// </summary>
/// <param name="dBInstanceIdentifier">The value to set for the DBInstanceIdentifier property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithDBInstanceIdentifier(string dBInstanceIdentifier)
{
this.dBInstanceIdentifier = dBInstanceIdentifier;
return this;
}
// Check to see if DBInstanceIdentifier property is set
internal bool IsSetDBInstanceIdentifier()
{
return this.dBInstanceIdentifier != null;
}
/// <summary>
/// Contains the name of the compute and memory capacity class of the DB Instance.
///
/// </summary>
public string DBInstanceClass
{
get { return this.dBInstanceClass; }
set { this.dBInstanceClass = value; }
}
/// <summary>
/// Sets the DBInstanceClass property
/// </summary>
/// <param name="dBInstanceClass">The value to set for the DBInstanceClass property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithDBInstanceClass(string dBInstanceClass)
{
this.dBInstanceClass = dBInstanceClass;
return this;
}
// Check to see if DBInstanceClass property is set
internal bool IsSetDBInstanceClass()
{
return this.dBInstanceClass != null;
}
/// <summary>
/// Provides the name of the database engine to be used for this DB Instance.
///
/// </summary>
public string Engine
{
get { return this.engine; }
set { this.engine = value; }
}
/// <summary>
/// Sets the Engine property
/// </summary>
/// <param name="engine">The value to set for the Engine property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithEngine(string engine)
{
this.engine = engine;
return this;
}
// Check to see if Engine property is set
internal bool IsSetEngine()
{
return this.engine != null;
}
/// <summary>
/// Specifies the current state of this database.
///
/// </summary>
public string DBInstanceStatus
{
get { return this.dBInstanceStatus; }
set { this.dBInstanceStatus = value; }
}
/// <summary>
/// Sets the DBInstanceStatus property
/// </summary>
/// <param name="dBInstanceStatus">The value to set for the DBInstanceStatus property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithDBInstanceStatus(string dBInstanceStatus)
{
this.dBInstanceStatus = dBInstanceStatus;
return this;
}
// Check to see if DBInstanceStatus property is set
internal bool IsSetDBInstanceStatus()
{
return this.dBInstanceStatus != null;
}
/// <summary>
/// Contains the master username for the DB Instance.
///
/// </summary>
public string MasterUsername
{
get { return this.masterUsername; }
set { this.masterUsername = value; }
}
/// <summary>
/// Sets the MasterUsername property
/// </summary>
/// <param name="masterUsername">The value to set for the MasterUsername property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithMasterUsername(string masterUsername)
{
this.masterUsername = masterUsername;
return this;
}
// Check to see if MasterUsername property is set
internal bool IsSetMasterUsername()
{
return this.masterUsername != null;
}
/// <summary>
/// The meaning of this parameter differs according to the database engine you use. <b>MySQL</b> Contains the name of the initial database of
/// this instance that was provided at create time, if one was specified when the DB Instance was created. This same name is returned for the
/// life of the DB Instance. Type: String <b>Oracle</b> Contains the Oracle System ID (SID) of the created DB Instance.
///
/// </summary>
public string DBName
{
get { return this.dBName; }
set { this.dBName = value; }
}
/// <summary>
/// Sets the DBName property
/// </summary>
/// <param name="dBName">The value to set for the DBName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithDBName(string dBName)
{
this.dBName = dBName;
return this;
}
// Check to see if DBName property is set
internal bool IsSetDBName()
{
return this.dBName != null;
}
/// <summary>
/// Specifies the connection endpoint.
///
/// </summary>
public Endpoint Endpoint
{
get { return this.endpoint; }
set { this.endpoint = value; }
}
/// <summary>
/// Sets the Endpoint property
/// </summary>
/// <param name="endpoint">The value to set for the Endpoint property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithEndpoint(Endpoint endpoint)
{
this.endpoint = endpoint;
return this;
}
// Check to see if Endpoint property is set
internal bool IsSetEndpoint()
{
return this.endpoint != null;
}
/// <summary>
/// Specifies the allocated storage size specified in gigabytes.
///
/// </summary>
public int AllocatedStorage
{
get { return this.allocatedStorage ?? default(int); }
set { this.allocatedStorage = value; }
}
/// <summary>
/// Sets the AllocatedStorage property
/// </summary>
/// <param name="allocatedStorage">The value to set for the AllocatedStorage property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithAllocatedStorage(int allocatedStorage)
{
this.allocatedStorage = allocatedStorage;
return this;
}
// Check to see if AllocatedStorage property is set
internal bool IsSetAllocatedStorage()
{
return this.allocatedStorage.HasValue;
}
/// <summary>
/// Provides the date and time the DB Instance was created.
///
/// </summary>
public DateTime InstanceCreateTime
{
get { return this.instanceCreateTime ?? default(DateTime); }
set { this.instanceCreateTime = value; }
}
/// <summary>
/// Sets the InstanceCreateTime property
/// </summary>
/// <param name="instanceCreateTime">The value to set for the InstanceCreateTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithInstanceCreateTime(DateTime instanceCreateTime)
{
this.instanceCreateTime = instanceCreateTime;
return this;
}
// Check to see if InstanceCreateTime property is set
internal bool IsSetInstanceCreateTime()
{
return this.instanceCreateTime.HasValue;
}
/// <summary>
/// Specifies the daily time range during which automated backups are created if automated backups are enabled, as determined by the
/// <c>BackupRetentionPeriod</c>.
///
/// </summary>
public string PreferredBackupWindow
{
get { return this.preferredBackupWindow; }
set { this.preferredBackupWindow = value; }
}
/// <summary>
/// Sets the PreferredBackupWindow property
/// </summary>
/// <param name="preferredBackupWindow">The value to set for the PreferredBackupWindow property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithPreferredBackupWindow(string preferredBackupWindow)
{
this.preferredBackupWindow = preferredBackupWindow;
return this;
}
// Check to see if PreferredBackupWindow property is set
internal bool IsSetPreferredBackupWindow()
{
return this.preferredBackupWindow != null;
}
/// <summary>
/// Specifies the number of days for which automatic DB Snapshots are retained.
///
/// </summary>
public int BackupRetentionPeriod
{
get { return this.backupRetentionPeriod ?? default(int); }
set { this.backupRetentionPeriod = value; }
}
/// <summary>
/// Sets the BackupRetentionPeriod property
/// </summary>
/// <param name="backupRetentionPeriod">The value to set for the BackupRetentionPeriod property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithBackupRetentionPeriod(int backupRetentionPeriod)
{
this.backupRetentionPeriod = backupRetentionPeriod;
return this;
}
// Check to see if BackupRetentionPeriod property is set
internal bool IsSetBackupRetentionPeriod()
{
return this.backupRetentionPeriod.HasValue;
}
/// <summary>
/// Provides List of DB Security Group elements containing only <c>DBSecurityGroup.Name</c> and <c>DBSecurityGroup.Status</c> subelements.
///
/// </summary>
public List<DBSecurityGroupMembership> DBSecurityGroups
{
get { return this.dBSecurityGroups; }
set { this.dBSecurityGroups = value; }
}
/// <summary>
/// Adds elements to the DBSecurityGroups collection
/// </summary>
/// <param name="dBSecurityGroups">The values to add to the DBSecurityGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithDBSecurityGroups(params DBSecurityGroupMembership[] dBSecurityGroups)
{
foreach (DBSecurityGroupMembership element in dBSecurityGroups)
{
this.dBSecurityGroups.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the DBSecurityGroups collection
/// </summary>
/// <param name="dBSecurityGroups">The values to add to the DBSecurityGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithDBSecurityGroups(IEnumerable<DBSecurityGroupMembership> dBSecurityGroups)
{
foreach (DBSecurityGroupMembership element in dBSecurityGroups)
{
this.dBSecurityGroups.Add(element);
}
return this;
}
// Check to see if DBSecurityGroups property is set
internal bool IsSetDBSecurityGroups()
{
return this.dBSecurityGroups.Count > 0;
}
/// <summary>
/// Provides List of VPC security group elements that the DB Instance belongs to.
///
/// </summary>
public List<VpcSecurityGroupMembership> VpcSecurityGroups
{
get { return this.vpcSecurityGroups; }
set { this.vpcSecurityGroups = value; }
}
/// <summary>
/// Adds elements to the VpcSecurityGroups collection
/// </summary>
/// <param name="vpcSecurityGroups">The values to add to the VpcSecurityGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithVpcSecurityGroups(params VpcSecurityGroupMembership[] vpcSecurityGroups)
{
foreach (VpcSecurityGroupMembership element in vpcSecurityGroups)
{
this.vpcSecurityGroups.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the VpcSecurityGroups collection
/// </summary>
/// <param name="vpcSecurityGroups">The values to add to the VpcSecurityGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithVpcSecurityGroups(IEnumerable<VpcSecurityGroupMembership> vpcSecurityGroups)
{
foreach (VpcSecurityGroupMembership element in vpcSecurityGroups)
{
this.vpcSecurityGroups.Add(element);
}
return this;
}
// Check to see if VpcSecurityGroups property is set
internal bool IsSetVpcSecurityGroups()
{
return this.vpcSecurityGroups.Count > 0;
}
/// <summary>
/// Provides the list of DB Parameter Groups applied to this DB Instance.
///
/// </summary>
public List<DBParameterGroupStatus> DBParameterGroups
{
get { return this.dBParameterGroups; }
set { this.dBParameterGroups = value; }
}
/// <summary>
/// Adds elements to the DBParameterGroups collection
/// </summary>
/// <param name="dBParameterGroups">The values to add to the DBParameterGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithDBParameterGroups(params DBParameterGroupStatus[] dBParameterGroups)
{
foreach (DBParameterGroupStatus element in dBParameterGroups)
{
this.dBParameterGroups.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the DBParameterGroups collection
/// </summary>
/// <param name="dBParameterGroups">The values to add to the DBParameterGroups collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithDBParameterGroups(IEnumerable<DBParameterGroupStatus> dBParameterGroups)
{
foreach (DBParameterGroupStatus element in dBParameterGroups)
{
this.dBParameterGroups.Add(element);
}
return this;
}
// Check to see if DBParameterGroups property is set
internal bool IsSetDBParameterGroups()
{
return this.dBParameterGroups.Count > 0;
}
/// <summary>
/// Specifies the name of the Availability Zone the DB Instance is located in.
///
/// </summary>
public string AvailabilityZone
{
get { return this.availabilityZone; }
set { this.availabilityZone = value; }
}
/// <summary>
/// Sets the AvailabilityZone property
/// </summary>
/// <param name="availabilityZone">The value to set for the AvailabilityZone property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithAvailabilityZone(string availabilityZone)
{
this.availabilityZone = availabilityZone;
return this;
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this.availabilityZone != null;
}
/// <summary>
/// Provides the inforamtion of the subnet group associated with the DB instance, including the name, descrption and subnets in the subnet
/// group.
///
/// </summary>
public DBSubnetGroup DBSubnetGroup
{
get { return this.dBSubnetGroup; }
set { this.dBSubnetGroup = value; }
}
/// <summary>
/// Sets the DBSubnetGroup property
/// </summary>
/// <param name="dBSubnetGroup">The value to set for the DBSubnetGroup property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithDBSubnetGroup(DBSubnetGroup dBSubnetGroup)
{
this.dBSubnetGroup = dBSubnetGroup;
return this;
}
// Check to see if DBSubnetGroup property is set
internal bool IsSetDBSubnetGroup()
{
return this.dBSubnetGroup != null;
}
/// <summary>
/// Specifies the weekly time range (in UTC) during which system maintenance can occur.
///
/// </summary>
public string PreferredMaintenanceWindow
{
get { return this.preferredMaintenanceWindow; }
set { this.preferredMaintenanceWindow = value; }
}
/// <summary>
/// Sets the PreferredMaintenanceWindow property
/// </summary>
/// <param name="preferredMaintenanceWindow">The value to set for the PreferredMaintenanceWindow property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithPreferredMaintenanceWindow(string preferredMaintenanceWindow)
{
this.preferredMaintenanceWindow = preferredMaintenanceWindow;
return this;
}
// Check to see if PreferredMaintenanceWindow property is set
internal bool IsSetPreferredMaintenanceWindow()
{
return this.preferredMaintenanceWindow != null;
}
/// <summary>
/// Specifies that changes to the DB Instance are pending. This element is only included when changes are pending. Specific changes are
/// identified by subelements.
///
/// </summary>
public PendingModifiedValues PendingModifiedValues
{
get { return this.pendingModifiedValues; }
set { this.pendingModifiedValues = value; }
}
/// <summary>
/// Sets the PendingModifiedValues property
/// </summary>
/// <param name="pendingModifiedValues">The value to set for the PendingModifiedValues property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithPendingModifiedValues(PendingModifiedValues pendingModifiedValues)
{
this.pendingModifiedValues = pendingModifiedValues;
return this;
}
// Check to see if PendingModifiedValues property is set
internal bool IsSetPendingModifiedValues()
{
return this.pendingModifiedValues != null;
}
/// <summary>
/// Specifies the latest time to which a database can be restored with point-in-time restore.
///
/// </summary>
public DateTime LatestRestorableTime
{
get { return this.latestRestorableTime ?? default(DateTime); }
set { this.latestRestorableTime = value; }
}
/// <summary>
/// Sets the LatestRestorableTime property
/// </summary>
/// <param name="latestRestorableTime">The value to set for the LatestRestorableTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithLatestRestorableTime(DateTime latestRestorableTime)
{
this.latestRestorableTime = latestRestorableTime;
return this;
}
// Check to see if LatestRestorableTime property is set
internal bool IsSetLatestRestorableTime()
{
return this.latestRestorableTime.HasValue;
}
/// <summary>
/// Specifies if the DB Instance is a Multi-AZ deployment.
///
/// </summary>
public bool MultiAZ
{
get { return this.multiAZ ?? default(bool); }
set { this.multiAZ = value; }
}
/// <summary>
/// Sets the MultiAZ property
/// </summary>
/// <param name="multiAZ">The value to set for the MultiAZ property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithMultiAZ(bool multiAZ)
{
this.multiAZ = multiAZ;
return this;
}
// Check to see if MultiAZ property is set
internal bool IsSetMultiAZ()
{
return this.multiAZ.HasValue;
}
/// <summary>
/// Indicates the database engine version.
///
/// </summary>
public string EngineVersion
{
get { return this.engineVersion; }
set { this.engineVersion = value; }
}
/// <summary>
/// Sets the EngineVersion property
/// </summary>
/// <param name="engineVersion">The value to set for the EngineVersion property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithEngineVersion(string engineVersion)
{
this.engineVersion = engineVersion;
return this;
}
// Check to see if EngineVersion property is set
internal bool IsSetEngineVersion()
{
return this.engineVersion != null;
}
/// <summary>
/// Indicates that minor version patches are applied automatically.
///
/// </summary>
public bool AutoMinorVersionUpgrade
{
get { return this.autoMinorVersionUpgrade ?? default(bool); }
set { this.autoMinorVersionUpgrade = value; }
}
/// <summary>
/// Sets the AutoMinorVersionUpgrade property
/// </summary>
/// <param name="autoMinorVersionUpgrade">The value to set for the AutoMinorVersionUpgrade property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithAutoMinorVersionUpgrade(bool autoMinorVersionUpgrade)
{
this.autoMinorVersionUpgrade = autoMinorVersionUpgrade;
return this;
}
// Check to see if AutoMinorVersionUpgrade property is set
internal bool IsSetAutoMinorVersionUpgrade()
{
return this.autoMinorVersionUpgrade.HasValue;
}
/// <summary>
/// Contains the identifier of the source DB Instance if this DB Instance is a Read Replica.
///
/// </summary>
public string ReadReplicaSourceDBInstanceIdentifier
{
get { return this.readReplicaSourceDBInstanceIdentifier; }
set { this.readReplicaSourceDBInstanceIdentifier = value; }
}
/// <summary>
/// Sets the ReadReplicaSourceDBInstanceIdentifier property
/// </summary>
/// <param name="readReplicaSourceDBInstanceIdentifier">The value to set for the ReadReplicaSourceDBInstanceIdentifier property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithReadReplicaSourceDBInstanceIdentifier(string readReplicaSourceDBInstanceIdentifier)
{
this.readReplicaSourceDBInstanceIdentifier = readReplicaSourceDBInstanceIdentifier;
return this;
}
// Check to see if ReadReplicaSourceDBInstanceIdentifier property is set
internal bool IsSetReadReplicaSourceDBInstanceIdentifier()
{
return this.readReplicaSourceDBInstanceIdentifier != null;
}
/// <summary>
/// Contains one or more identifiers of the Read Replicas associated with this DB Instance.
///
/// </summary>
public List<string> ReadReplicaDBInstanceIdentifiers
{
get { return this.readReplicaDBInstanceIdentifiers; }
set { this.readReplicaDBInstanceIdentifiers = value; }
}
/// <summary>
/// Adds elements to the ReadReplicaDBInstanceIdentifiers collection
/// </summary>
/// <param name="readReplicaDBInstanceIdentifiers">The values to add to the ReadReplicaDBInstanceIdentifiers collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithReadReplicaDBInstanceIdentifiers(params string[] readReplicaDBInstanceIdentifiers)
{
foreach (string element in readReplicaDBInstanceIdentifiers)
{
this.readReplicaDBInstanceIdentifiers.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the ReadReplicaDBInstanceIdentifiers collection
/// </summary>
/// <param name="readReplicaDBInstanceIdentifiers">The values to add to the ReadReplicaDBInstanceIdentifiers collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithReadReplicaDBInstanceIdentifiers(IEnumerable<string> readReplicaDBInstanceIdentifiers)
{
foreach (string element in readReplicaDBInstanceIdentifiers)
{
this.readReplicaDBInstanceIdentifiers.Add(element);
}
return this;
}
// Check to see if ReadReplicaDBInstanceIdentifiers property is set
internal bool IsSetReadReplicaDBInstanceIdentifiers()
{
return this.readReplicaDBInstanceIdentifiers.Count > 0;
}
/// <summary>
/// License model information for this DB Instance.
///
/// </summary>
public string LicenseModel
{
get { return this.licenseModel; }
set { this.licenseModel = value; }
}
/// <summary>
/// Sets the LicenseModel property
/// </summary>
/// <param name="licenseModel">The value to set for the LicenseModel property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithLicenseModel(string licenseModel)
{
this.licenseModel = licenseModel;
return this;
}
// Check to see if LicenseModel property is set
internal bool IsSetLicenseModel()
{
return this.licenseModel != null;
}
/// <summary>
/// Specifies the Provisioned IOPS (I/O operations per second) value.
///
/// </summary>
public int Iops
{
get { return this.iops ?? default(int); }
set { this.iops = value; }
}
/// <summary>
/// Sets the Iops property
/// </summary>
/// <param name="iops">The value to set for the Iops property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithIops(int iops)
{
this.iops = iops;
return this;
}
// Check to see if Iops property is set
internal bool IsSetIops()
{
return this.iops.HasValue;
}
/// <summary>
/// Provides the list of option group memberships for this DB Instance.
///
/// </summary>
public List<OptionGroupMembership> OptionGroupMemberships
{
get { return this.optionGroupMemberships; }
set { this.optionGroupMemberships = value; }
}
/// <summary>
/// Adds elements to the OptionGroupMemberships collection
/// </summary>
/// <param name="optionGroupMemberships">The values to add to the OptionGroupMemberships collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithOptionGroupMemberships(params OptionGroupMembership[] optionGroupMemberships)
{
foreach (OptionGroupMembership element in optionGroupMemberships)
{
this.optionGroupMemberships.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the OptionGroupMemberships collection
/// </summary>
/// <param name="optionGroupMemberships">The values to add to the OptionGroupMemberships collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithOptionGroupMemberships(IEnumerable<OptionGroupMembership> optionGroupMemberships)
{
foreach (OptionGroupMembership element in optionGroupMemberships)
{
this.optionGroupMemberships.Add(element);
}
return this;
}
// Check to see if OptionGroupMemberships property is set
internal bool IsSetOptionGroupMemberships()
{
return this.optionGroupMemberships.Count > 0;
}
/// <summary>
/// If present, specifies the name of the character set that this instance is associated with.
///
/// </summary>
public string CharacterSetName
{
get { return this.characterSetName; }
set { this.characterSetName = value; }
}
/// <summary>
/// Sets the CharacterSetName property
/// </summary>
/// <param name="characterSetName">The value to set for the CharacterSetName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithCharacterSetName(string characterSetName)
{
this.characterSetName = characterSetName;
return this;
}
// Check to see if CharacterSetName property is set
internal bool IsSetCharacterSetName()
{
return this.characterSetName != null;
}
/// <summary>
/// If present, specifies the name of the secondary Availability Zone for a DB instance with multi-AZ support.
///
/// </summary>
public string SecondaryAvailabilityZone
{
get { return this.secondaryAvailabilityZone; }
set { this.secondaryAvailabilityZone = value; }
}
/// <summary>
/// Sets the SecondaryAvailabilityZone property
/// </summary>
/// <param name="secondaryAvailabilityZone">The value to set for the SecondaryAvailabilityZone property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithSecondaryAvailabilityZone(string secondaryAvailabilityZone)
{
this.secondaryAvailabilityZone = secondaryAvailabilityZone;
return this;
}
// Check to see if SecondaryAvailabilityZone property is set
internal bool IsSetSecondaryAvailabilityZone()
{
return this.secondaryAvailabilityZone != null;
}
/// <summary>
/// Specifies the accessibility options for the DB Instance. A value of true specifies an Internet-facing instance with a publicly resolvable
/// DNS name, which resolves to a public IP address. A value of false specifies an internal instance with a DNS name that resolves to a private
/// IP address. Default: The default behavior varies depending on whether a VPC has been requested or not. The following list shows the default
/// behavior in each case. <ul> <li><b>Default VPC:</b>true</li> <li><b>VPC:</b>false</li> </ul> If no DB subnet group has been specified as
/// part of the request and the PubliclyAccessible value has not been set, the DB instance will be publicly accessible. If a specific DB subnet
/// group has been specified as part of the request and the PubliclyAccessible value has not been set, the DB instance will be private.
///
/// </summary>
public bool PubliclyAccessible
{
get { return this.publiclyAccessible ?? default(bool); }
set { this.publiclyAccessible = value; }
}
/// <summary>
/// Sets the PubliclyAccessible property
/// </summary>
/// <param name="publiclyAccessible">The value to set for the PubliclyAccessible property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithPubliclyAccessible(bool publiclyAccessible)
{
this.publiclyAccessible = publiclyAccessible;
return this;
}
// Check to see if PubliclyAccessible property is set
internal bool IsSetPubliclyAccessible()
{
return this.publiclyAccessible.HasValue;
}
/// <summary>
/// The status of a Read Replica. If the instance is not a for a read replica, this will be blank.
///
/// </summary>
public List<DBInstanceStatusInfo> StatusInfos
{
get { return this.statusInfos; }
set { this.statusInfos = value; }
}
/// <summary>
/// Adds elements to the StatusInfos collection
/// </summary>
/// <param name="statusInfos">The values to add to the StatusInfos collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithStatusInfos(params DBInstanceStatusInfo[] statusInfos)
{
foreach (DBInstanceStatusInfo element in statusInfos)
{
this.statusInfos.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the StatusInfos collection
/// </summary>
/// <param name="statusInfos">The values to add to the StatusInfos collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBInstance WithStatusInfos(IEnumerable<DBInstanceStatusInfo> statusInfos)
{
foreach (DBInstanceStatusInfo element in statusInfos)
{
this.statusInfos.Add(element);
}
return this;
}
// Check to see if StatusInfos property is set
internal bool IsSetStatusInfos()
{
return this.statusInfos.Count > 0;
}
}
}
| |
#region TestSyntaxCheck.cs file
//
// Tests for StaMa state machine controller library
//
// Copyright (c) 2005-2015, Roland Schneider. All rights reserved.
//
#endregion
using System;
using StaMa;
#if !MF_FRAMEWORK
using NUnit.Framework;
#else
using MFUnitTest.Framework;
using Microsoft.SPOT;
#endif
namespace StaMaTest
{
[TestFixture]
public class SyntaxCheckTests
{
const string Transi1 = "Transi1";
const string Transi2 = "Transi2";
const string Transi3 = "Transi3";
const string State1 = "State1";
const string State2 = "State2";
const string State1a1 = "State1a1";
const string State1a2 = "State1a2";
const string State1a2a1 = "State1a2a1";
const string State1a2a2 = "State1a2a2";
const string State2a1 = "State2a1";
const string State2a2 = "State2a2";
const string State1b1 = "State1b1";
const string State1b2 = "State1b2";
const string State1a1a1 = "State1a1a1";
const string State1a1a2 = "State1a1a2";
const string State2a1a1 = "State2a1a1";
const string State2a1a2 = "State2a1a2";
private struct TestData
{
public TestData(string stateName, bool expectedIsValid)
{
StateName = stateName;
ExpectedIsValid = expectedIsValid;
}
public string StateName;
public bool ExpectedIsValid;
}
[Test]
public void IsValidIdentifier_WithSuspectStateNames_ReturnsExpected()
{
TestData[] testDataArray = new TestData[]
{
new TestData("", false),
new TestData("&", false),
new TestData("6", true),
new TestData("_", true),
new TestData("__", true),
new TestData("__6", true),
new TestData("__b", true),
new TestData("B_", true),
new TestData("6B", false),
new TestData("B6", true),
new TestData("__X", true),
new TestData("X", true),
new TestData("X\nx", false),
};
foreach (TestData testData in testDataArray)
{
bool isValid = StateMachineTemplate.IsValidIdentifier(testData.StateName);
Assert.That(isValid, Is.EqualTo(testData.ExpectedIsValid), "Test string \"" + testData.StateName + "\" didn't match expectation.");
}
}
[Test]
public void IsValidIdentifier_WithNull_Throws()
{
Assert.That(() => { StateMachineTemplate.IsValidIdentifier(null); }, Throws.TypeOf(typeof(ArgumentNullException)));
}
[Test]
public void StateMachineTemplate_WithValidStructure_IsInitialized()
{
// Set up a typical tree without problems
StateMachineTemplate t = new StateMachineTemplate();
t.Region(State1, false);
t.State(State1);
t.Region(State1a1, false);
t.State(State1a1);
t.EndState();
t.State(State1a2);
t.Region(State1a2a1, false);
t.State(State1a2a1);
t.Transition(Transi3, new string[] { State1a2a1 }, new string[] { State1a2a2 }, 1, null, null);
t.EndState();
t.State(State1a2a2);
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
t.Region(State1b1, false);
t.State(State1b1);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State2);
t.EndState();
t.EndRegion();
Assert.That(t.Root, Is.Not.Null, "State machine template not complete.");
Assert.That(t.StateConfigurationMax, Is.EqualTo(4), "StateConfigurationMax wrong");
Assert.That(t.ConcurrencyDegree, Is.EqualTo(2), "ConcurrencyDegree wrong");
Assert.That(t.HistoryMax, Is.EqualTo(0), "HistoryMax wrong");
}
[Test]
public void StateMachineTemplate_WithValidStructure2_IsInitialized()
{
// Set up a typical tree without problems
StateMachineTemplate t = new StateMachineTemplate();
t.Region(State1, false);
t.State(State1);
t.Transition(Transi1, new string[] { State1 }, new string[] { State2 }, 1, null, null);
t.Region(State1a1, true);
t.State(State1a1);
t.Transition(Transi3, new string[] { State1a1 }, new string[] { State1a2 }, 1, null, null);
t.EndState();
t.State(State1a2);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State2);
t.Transition(Transi2, new string[] { State2 }, new string[] { State1 }, 1, null, null);
t.EndState();
t.EndRegion();
Assert.That(t.Root, Is.Not.Null, "State machine template not complete.");
Assert.That(t.StateConfigurationMax, Is.EqualTo(2), "StateConfigurationMax wrong");
Assert.That(t.ConcurrencyDegree, Is.EqualTo(1), "ConcurrencyDegree wrong");
Assert.That(t.HistoryMax, Is.EqualTo(1), "HistoryMax wrong");
}
[Test]
public void StateMachineTemplate_WithOpenRegion_IsNotInitialized()
{
StateMachineTemplate t = new StateMachineTemplate();
t.Region(State1, false);
Assert.That(t.Root, Is.Null, "Unexpected StateMachineTemplate initialization.");
}
[Test]
public void StateMachineTemplate_WithOpenRegionAndStates_IsNotInitialized()
{
StateMachineTemplate t = new StateMachineTemplate();
t.Region(State1, false);
t.State(State1);
t.EndState();
Assert.That(t.Root, Is.Null, "Unexpected StateMachineTemplate initialization.");
}
[Test]
public void StateMachineTemplate_WithMissingEndState_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
t.Region(State1, false);
t.State(State1);
// t.EndState() omitted.
Assert.That(() => { t.State(State2); }, Throws.TypeOf(typeof(StateMachineException)));
}
[Test]
public void StateMachineTemplate_WithMissingEndRegion_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
t.Region(State1, false);
t.State(State1);
t.Region(State1a1, false);
t.State(State1a1);
t.EndState();
// t.EndRegion() omitted.
Assert.That(() => { t.Region(State1b1, false); }, Throws.TypeOf(typeof(StateMachineException)));
}
[Test]
public void StateMachineTemplate_WithMissingCompositeState_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
t.Region(State1, false);
// t.State(State1) omitted.
Assert.That(() => { t.Region(State2, false); }, Throws.TypeOf(typeof(StateMachineException)));
}
[Test]
public void StateMachineTemplate_EndRegionWithoutRegion_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
Assert.That(() => { t.EndRegion(); }, Throws.TypeOf(typeof(StateMachineException)));
}
[Test]
public void StateMachineTemplate_NestedEndRegionWithoutRegion_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
t.Region(State1, false);
t.State(State1);
// t.EndState() omitted.
Assert.That(() => { t.EndRegion(); }, Throws.TypeOf(typeof(StateMachineException)));
}
[Test]
public void StateMachineTemplate_WithConflictingTransitionTargetStateDefinition_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
Exception thrownException = null;
try
{
//## Begin BadTransiTargetsTest1
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_SyntaxCheckTests"
// at 07-22-2015 22:05:03 using StaMaShapes Version 2300
t.Region(State1, false);
t.State(State1, null, null);
t.Region(State1a1, false);
t.State(State1a1, null, null);
t.Region(State1a1a1, false);
t.State(State1a1a1, null, null);
t.EndState();
t.State(State1a1a2, null, null);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State1a2, null, null);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State2, null, null);
t.Transition(Transi1, new string[] {State1a1, State1a2}, 1, null, null);
t.EndState();
t.EndRegion();
//## End BadTransiTargetsTest1
}
catch (Exception ex)
{
thrownException = ex;
}
Assert.That(thrownException, Is.Not.Null);
Assert.That(thrownException.GetType(), Is.EqualTo(typeof(StateMachineException)));
}
[Test]
public void StateMachineTemplate_WithTransitionSourceNotContainedInTransitionAnchor_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
Exception thrownException = null;
try
{
//## Begin BadTransiTargetsTest2
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_SyntaxCheckTests"
// at 07-22-2015 22:05:03 using StaMaShapes Version 2300
t.Region(State1, false);
t.State(State1, null, null);
t.Region(State1a1, false);
t.State(State1a1, null, null);
t.Transition(Transi1, State1, State2, 1, null, null);
t.Region(State1a1a1, false);
t.State(State1a1a1, null, null);
t.EndState();
t.State(State1a1a2, null, null);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State1a2, null, null);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State2, null, null);
t.EndState();
t.EndRegion();
//## End BadTransiTargetsTest2
}
catch (Exception ex)
{
thrownException = ex;
}
Assert.That(thrownException, Is.Not.Null);
Assert.That(thrownException.GetType(), Is.EqualTo(typeof(StateMachineException)));
}
[Test]
public void StateMachineTemplate_WithTransitionSourceNotContainedInTransitionAnchor2_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
Exception thrownException = null;
try
{
//## Begin BadTransiTargetsTest3
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_SyntaxCheckTests"
// at 07-22-2015 22:05:03 using StaMaShapes Version 2300
t.Region(State1, false);
t.State(State1, null, null);
t.Transition(Transi1, State2, State1, 1, null, null);
t.Region(State1a1, false);
t.State(State1a1, null, null);
t.Region(State1a1a1, false);
t.State(State1a1a1, null, null);
t.EndState();
t.State(State1a1a2, null, null);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State1a2, null, null);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State2, null, null);
t.EndState();
t.EndRegion();
//## End BadTransiTargetsTest3
}
catch (Exception ex)
{
thrownException = ex;
}
Assert.That(thrownException, Is.Not.Null);
Assert.That(thrownException.GetType(), Is.EqualTo(typeof(StateMachineException)));
}
[Test]
public void StateMachineTemplate_WithTransitionSourceNotContainedInTransitionAnchor3_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
Exception thrownException = null;
try
{
//## Begin BadTransiTargetsTest4
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_SyntaxCheckTests"
// at 07-22-2015 22:05:03 using StaMaShapes Version 2300
t.Region(State1, false);
t.State(State1, null, null);
t.Transition(Transi1, State2a1a1, State1, 1, null, null);
t.Region(State1a1, false);
t.State(State1a1, null, null);
t.Region(State1a1a1, false);
t.State(State1a1a1, null, null);
t.EndState();
t.State(State1a1a2, null, null);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State1a2, null, null);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State2, null, null);
t.Region(State2a1, false);
t.State(State2a1, null, null);
t.Region(State2a1a1, false);
t.State(State2a1a1, null, null);
t.EndState();
t.State(State2a1a2, null, null);
t.EndState();
t.EndRegion();
t.EndState();
t.State(State2a2, null, null);
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
//## End BadTransiTargetsTest4
}
catch (Exception ex)
{
thrownException = ex;
}
Assert.That(thrownException, Is.Not.Null);
Assert.That(thrownException.GetType(), Is.EqualTo(typeof(StateMachineException)));
}
[Test]
public void StateMachineTemplate_WithDuplicateStateName_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
t.Region(State1, false);
t.State(State1);
t.EndState();
t.State(State2);
t.Region(State2a1, false);
t.State(State2a1);
t.EndState();
Assert.That(() => { t.State(State1); }, Throws.TypeOf(typeof(ArgumentOutOfRangeException)));
}
[Test]
public void StateMachineTemplate_WithDuplicateTransitionName_Throws()
{
StateMachineTemplate t = new StateMachineTemplate();
t.Region(State1, false);
t.State(State1);
t.Transition(Transi1, new string[] { State1 }, new string[] { State2 }, 1, null, null);
Assert.That(() => { t.Transition(Transi1, new string[] { State1 }, new string[] { State2 }, 1, null, null); }, Throws.TypeOf(typeof(ArgumentOutOfRangeException)));
}
}
}
| |
//
// Mono.Data.SqliteClient.Sqlite.cs
//
// Provides C# bindings to the library sqlite.dll
//
// Everaldo Canuto <everaldo_canuto@yahoo.com.br>
// Chris Turchin <chris@turchin.net>
// Jeroen Zwartepoorte <jeroen@xs4all.nl>
// Thomas Zoechling <thomas.zoechling@gmx.at>
//
// Copyright (C) 2004 Everaldo Canuto
//
// 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.Security;
using System.Runtime.InteropServices;
using System.Text;
namespace Mono.Data.SqliteClient
{
/// <summary>
/// Represents the return values for sqlite_exec() and sqlite_step()
/// </summary>
internal enum SqliteError : int {
/// <value>Successful result</value>
OK = 0,
/// <value>SQL error or missing database</value>
ERROR = 1,
/// <value>An internal logic error in SQLite</value>
INTERNAL = 2,
/// <value>Access permission denied</value>
PERM = 3,
/// <value>Callback routine requested an abort</value>
ABORT = 4,
/// <value>The database file is locked</value>
BUSY = 5,
/// <value>A table in the database is locked</value>
LOCKED = 6,
/// <value>A malloc() failed</value>
NOMEM = 7,
/// <value>Attempt to write a readonly database</value>
READONLY = 8,
/// <value>Operation terminated by public const int interrupt()</value>
INTERRUPT = 9,
/// <value>Some kind of disk I/O error occurred</value>
IOERR = 10,
/// <value>The database disk image is malformed</value>
CORRUPT = 11,
/// <value>(Internal Only) Table or record not found</value>
NOTFOUND = 12,
/// <value>Insertion failed because database is full</value>
FULL = 13,
/// <value>Unable to open the database file</value>
CANTOPEN = 14,
/// <value>Database lock protocol error</value>
PROTOCOL = 15,
/// <value>(Internal Only) Database table is empty</value>
EMPTY = 16,
/// <value>The database schema changed</value>
SCHEMA = 17,
/// <value>Too much data for one row of a table</value>
TOOBIG = 18,
/// <value>Abort due to contraint violation</value>
CONSTRAINT= 19,
/// <value>Data type mismatch</value>
MISMATCH = 20,
/// <value>Library used incorrectly</value>
MISUSE = 21,
/// <value>Uses OS features not supported on host</value>
NOLFS = 22,
/// <value>Authorization denied</value>
AUTH = 23,
/// <value>Auxiliary database format error</value>
FORMAT = 24,
/// <value>2nd parameter to sqlite_bind out of range</value>
RANGE = 25,
/// <value>File opened that is not a database file</value>
NOTADB = 26,
/// <value>sqlite_step() has another row ready</value>
ROW = 100,
/// <value>sqlite_step() has finished executing</value>
DONE = 101
}
/// <summary>
/// Provides the core of C# bindings to the library sqlite.dll
/// </summary>
internal sealed class Sqlite {
#region PInvoke Functions
[DllImport("sqlite")]
internal static extern IntPtr sqlite_open (string dbname, int db_mode, out IntPtr errstr);
[DllImport("sqlite")]
internal static extern void sqlite_close (IntPtr sqlite_handle);
[DllImport("sqlite")]
internal static extern int sqlite_changes (IntPtr handle);
[DllImport("sqlite")]
internal static extern int sqlite_last_insert_rowid (IntPtr sqlite_handle);
[DllImport ("sqlite")]
internal static extern void sqliteFree (IntPtr ptr);
[DllImport ("sqlite")]
internal static extern SqliteError sqlite_compile (IntPtr sqlite_handle, IntPtr zSql, out IntPtr pzTail, out IntPtr pVm, out IntPtr errstr);
[DllImport ("sqlite")]
internal static extern SqliteError sqlite_step (IntPtr pVm, out int pN, out IntPtr pazValue, out IntPtr pazColName);
[DllImport ("sqlite")]
internal static extern SqliteError sqlite_finalize (IntPtr pVm, out IntPtr pzErrMsg);
[DllImport ("sqlite")]
internal static extern SqliteError sqlite_exec (IntPtr handle, string sql, IntPtr callback, IntPtr user_data, out IntPtr errstr_ptr);
[DllImport ("sqlite")]
internal static extern void sqlite_busy_timeout (IntPtr handle, int ms);
[DllImport("sqlite3", CharSet = CharSet.Unicode)]
internal static extern int sqlite3_open16 (string dbname, out IntPtr handle);
[DllImport("sqlite3")]
internal static extern void sqlite3_close (IntPtr sqlite_handle);
[DllImport("sqlite3")]
internal static extern IntPtr sqlite3_errmsg16 (IntPtr sqlite_handle);
[DllImport("sqlite3")]
internal static extern int sqlite3_changes (IntPtr handle);
[DllImport("sqlite3")]
internal static extern long sqlite3_last_insert_rowid (IntPtr sqlite_handle);
[DllImport ("sqlite3")]
internal static extern SqliteError sqlite3_prepare16 (IntPtr sqlite_handle, IntPtr zSql, int zSqllen, out IntPtr pVm, out IntPtr pzTail);
[DllImport ("sqlite3")]
internal static extern SqliteError sqlite3_step (IntPtr pVm);
[DllImport ("sqlite3")]
internal static extern SqliteError sqlite3_finalize (IntPtr pVm);
[DllImport ("sqlite3")]
internal static extern SqliteError sqlite3_exec (IntPtr handle, string sql, IntPtr callback, IntPtr user_data, out IntPtr errstr_ptr);
[DllImport ("sqlite3")]
internal static extern IntPtr sqlite3_column_name16 (IntPtr pVm, int col);
[DllImport ("sqlite3")]
internal static extern IntPtr sqlite3_column_text16 (IntPtr pVm, int col);
[DllImport ("sqlite3")]
internal static extern IntPtr sqlite3_column_blob (IntPtr pVm, int col);
[DllImport ("sqlite3")]
internal static extern int sqlite3_column_bytes16 (IntPtr pVm, int col);
[DllImport ("sqlite3")]
internal static extern int sqlite3_column_count (IntPtr pVm);
[DllImport ("sqlite3")]
internal static extern int sqlite3_column_type (IntPtr pVm, int col);
[DllImport ("sqlite3")]
internal static extern Int64 sqlite3_column_int64 (IntPtr pVm, int col);
[DllImport ("sqlite3")]
internal static extern double sqlite3_column_double (IntPtr pVm, int col);
[DllImport ("sqlite3")]
internal static extern IntPtr sqlite3_column_decltype16 (IntPtr pVm, int col);
[DllImport ("sqlite3")]
internal static extern int sqlite3_bind_parameter_count (IntPtr pStmt);
[DllImport ("sqlite3")]
internal static extern IntPtr sqlite3_bind_parameter_name (IntPtr pStmt, int n); // UTF-8 encoded return
[DllImport ("sqlite3")]
internal static extern SqliteError sqlite3_bind_blob (IntPtr pStmt, int n, byte[] blob, int length, IntPtr freetype);
[DllImport ("sqlite3")]
internal static extern SqliteError sqlite3_bind_double (IntPtr pStmt, int n, double value);
[DllImport ("sqlite3")]
internal static extern SqliteError sqlite3_bind_int (IntPtr pStmt, int n, int value);
[DllImport ("sqlite3")]
internal static extern SqliteError sqlite3_bind_int64 (IntPtr pStmt, int n, long value);
[DllImport ("sqlite3")]
internal static extern SqliteError sqlite3_bind_null (IntPtr pStmt, int n);
[DllImport ("sqlite3", CharSet = CharSet.Unicode)]
internal static extern SqliteError sqlite3_bind_text16 (IntPtr pStmt, int n, string value, int length, IntPtr freetype);
[DllImport ("sqlite3")]
internal static extern void sqlite3_busy_timeout (IntPtr handle, int ms);
#endregion
// These are adapted from Mono.Unix. When encoding is null,
// use Ansi encoding, which is a superset of the default
// expected encoding (ISO-8859-1).
public static IntPtr StringToHeap (string s, Encoding encoding)
{
if (encoding == null)
return Marshal.StringToHGlobalAnsi (s);
int min_byte_count = encoding.GetMaxByteCount(1);
char[] copy = s.ToCharArray ();
byte[] marshal = new byte [encoding.GetByteCount (copy) + min_byte_count];
int bytes_copied = encoding.GetBytes (copy, 0, copy.Length, marshal, 0);
if (bytes_copied != (marshal.Length-min_byte_count))
throw new NotSupportedException ("encoding.GetBytes() doesn't equal encoding.GetByteCount()!");
IntPtr mem = Marshal.AllocHGlobal (marshal.Length);
if (mem == IntPtr.Zero)
throw new OutOfMemoryException ();
bool copied = false;
try {
Marshal.Copy (marshal, 0, mem, marshal.Length);
copied = true;
}
finally {
if (!copied)
Marshal.FreeHGlobal (mem);
}
return mem;
}
public static unsafe string HeapToString (IntPtr p, Encoding encoding)
{
if (encoding == null)
return Marshal.PtrToStringAnsi (p);
if (p == IntPtr.Zero)
return null;
// This assumes a single byte terminates the string.
int len = 0;
while (Marshal.ReadByte (p, len) != 0)
checked {++len;}
string s = new string ((sbyte*) p, 0, len, encoding);
len = s.Length;
while (len > 0 && s [len-1] == 0)
--len;
if (len == s.Length)
return s;
return s.Substring (0, len);
}
}
}
| |
/******************************************************************************
*
* Name: GdalConfiguration.cs.pp
* Project: GDAL CSharp Interface
* Purpose: A static configuration utility class to enable GDAL/OGR.
* Author: Felix Obermaier
*
******************************************************************************
* Copyright (c) 2012-2018, Felix Obermaier
*
* 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.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Gdal = OSGeo.GDAL.Gdal;
using Ogr = OSGeo.OGR.Ogr;
namespace gView.DataSources.GDAL
{
public static partial class GdalConfiguration
{
private static volatile bool _configuredOgr;
private static volatile bool _configuredGdal;
private static volatile bool _usable;
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetDefaultDllDirectories(uint directoryFlags);
// LOAD_LIBRARY_SEARCH_USER_DIRS | LOAD_LIBRARY_SEARCH_SYSTEM32
private const uint DllSearchFlags = 0x00000400 | 0x00000800;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AddDllDirectory(string lpPathName);
/// <summary>
/// Construction of Gdal/Ogr
/// </summary>
static GdalConfiguration()
{
string executingDirectory = null, gdalPath = null, nativePath = null;
try
{
if (!IsWindows)
{
const string notSet = "_Not_set_";
string tmp = Gdal.GetConfigOption("GDAL_DATA", notSet);
_usable = tmp != notSet;
return;
}
string executingAssemblyFile = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath;
executingDirectory = Path.GetDirectoryName(executingAssemblyFile);
if (string.IsNullOrEmpty(executingDirectory))
throw new InvalidOperationException("cannot get executing directory");
// modify search place and order
SetDefaultDllDirectories(DllSearchFlags);
gdalPath = Path.Combine(executingDirectory, "gdal");
nativePath = Path.Combine(gdalPath, GetPlatform());
if (!Directory.Exists(nativePath))
throw new DirectoryNotFoundException($"GDAL native directory not found at '{nativePath}'");
if (!File.Exists(Path.Combine(nativePath, "gdal_wrap.dll")))
throw new FileNotFoundException(
$"GDAL native wrapper file not found at '{Path.Combine(nativePath, "gdal_wrap.dll")}'");
// Add directories
AddDllDirectory(nativePath);
AddDllDirectory(Path.Combine(nativePath, "plugins"));
// Set the additional GDAL environment variables.
string gdalData = Path.Combine(gdalPath, "data");
Environment.SetEnvironmentVariable("GDAL_DATA", gdalData);
Gdal.SetConfigOption("GDAL_DATA", gdalData);
string driverPath = Path.Combine(nativePath, "plugins");
Environment.SetEnvironmentVariable("GDAL_DRIVER_PATH", driverPath);
Gdal.SetConfigOption("GDAL_DRIVER_PATH", driverPath);
Environment.SetEnvironmentVariable("GEOTIFF_CSV", gdalData);
Gdal.SetConfigOption("GEOTIFF_CSV", gdalData);
string projSharePath = Path.Combine(gdalPath, "share");
Environment.SetEnvironmentVariable("PROJ_LIB", projSharePath);
Gdal.SetConfigOption("PROJ_LIB", projSharePath);
_usable = true;
}
catch (Exception e)
{
_usable = false;
Trace.WriteLine(e, "error");
Trace.WriteLine($"Executing directory: {executingDirectory}", "error");
Trace.WriteLine($"gdal directory: {gdalPath}", "error");
Trace.WriteLine($"native directory: {nativePath}", "error");
//throw;
}
}
/// <summary>
/// Gets a value indicating if the GDAL package is set up properly.
/// </summary>
public static bool Usable
{
get { return _usable; }
}
/// <summary>
/// Method to ensure the static constructor is being called.
/// </summary>
/// <remarks>Be sure to call this function before using Gdal/Ogr/Osr</remarks>
public static void ConfigureOgr()
{
if (!_usable) return;
if (_configuredOgr) return;
// Register drivers
Ogr.RegisterAll();
_configuredOgr = true;
PrintDriversOgr();
}
/// <summary>
/// Method to ensure the static constructor is being called.
/// </summary>
/// <remarks>Be sure to call this function before using Gdal/Ogr/Osr</remarks>
public static void ConfigureGdal()
{
if (!_usable) return;
if (_configuredGdal) return;
// Register drivers
Gdal.AllRegister();
_configuredGdal = true;
PrintDriversGdal();
}
/// <summary>
/// Function to determine which platform we're on
/// </summary>
private static string GetPlatform()
{
return Environment.Is64BitProcess ? "x64" : "x86";
}
/// <summary>
/// Gets a value indicating if we are on a windows platform
/// </summary>
private static bool IsWindows
{
get
{
var res = !(Environment.OSVersion.Platform == PlatformID.Unix ||
Environment.OSVersion.Platform == PlatformID.MacOSX);
return res;
}
}
private static void PrintDriversOgr()
{
#if DEBUG
if (_usable)
{
var num = Ogr.GetDriverCount();
for (var i = 0; i < num; i++)
{
var driver = Ogr.GetDriver(i);
Trace.WriteLine($"OGR {i}: {driver.GetName()}", "Debug");
}
}
#endif
}
private static void PrintDriversGdal()
{
#if DEBUG
if (_usable)
{
var num = Gdal.GetDriverCount();
for (var i = 0; i < num; i++)
{
var driver = Gdal.GetDriver(i);
Trace.WriteLine($"GDAL {i}: {driver.ShortName}-{driver.LongName}");
}
}
#endif
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: CircInfo
// ObjectType: CircInfo
// CSLAType: ReadOnlyObject
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
namespace DocStore.Business.Circulations
{
/// <summary>
/// Circulation of document or folder (read only object).<br/>
/// This is a generated <see cref="CircInfo"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="CircList"/> collection.
/// </remarks>
[Serializable]
public partial class CircInfo : ReadOnlyBase<CircInfo>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="CircID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CircIDProperty = RegisterProperty<int>(p => p.CircID, "Circ ID", -1);
/// <summary>
/// Gets the Circ ID.
/// </summary>
/// <value>The Circ ID.</value>
public int CircID
{
get { return GetProperty(CircIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DocID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> DocIDProperty = RegisterProperty<int?>(p => p.DocID, "Doc ID", null);
/// <summary>
/// Gets the Doc ID.
/// </summary>
/// <value>The Doc ID.</value>
public int? DocID
{
get { return GetProperty(DocIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="FolderID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> FolderIDProperty = RegisterProperty<int?>(p => p.FolderID, "Folder ID", null);
/// <summary>
/// Gets the Folder ID.
/// </summary>
/// <value>The Folder ID.</value>
public int? FolderID
{
get { return GetProperty(FolderIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="NeedsReply"/> property.
/// </summary>
public static readonly PropertyInfo<bool> NeedsReplyProperty = RegisterProperty<bool>(p => p.NeedsReply, "Needs Reply");
/// <summary>
/// Gets the Needs Reply.
/// </summary>
/// <value><c>true</c> if Needs Reply; otherwise, <c>false</c>.</value>
public bool NeedsReply
{
get { return GetProperty(NeedsReplyProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="NeedsReplyDecision"/> property.
/// </summary>
public static readonly PropertyInfo<bool> NeedsReplyDecisionProperty = RegisterProperty<bool>(p => p.NeedsReplyDecision, "Needs Reply Decision");
/// <summary>
/// Gets the Needs Reply Decision.
/// </summary>
/// <value><c>true</c> if Needs Reply Decision; otherwise, <c>false</c>.</value>
public bool NeedsReplyDecision
{
get { return GetProperty(NeedsReplyDecisionProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CircTypeTag"/> property.
/// </summary>
public static readonly PropertyInfo<string> CircTypeTagProperty = RegisterProperty<string>(p => p.CircTypeTag, "Circ Type Tag");
/// <summary>
/// Gets the Circ Type Tag.
/// </summary>
/// <value>The Circ Type Tag.</value>
public string CircTypeTag
{
get { return GetProperty(CircTypeTagProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="SenderEntityID"/> property.
/// </summary>
public static readonly PropertyInfo<int?> SenderEntityIDProperty = RegisterProperty<int?>(p => p.SenderEntityID, "Sender Entity ID", null);
/// <summary>
/// Gets the Sender Entity ID.
/// </summary>
/// <value>The Sender Entity ID.</value>
public int? SenderEntityID
{
get { return GetProperty(SenderEntityIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="SentDateTime"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> SentDateTimeProperty = RegisterProperty<SmartDate>(p => p.SentDateTime, "Sent Date Time", null);
/// <summary>
/// Gets the Sent Date Time.
/// </summary>
/// <value>The Sent Date Time.</value>
public SmartDate SentDateTime
{
get { return GetProperty(SentDateTimeProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DaysToReply"/> property.
/// </summary>
public static readonly PropertyInfo<short> DaysToReplyProperty = RegisterProperty<short>(p => p.DaysToReply, "Days To Reply");
/// <summary>
/// Gets the Days To Reply.
/// </summary>
/// <value>The Days To Reply.</value>
public short DaysToReply
{
get { return GetProperty(DaysToReplyProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="DaysToLive"/> property.
/// </summary>
public static readonly PropertyInfo<short> DaysToLiveProperty = RegisterProperty<short>(p => p.DaysToLive, "Days To Live");
/// <summary>
/// Gets the Days To Live.
/// </summary>
/// <value>The Days To Live.</value>
public short DaysToLive
{
get { return GetProperty(DaysToLiveProperty); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="CircInfo"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="CircInfo"/> object.</returns>
internal static CircInfo GetCircInfo(SafeDataReader dr)
{
CircInfo obj = new CircInfo();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="CircInfo"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public CircInfo()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="CircInfo"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(CircIDProperty, dr.GetInt32("CircID"));
LoadProperty(DocIDProperty, (int?)dr.GetValue("DocID"));
LoadProperty(FolderIDProperty, (int?)dr.GetValue("FolderID"));
LoadProperty(NeedsReplyProperty, dr.GetBoolean("NeedsReply"));
LoadProperty(NeedsReplyDecisionProperty, dr.GetBoolean("NeedsReplyDecision"));
LoadProperty(CircTypeTagProperty, dr.GetString("CircTypeTag"));
LoadProperty(SenderEntityIDProperty, (int?)dr.GetValue("SenderEntityID"));
LoadProperty(SentDateTimeProperty, dr.IsDBNull("SentDateTime") ? null : dr.GetSmartDate("SentDateTime", true));
LoadProperty(DaysToReplyProperty, dr.GetInt16("DaysToReply"));
LoadProperty(DaysToLiveProperty, dr.GetInt16("DaysToLive"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Edc.Api.Areas.HelpPage.ModelDescriptions;
using Edc.Api.Areas.HelpPage.Models;
namespace Edc.Api.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using OpenLiveWriter.Api;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.PostEditor.Video;
using ContentAlignment = OpenLiveWriter.Api.Alignment;
namespace OpenLiveWriter.PostEditor.ContentSources
{
public class SmartContent : ISmartContent, ILayoutStyle, ISupportingFiles, IInternalContent
{
private readonly static string SETTING_ALIGNMENT = "microsoft.internal.alignment";
private readonly static string SETTING_PADDING_TOP = "microsoft.internal.paddingTop";
private readonly static string SETTING_PADDING_RIGHT = "microsoft.internal.paddingRight";
private readonly static string SETTING_PADDING_BOTTOM = "microsoft.internal.paddingBottom";
private readonly static string SETTING_PADDING_LEFT = "microsoft.internal.paddingLeft";
private IExtensionData _extensionData;
public SmartContent(IExtensionData extensionData)
{
_extensionData = extensionData;
}
public DateTime? RefreshCallback
{
get
{
return _extensionData.RefreshCallBack;
}
set
{
_extensionData.RefreshCallBack = value;
}
}
public Object ObjectState
{
get
{
return _extensionData.ObjectState;
}
set
{
_extensionData.ObjectState = value;
}
}
public IExtensionData ExtensionData
{
get
{
return _extensionData;
}
}
public IProperties Properties
{
get
{
return _extensionData.Settings;
}
}
public Alignment Alignment
{
get
{
try
{
string alignment = Properties.GetString(SETTING_ALIGNMENT, Api.Alignment.None.ToString());
Alignment cAlignment = (Alignment)Api.Alignment.Parse(typeof (Alignment), alignment);
return cAlignment;
}
catch(Exception)
{
return Alignment.None;
}
}
set { Properties.SetString(SETTING_ALIGNMENT, value.ToString()); }
}
public ILayoutStyle Layout
{
get { return this; }
}
public ISupportingFiles Files
{
get { return this;}
}
public string[] SupportingFileIds
{
get { return (this as ISupportingFiles).Filenames; }
}
public Stream GetFileStream(string fileId)
{
return (this as ISupportingFiles).Open(fileId) ;
}
Stream ISupportingFiles.Open(string fileName)
{
return (this as ISupportingFiles).Open(fileName, false) ;
}
Stream ISupportingFiles.Open(string fileName, bool create )
{
ISupportingFiles files = this as ISupportingFiles ;
if ( !files.Contains(fileName) )
{
using ( MemoryStream emptyStream = new MemoryStream() )
_extensionData.AddFile(fileName, emptyStream);
}
return _extensionData.GetFileStream(fileName);
}
void ISupportingFiles.AddFile(string fileName, string sourceFilePath)
{
//Writer Beta1 has a bug that will cause AddFile to overwrite the source file with a zero byte file.
//To prevent users from ever encountering this bug, this method has been marked obsolete and throws
//an exception so no developers will ever use it.
throw new NotSupportedException("ISupportingFiles.AddFile() is not supported, use ISupportingFiles.Add() instead");
}
void ISupportingFiles.Add(string fileName, string sourceFilePath)
{
using ( FileStream fileStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
_extensionData.AddFile(fileName, fileStream);
}
void ISupportingFiles.AddImage(string fileName, Image image, ImageFormat imageFormat)
{
// convert the bitmap into a stream
using (MemoryStream imageStream = new MemoryStream())
{
// save the image into the strea
if (image is Bitmap)
ImageHelper2.SaveImage((Bitmap) image, imageFormat, imageStream);
else
image.Save(imageStream, imageFormat);
// add the stream to the supporting file
imageStream.Seek(0, SeekOrigin.Begin);
_extensionData.AddFile(fileName, imageStream);
}
}
void ISupportingFiles.Remove(string fileName)
{
_extensionData.RemoveFile(fileName);
}
void ISupportingFiles.RemoveAll()
{
ISupportingFiles files = this as ISupportingFiles ;
foreach ( string fileName in files.Filenames )
files.Remove(fileName);
}
Uri ISupportingFiles.GetUri(string fileName)
{
return _extensionData.GetFileUri(fileName);
}
bool ISupportingFiles.Contains(string fileName)
{
ISupportingFiles files = this as ISupportingFiles ;
foreach ( string existingFile in files.Filenames )
if ( fileName == existingFile )
return true ; // found the target file
// didn't find the target file
return false ;
}
string[] ISupportingFiles.Filenames
{
get
{
return _extensionData.FileIds ;
}
}
int ILayoutStyle.TopMargin
{
get { return Properties.GetInt(SETTING_PADDING_TOP, 0); }
set { Properties.SetInt(SETTING_PADDING_TOP, value); }
}
int ILayoutStyle.RightMargin
{
get { return Properties.GetInt(SETTING_PADDING_RIGHT, 0); }
set { Properties.SetInt(SETTING_PADDING_RIGHT, value); }
}
int ILayoutStyle.BottomMargin
{
get { return Properties.GetInt(SETTING_PADDING_BOTTOM, 0); }
set { Properties.SetInt(SETTING_PADDING_BOTTOM, value); }
}
int ILayoutStyle.LeftMargin
{
get { return Properties.GetInt(SETTING_PADDING_LEFT, 0); }
set { Properties.SetInt(SETTING_PADDING_LEFT, value); }
}
public string Id
{
get { return _extensionData.Id; }
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Xml;
using NLog.Common;
using NLog.Filters;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
/// <summary>
/// A class for configuring NLog through an XML configuration file
/// (App.config style or App.nlog style).
/// </summary>
public class XmlLoggingConfiguration : LoggingConfiguration
{
private readonly ConfigurationItemFactory configurationItemFactory = ConfigurationItemFactory.Default;
private readonly Dictionary<string, bool> visitedFile = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, string> variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private string originalFileName;
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
public XmlLoggingConfiguration(string fileName)
{
using (XmlReader reader = XmlReader.Create(fileName))
{
this.Initialize(reader, fileName, false);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="fileName">Configuration file to be read.</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
public XmlLoggingConfiguration(string fileName, bool ignoreErrors)
{
using (XmlReader reader = XmlReader.Create(fileName))
{
this.Initialize(reader, fileName, ignoreErrors);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName)
{
this.Initialize(reader, fileName, false);
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors)
{
this.Initialize(reader, fileName, ignoreErrors);
}
#if !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
internal XmlLoggingConfiguration(XmlElement element, string fileName)
{
using (var stringReader = new StringReader(element.OuterXml))
{
XmlReader reader = XmlReader.Create(stringReader);
this.Initialize(reader, fileName, false);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
/// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param>
internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors)
{
using (var stringReader = new StringReader(element.OuterXml))
{
XmlReader reader = XmlReader.Create(stringReader);
this.Initialize(reader, fileName, ignoreErrors);
}
}
#endif
#if !NET_CF && !SILVERLIGHT
/// <summary>
/// Gets the default <see cref="LoggingConfiguration" /> object by parsing
/// the application configuration file (<c>app.exe.config</c>).
/// </summary>
public static LoggingConfiguration AppConfig
{
get
{
object o = System.Configuration.ConfigurationManager.GetSection("nlog");
return o as LoggingConfiguration;
}
}
#endif
/// <summary>
/// Gets or sets a value indicating whether the configuration files
/// should be watched for changes and reloaded automatically when changed.
/// </summary>
public bool AutoReload { get; set; }
/// <summary>
/// Gets the collection of file names which should be watched for changes by NLog.
/// This is the list of configuration files processed.
/// If the <c>autoReload</c> attribute is not set it returns empty collection.
/// </summary>
public override IEnumerable<string> FileNamesToWatch
{
get
{
if (this.AutoReload)
{
return this.visitedFile.Keys;
}
return new string[0];
}
}
/// <summary>
/// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object.
/// </summary>
/// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns>
public override LoggingConfiguration Reload()
{
return new XmlLoggingConfiguration(this.originalFileName);
}
private static bool IsTargetElement(string name)
{
return name.Equals("target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target", StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetRefElement(string name)
{
return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase);
}
private static string CleanWhitespace(string s)
{
s = s.Replace(" ", string.Empty); // get rid of the whitespace
return s;
}
private static string StripOptionalNamespacePrefix(string attributeValue)
{
if (attributeValue == null)
{
return null;
}
int p = attributeValue.IndexOf(':');
if (p < 0)
{
return attributeValue;
}
return attributeValue.Substring(p + 1);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")]
private static Target WrapWithAsyncTargetWrapper(Target target)
{
var asyncTargetWrapper = new AsyncTargetWrapper();
asyncTargetWrapper.WrappedTarget = target;
asyncTargetWrapper.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name);
target = asyncTargetWrapper;
return target;
}
/// <summary>
/// Initializes the configuration.
/// </summary>
/// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param>
/// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param>
/// <param name="ignoreErrors">Ignore any errors during configuration.</param>
private void Initialize(XmlReader reader, string fileName, bool ignoreErrors)
{
try
{
reader.MoveToContent();
var content = new NLogXmlElement(reader);
if (fileName != null)
{
#if SILVERLIGHT
string key = fileName;
#else
string key = Path.GetFullPath(fileName);
#endif
this.visitedFile[key] = true;
this.originalFileName = fileName;
this.ParseTopLevel(content, Path.GetDirectoryName(fileName));
InternalLogger.Info("Configured from an XML element in {0}...", fileName);
}
else
{
this.ParseTopLevel(content, null);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception);
if (!ignoreErrors)
{
if (LogManager.ThrowExceptions)
{
throw ConfigException;
}
else
{
InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
}
}
else
{
InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException);
}
}
}
private void ConfigureFromFile(string fileName)
{
#if SILVERLIGHT
// file names are relative to XAP
string key = fileName;
#else
string key = Path.GetFullPath(fileName);
#endif
if (this.visitedFile.ContainsKey(key))
{
return;
}
this.visitedFile[key] = true;
this.ParseTopLevel(new NLogXmlElement(fileName), Path.GetDirectoryName(fileName));
}
private void ParseTopLevel(NLogXmlElement content, string baseDirectory)
{
content.AssertName("nlog", "configuration");
switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "CONFIGURATION":
this.ParseConfigurationElement(content, baseDirectory);
break;
case "NLOG":
this.ParseNLogElement(content, baseDirectory);
break;
}
}
private void ParseConfigurationElement(NLogXmlElement configurationElement, string baseDirectory)
{
InternalLogger.Trace("ParseConfigurationElement");
configurationElement.AssertName("configuration");
foreach (var el in configurationElement.Elements("nlog"))
{
this.ParseNLogElement(el, baseDirectory);
}
}
private void ParseNLogElement(NLogXmlElement nlogElement, string baseDirectory)
{
InternalLogger.Trace("ParseNLogElement");
nlogElement.AssertName("nlog");
this.AutoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", false);
LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions);
InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole);
#if !NET_CF
InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError);
#endif
InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile);
InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name));
LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name));
foreach (var el in nlogElement.Children)
{
switch (el.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "EXTENSIONS":
this.ParseExtensionsElement(el, baseDirectory);
break;
case "INCLUDE":
this.ParseIncludeElement(el, baseDirectory);
break;
case "APPENDERS":
case "TARGETS":
this.ParseTargetsElement(el);
break;
case "VARIABLE":
this.ParseVariableElement(el);
break;
case "RULES":
this.ParseRulesElement(el, this.LoggingRules);
break;
default:
InternalLogger.Warn("Skipping unknown node: {0}", el.LocalName);
break;
}
}
}
private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection)
{
InternalLogger.Trace("ParseRulesElement");
rulesElement.AssertName("rules");
foreach (var loggerElement in rulesElement.Elements("logger"))
{
this.ParseLoggerElement(loggerElement, rulesCollection);
}
}
private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection)
{
loggerElement.AssertName("logger");
var rule = new LoggingRule();
string namePattern = loggerElement.GetOptionalAttribute("name", "*");
string appendTo = loggerElement.GetOptionalAttribute("appendTo", null);
if (appendTo == null)
{
appendTo = loggerElement.GetOptionalAttribute("writeTo", null);
}
rule.LoggerNamePattern = namePattern;
if (appendTo != null)
{
foreach (string t in appendTo.Split(','))
{
string targetName = t.Trim();
Target target = FindTargetByName(targetName);
if (target != null)
{
rule.Targets.Add(target);
}
else
{
throw new NLogConfigurationException("Target " + targetName + " not found.");
}
}
}
rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false);
string levelString;
if (loggerElement.AttributeValues.TryGetValue("level", out levelString))
{
LogLevel level = LogLevel.FromString(levelString);
rule.EnableLoggingForLevel(level);
}
else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString))
{
levelString = CleanWhitespace(levelString);
string[] tokens = levelString.Split(',');
foreach (string s in tokens)
{
if (!string.IsNullOrEmpty(s))
{
LogLevel level = LogLevel.FromString(s);
rule.EnableLoggingForLevel(level);
}
}
}
else
{
int minLevel = 0;
int maxLevel = LogLevel.MaxLevel.Ordinal;
string minLevelString;
string maxLevelString;
if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString))
{
minLevel = LogLevel.FromString(minLevelString).Ordinal;
}
if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString))
{
maxLevel = LogLevel.FromString(maxLevelString).Ordinal;
}
for (int i = minLevel; i <= maxLevel; ++i)
{
rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
}
}
foreach (var child in loggerElement.Children)
{
switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture))
{
case "FILTERS":
this.ParseFilters(rule, child);
break;
case "LOGGER":
this.ParseLoggerElement(child, rule.ChildRules);
break;
}
}
rulesCollection.Add(rule);
}
private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement)
{
filtersElement.AssertName("filters");
foreach (var filterElement in filtersElement.Children)
{
string name = filterElement.LocalName;
Filter filter = this.configurationItemFactory.Filters.CreateInstance(name);
this.ConfigureObjectFromAttributes(filter, filterElement, false);
rule.Filters.Add(filter);
}
}
private void ParseVariableElement(NLogXmlElement variableElement)
{
variableElement.AssertName("variable");
string name = variableElement.GetRequiredAttribute("name");
string value = this.ExpandVariables(variableElement.GetRequiredAttribute("value"));
this.variables[name] = value;
}
private void ParseTargetsElement(NLogXmlElement targetsElement)
{
targetsElement.AssertName("targets", "appenders");
bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false);
NLogXmlElement defaultWrapperElement = null;
var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>();
foreach (var targetElement in targetsElement.Children)
{
string name = targetElement.LocalName;
string type = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null));
switch (name.ToUpper(CultureInfo.InvariantCulture))
{
case "DEFAULT-WRAPPER":
defaultWrapperElement = targetElement;
break;
case "DEFAULT-TARGET-PARAMETERS":
if (type == null)
{
throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
}
typeNameToDefaultTargetParameters[type] = targetElement;
break;
case "TARGET":
case "APPENDER":
case "WRAPPER":
case "WRAPPER-TARGET":
case "COMPOUND-TARGET":
if (type == null)
{
throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>.");
}
Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type);
NLogXmlElement defaults;
if (typeNameToDefaultTargetParameters.TryGetValue(type, out defaults))
{
this.ParseTargetElement(newTarget, defaults);
}
this.ParseTargetElement(newTarget, targetElement);
if (asyncWrap)
{
newTarget = WrapWithAsyncTargetWrapper(newTarget);
}
if (defaultWrapperElement != null)
{
newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement);
}
InternalLogger.Info("Adding target {0}", newTarget);
AddTarget(newTarget.Name, newTarget);
break;
}
}
}
private void ParseTargetElement(Target target, NLogXmlElement targetElement)
{
var compound = target as CompoundTargetBase;
var wrapper = target as WrapperTargetBase;
this.ConfigureObjectFromAttributes(target, targetElement, true);
foreach (var childElement in targetElement.Children)
{
string name = childElement.LocalName;
if (compound != null)
{
if (IsTargetRefElement(name))
{
string targetName = childElement.GetRequiredAttribute("name");
Target newTarget = this.FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
compound.Targets.Add(newTarget);
continue;
}
if (IsTargetElement(name))
{
string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));
Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type);
if (newTarget != null)
{
this.ParseTargetElement(newTarget, childElement);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
compound.Targets.Add(newTarget);
}
continue;
}
}
if (wrapper != null)
{
if (IsTargetRefElement(name))
{
string targetName = childElement.GetRequiredAttribute("name");
Target newTarget = this.FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
wrapper.WrappedTarget = newTarget;
continue;
}
if (IsTargetElement(name))
{
string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type"));
Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type);
if (newTarget != null)
{
this.ParseTargetElement(newTarget, childElement);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
if (wrapper.WrappedTarget != null)
{
throw new NLogConfigurationException("Wrapped target already defined.");
}
wrapper.WrappedTarget = newTarget;
}
continue;
}
}
this.SetPropertyFromElement(target, childElement);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "Need to load external assembly.")]
private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory)
{
extensionsElement.AssertName("extensions");
foreach (var addElement in extensionsElement.Elements("add"))
{
string prefix = addElement.GetOptionalAttribute("prefix", null);
if (prefix != null)
{
prefix = prefix + ".";
}
string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null));
if (type != null)
{
this.configurationItemFactory.RegisterType(Type.GetType(type, true), prefix);
}
#if !WINDOWS_PHONE
string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null);
if (assemblyFile != null)
{
try
{
#if SILVERLIGHT
var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative));
var assemblyPart = new AssemblyPart();
Assembly asm = assemblyPart.Load(si.Stream);
#else
string fullFileName = Path.Combine(baseDirectory, assemblyFile);
InternalLogger.Info("Loading assembly file: {0}", fullFileName);
Assembly asm = Assembly.LoadFrom(fullFileName);
#endif
this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error loading extensions: {0}", exception);
if (LogManager.ThrowExceptions)
{
throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
}
}
continue;
}
string assemblyName = addElement.GetOptionalAttribute("assembly", null);
if (assemblyName != null)
{
try
{
InternalLogger.Info("Loading assembly name: {0}", assemblyName);
#if SILVERLIGHT
var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative));
var assemblyPart = new AssemblyPart();
Assembly asm = assemblyPart.Load(si.Stream);
#else
Assembly asm = Assembly.Load(assemblyName);
#endif
this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error loading extensions: {0}", exception);
if (LogManager.ThrowExceptions)
{
throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
}
}
continue;
}
#endif
}
}
private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory)
{
includeElement.AssertName("include");
string newFileName = includeElement.GetRequiredAttribute("file");
try
{
newFileName = this.ExpandVariables(newFileName);
newFileName = SimpleLayout.Evaluate(newFileName);
if (baseDirectory != null)
{
newFileName = Path.Combine(baseDirectory, newFileName);
}
#if SILVERLIGHT
newFileName = newFileName.Replace("\\", "/");
if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null)
#else
if (File.Exists(newFileName))
#endif
{
InternalLogger.Debug("Including file '{0}'", newFileName);
this.ConfigureFromFile(newFileName);
}
else
{
throw new FileNotFoundException("Included file not found: " + newFileName);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error when including '{0}' {1}", newFileName, exception);
if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false))
{
return;
}
throw new NLogConfigurationException("Error when including: " + newFileName, exception);
}
}
private void SetPropertyFromElement(object o, NLogXmlElement element)
{
if (this.AddArrayItemFromElement(o, element))
{
return;
}
if (this.SetLayoutFromElement(o, element))
{
return;
}
PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandVariables(element.Value), this.configurationItemFactory);
}
private bool AddArrayItemFromElement(object o, NLogXmlElement element)
{
string name = element.LocalName;
PropertyInfo propInfo;
if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo))
{
return false;
}
Type elementType = PropertyHelper.GetArrayItemType(propInfo);
if (elementType != null)
{
IList propertyValue = (IList)propInfo.GetValue(o, null);
object arrayItem = FactoryHelper.CreateInstance(elementType);
this.ConfigureObjectFromAttributes(arrayItem, element, true);
this.ConfigureObjectFromElement(arrayItem, element);
propertyValue.Add(arrayItem);
return true;
}
return false;
}
private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType)
{
foreach (var kvp in element.AttributeValues)
{
string childName = kvp.Key;
string childValue = kvp.Value;
if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase))
{
continue;
}
PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandVariables(childValue), this.configurationItemFactory);
}
}
private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement)
{
PropertyInfo targetPropertyInfo;
string name = layoutElement.LocalName;
// if property exists
if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo))
{
// and is a Layout
if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType))
{
string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null));
// and 'type' attribute has been specified
if (layoutTypeName != null)
{
// configure it from current element
Layout layout = this.configurationItemFactory.Layouts.CreateInstance(this.ExpandVariables(layoutTypeName));
this.ConfigureObjectFromAttributes(layout, layoutElement, true);
this.ConfigureObjectFromElement(layout, layoutElement);
targetPropertyInfo.SetValue(o, layout, null);
return true;
}
}
}
return false;
}
private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element)
{
foreach (var child in element.Children)
{
this.SetPropertyFromElement(targetObject, child);
}
}
private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters)
{
string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type"));
Target wrapperTargetInstance = this.configurationItemFactory.Targets.CreateInstance(wrapperType);
WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper.");
}
this.ParseTargetElement(wrapperTargetInstance, defaultParameters);
while (wtb.WrappedTarget != null)
{
wtb = wtb.WrappedTarget as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper.");
}
}
wtb.WrappedTarget = t;
wrapperTargetInstance.Name = t.Name;
t.Name = t.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name);
return wrapperTargetInstance;
}
private string ExpandVariables(string input)
{
string output = input;
// TODO - make this case-insensitive, will probably require a different approach
foreach (var kvp in this.variables)
{
output = output.Replace("${" + kvp.Key + "}", kvp.Value);
}
return output;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Windows.Input;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.AvalonEdit.Utils;
using ICSharpCode.AvalonEdit.Editing;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media.TextFormatting;
using System.Windows.Threading;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Drawing;
using System.Windows.Media;
namespace beam
{
public class HighlightSExprBackgroundRenderer : IBackgroundRenderer
{
private ExtendedTextEditor _editor;
public HighlightSExprBackgroundRenderer(ExtendedTextEditor editor)
{
_editor = editor;
}
public KnownLayer Layer
{
get { return KnownLayer.Background; }
}
public void Draw(TextView textView, DrawingContext drawingContext)
{
if (_editor.Document == null)
return;
if (_editor.sexprMode == ExtendedTextEditor.MatchMode.None)
return;
textView.EnsureVisualLines();
var currentLine = _editor.Document.GetLineByOffset(_editor.CaretOffset);
foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, _editor.sexprSeg))
{
drawingContext.DrawRectangle(
new SolidColorBrush(Color.FromArgb(0x40, 0x80, 0x80, 0xFF)), null,
rect);
}
}
}
public class ExtendedTextEditor : TextEditor, INotifyPropertyChanged
{
public ExtendedTextEditor()
{
this.Background = new SolidColorBrush(Color.FromArgb(255, 0, 43, 54)); // base 03
this.Foreground = new SolidColorBrush(Color.FromArgb(255, 131, 148, 150)); // base 0
this.ShowLineNumbers = true;
this.Padding = new System.Windows.Thickness(5.0);
this.LineNumbersForeground = new SolidColorBrush(Color.FromArgb(255, 101, 123, 131)); // base 0
TextArea.Caret.PositionChanged += (sender, e) =>
CaretMoved();
TextArea.TextView.BackgroundRenderers.Add(new HighlightSExprBackgroundRenderer(this));
}
protected virtual void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#region enum Mode
enum Mode
{
None, // No drag
Drag, // Dragging number
}
Mode mode = Mode.None;
#endregion
string matchedNumStr = "";
int matchedNumOffset = -1;
int matchedNumLength = 0;
bool matchedNumSign = false;
bool matchedNumDot = false;
int matchedNumFracDigits = 0;
int curLength;
bool hasMatch = false;
Point startDragPos;
double startDragValue;
object undoGroupDescriptor;
#region MouseMove
override protected void OnPreviewMouseMove(MouseEventArgs e)
{
if (e.Handled)
return;
if (mode == Mode.None)
{
TextViewPosition? position = this.TextArea.TextView.GetPositionFloor(e.GetPosition(this.TextArea.TextView) + this.TextArea.TextView.ScrollOffset);
if (position != null)
{
DocumentLine line = this.TextArea.Document.GetLineByNumber(position.Value.Line); ;
int begin = line.Offset;
int end = line.EndOffset;
int offset = this.TextArea.Document.GetOffset(position.Value.Location);
int lineOffset = offset - begin;
hasMatch = false;
//if (Char.IsDigit(this.TextArea.Document.GetCharAt(offset)))
{
string l = this.TextArea.Document.GetText(line.Offset, line.Length);
//string pat = @"([-+]?)\d+(\.?)(d*)";
string pat = @"([-+]?)\d*(?:(\.)(\d*))?";
Regex r = new Regex(pat);
Match m = r.Match(l);
while (m.Success && hasMatch == false)
{
int start = m.Index;
int length = m.Length;
if (start <= lineOffset && lineOffset < start + length)
{
matchedNumStr = m.Value;
matchedNumOffset = start + begin;
matchedNumLength = length;
matchedNumSign = m.Groups[1].Value.Length > 0;
matchedNumDot = m.Groups[2].Value.Length > 0;
matchedNumFracDigits = m.Groups[3].Value.Length;
curLength = matchedNumLength;
hasMatch = true;
undoGroupDescriptor = new object();
this.Document.UndoStack.StartUndoGroup(undoGroupDescriptor);
this.Document.UndoStack.EndUndoGroup();
}
m = m.NextMatch();
}
}
}
}
else if (mode == Mode.Drag)
{
Vector delta = e.GetPosition(this.TextArea) - startDragPos;
double dist = delta.X - delta.Y;
double newValue = startDragValue * Math.Exp(dist * 0.001);
string formatStr = "F" + matchedNumFracDigits.ToString();
string signStr = (matchedNumSign && newValue >= 0) ? "+" : "";
string numStr = signStr + newValue.ToString(formatStr, CultureInfo.InvariantCulture);
this.Document.UndoStack.StartContinuedUndoGroup(undoGroupDescriptor);
this.Document.Replace(matchedNumOffset, curLength, numStr);
this.Document.UndoStack.EndUndoGroup();
curLength = numStr.Length;
ICommand curSaveCommand = ((FileViewModel)this.TextArea.DataContext).SaveCommand;
// disabled because IsDirty flag is only set first change
// this is possible due to the continuing Undo group
//if (curSaveCommand.CanExecute(null))
curSaveCommand.Execute(null);
e.Handled = true;
}
}
#endregion
#region MouseLeftButtonDown
override protected void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (e.Handled==true)
return;
FileViewModel curFile = ((FileViewModel)this.TextArea.DataContext);
if (hasMatch && curFile.IsDirty==false)
{
if (this.TextArea.CaptureMouse())
{
mode = Mode.Drag;
startDragPos = e.GetPosition(this.TextArea.TextView);
startDragValue = Double.Parse(matchedNumStr, CultureInfo.InvariantCulture);
}
e.Handled = true;
return;
}
}
#endregion
#region MouseLeftButtonUp
override protected void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (mode == Mode.None || e.Handled == true)
return;
if (mode == Mode.Drag)
{
this.TextArea.ReleaseMouseCapture();
mode = Mode.None;
e.Handled = true;
return;
}
}
#endregion
void MarkLeft(int startOffset, char lookFor)
{
int curOffset = startOffset;
while (curOffset > -1)
{
curOffset = TextArea.Document.LastIndexOf(lookFor, 0, curOffset);
if (curOffset > -1)
{
TextSegment curSegment = new TextSegment() { StartOffset = curOffset, EndOffset = startOffset };
string tryString = TextArea.Document.GetText(curSegment);
if (global::ParserLogic.parse_success(tryString))
{
sexprMode = MatchMode.Success;
sexprSeg = curSegment;
break;
}
}
else
{
// failed at offset - 1
sexprMode = MatchMode.Failure;
sexprSeg = new TextSegment() { StartOffset = TextArea.Caret.Offset-1, Length = 1 };
}
}
}
public enum MatchMode
{
None, // No hightlight
Success, // Matched highlight
Failure, // Failed to match
}
public MatchMode sexprMode;
public TextSegment sexprSeg;
void MarkRight(int startOffset, char lookFor)
{
int curOffset = startOffset;
while (curOffset > -1)
{
curOffset = TextArea.Document.IndexOf(lookFor, curOffset+1, TextArea.Document.TextLength-curOffset-1);
if (curOffset > -1)
{
TextSegment curSegment = new TextSegment() { StartOffset = startOffset, EndOffset = curOffset + 1 };
string tryString = TextArea.Document.GetText(curSegment);
if (global::ParserLogic.parse_success(tryString))
{
sexprMode = MatchMode.Success;
sexprSeg = curSegment;
break;
}
}
else
{
sexprMode = MatchMode.Failure;
sexprSeg = new TextSegment() { StartOffset = TextArea.Caret.Offset, Length = 1 };
}
}
}
protected void CaretMoved()
{
MatchMode curMode = sexprMode;
TextSegment curSeg = sexprSeg;
int offset = TextArea.Caret.Offset;
sexprMode = MatchMode.None;
if (offset > 0)
{
char s = TextArea.Document.GetCharAt(TextArea.Caret.Offset - 1);
//Console.WriteLine(s);
if (s==')')
{
MarkLeft(offset, '(');
}
}
if (offset < TextArea.Document.TextLength)
{
char s = TextArea.Document.GetCharAt(TextArea.Caret.Offset);
//Console.WriteLine(s);
if (s=='(')
{
MarkRight(offset, ')');
}
}
if (curMode != sexprMode || curSeg != sexprSeg)
TextArea.TextView.InvalidateLayer(KnownLayer.Background);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
public class BetterList<T>
{
public delegate int CompareFunc(T left, T right);
public T[] buffer;
public int size;
[DebuggerHidden]
public T this[int i]
{
get
{
return this.buffer[i];
}
set
{
this.buffer[i] = value;
}
}
[DebuggerHidden, DebuggerHidden, DebuggerStepThrough]
public IEnumerator<T> GetEnumerator()
{
BetterList<T>.<GetEnumerator>c__Iterator16 <GetEnumerator>c__Iterator = new BetterList<T>.<GetEnumerator>c__Iterator16();
<GetEnumerator>c__Iterator.<>f__this = this;
return <GetEnumerator>c__Iterator;
}
private void AllocateMore()
{
T[] array = (this.buffer == null) ? new T[32] : new T[Mathf.Max(this.buffer.Length << 1, 32)];
if (this.buffer != null && this.size > 0)
{
this.buffer.CopyTo(array, 0);
}
this.buffer = array;
}
private void Trim()
{
if (this.size > 0)
{
if (this.size < this.buffer.Length)
{
T[] array = new T[this.size];
for (int i = 0; i < this.size; i++)
{
array[i] = this.buffer[i];
}
this.buffer = array;
}
}
else
{
this.buffer = null;
}
}
public void Clear()
{
this.size = 0;
}
public void Release()
{
this.size = 0;
this.buffer = null;
}
public void Add(T item)
{
if (this.buffer == null || this.size == this.buffer.Length)
{
this.AllocateMore();
}
this.buffer[this.size++] = item;
}
public void Insert(int index, T item)
{
if (this.buffer == null || this.size == this.buffer.Length)
{
this.AllocateMore();
}
if (index < this.size)
{
for (int i = this.size; i > index; i--)
{
this.buffer[i] = this.buffer[i - 1];
}
this.buffer[index] = item;
this.size++;
}
else
{
this.Add(item);
}
}
public bool Contains(T item)
{
if (this.buffer == null)
{
return false;
}
for (int i = 0; i < this.size; i++)
{
if (this.buffer[i].Equals(item))
{
return true;
}
}
return false;
}
public bool Remove(T item)
{
if (this.buffer != null)
{
EqualityComparer<T> @default = EqualityComparer<T>.Default;
for (int i = 0; i < this.size; i++)
{
if (@default.Equals(this.buffer[i], item))
{
this.size--;
this.buffer[i] = default(T);
for (int j = i; j < this.size; j++)
{
this.buffer[j] = this.buffer[j + 1];
}
this.buffer[this.size] = default(T);
return true;
}
}
}
return false;
}
public void RemoveAt(int index)
{
if (this.buffer != null && index < this.size)
{
this.size--;
this.buffer[index] = default(T);
for (int i = index; i < this.size; i++)
{
this.buffer[i] = this.buffer[i + 1];
}
this.buffer[this.size] = default(T);
}
}
public T Pop()
{
if (this.buffer != null && this.size != 0)
{
T result = this.buffer[--this.size];
this.buffer[this.size] = default(T);
return result;
}
return default(T);
}
public T[] ToArray()
{
this.Trim();
return this.buffer;
}
[DebuggerHidden, DebuggerStepThrough]
public void Sort(BetterList<T>.CompareFunc comparer)
{
int num = 0;
int num2 = this.size - 1;
bool flag = true;
while (flag)
{
flag = false;
for (int i = num; i < num2; i++)
{
if (comparer(this.buffer[i], this.buffer[i + 1]) > 0)
{
T t = this.buffer[i];
this.buffer[i] = this.buffer[i + 1];
this.buffer[i + 1] = t;
flag = true;
}
else if (!flag)
{
num = ((i != 0) ? (i - 1) : 0);
}
}
}
}
}
| |
// 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.Management.ContainerRegistry
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// RegistriesOperations operations.
/// </summary>
public partial interface IRegistriesOperations
{
/// <summary>
/// Checks whether the container registry name is available for use.
/// The name must contain only alphanumeric characters, be globally
/// unique, and between 5 and 60 characters in length.
/// </summary>
/// <param name='name'>
/// The name of the container registry.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<RegistryNameStatus>> CheckNameAvailabilityWithHttpMessagesAsync(string name, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the properties of the specified container registry.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the container registry
/// belongs.
/// </param>
/// <param name='registryName'>
/// The name of the container registry.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Registry>> GetPropertiesWithHttpMessagesAsync(string resourceGroupName, string registryName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Creates or updates a container registry with the specified
/// parameters.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the container registry
/// belongs.
/// </param>
/// <param name='registryName'>
/// The name of the container registry.
/// </param>
/// <param name='registry'>
/// The parameters for creating or updating a container registry.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Registry>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string registryName, Registry registry, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a container registry.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the container registry
/// belongs.
/// </param>
/// <param name='registryName'>
/// The name of the container registry.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string registryName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates a container registry with the specified parameters.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the container registry
/// belongs.
/// </param>
/// <param name='registryName'>
/// The name of the container registry.
/// </param>
/// <param name='registryUpdateParameters'>
/// The parameters for updating a container registry.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Registry>> UpdateWithHttpMessagesAsync(string resourceGroupName, string registryName, RegistryUpdateParameters registryUpdateParameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all the available container registries under the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the container registry
/// belongs.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Registry>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all the available container registries under the specified
/// subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Registry>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the administrator login credentials for the specified
/// container registry.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the container registry
/// belongs.
/// </param>
/// <param name='registryName'>
/// The name of the container registry.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<RegistryCredentials>> GetCredentialsWithHttpMessagesAsync(string resourceGroupName, string registryName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Regenerates the administrator login credentials for the specified
/// container registry.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group to which the container registry
/// belongs.
/// </param>
/// <param name='registryName'>
/// The name of the container registry.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<RegistryCredentials>> RegenerateCredentialsWithHttpMessagesAsync(string resourceGroupName, string registryName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all the available container registries under the specified
/// resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Registry>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all the available container registries under the specified
/// subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Registry>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// 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 gagvc = Google.Ads.GoogleAds.V8.Common;
using gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAdServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetAdRequestObject()
{
moq::Mock<AdService.AdServiceClient> mockGrpcClient = new moq::Mock<AdService.AdServiceClient>(moq::MockBehavior.Strict);
GetAdRequest request = new GetAdRequest
{
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
};
gagvr::Ad expectedResponse = new gagvr::Ad
{
Type = gagve::AdTypeEnum.Types.AdType.VideoTrueviewDiscoveryAd,
TextAd = new gagvc::TextAdInfo(),
ExpandedTextAd = new gagvc::ExpandedTextAdInfo(),
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
ExpandedDynamicSearchAd = new gagvc::ExpandedDynamicSearchAdInfo(),
HotelAd = new gagvc::HotelAdInfo(),
ShoppingSmartAd = new gagvc::ShoppingSmartAdInfo(),
ShoppingProductAd = new gagvc::ShoppingProductAdInfo(),
DevicePreference = gagve::DeviceEnum.Types.Device.Desktop,
GmailAd = new gagvc::GmailAdInfo(),
ImageAd = new gagvc::ImageAdInfo(),
VideoAd = new gagvc::VideoAdInfo(),
ResponsiveSearchAd = new gagvc::ResponsiveSearchAdInfo(),
UrlCollections =
{
new gagvc::UrlCollection(),
},
SystemManagedResourceSource = gagve::SystemManagedResourceSourceEnum.Types.SystemManagedResourceSource.AdVariations,
LegacyResponsiveDisplayAd = new gagvc::LegacyResponsiveDisplayAdInfo(),
AppAd = new gagvc::AppAdInfo(),
LegacyAppInstallAd = new gagvc::LegacyAppInstallAdInfo(),
ResponsiveDisplayAd = new gagvc::ResponsiveDisplayAdInfo(),
LocalAd = new gagvc::LocalAdInfo(),
DisplayUploadAd = new gagvc::DisplayUploadAdInfo(),
AppEngagementAd = new gagvc::AppEngagementAdInfo(),
FinalAppUrls =
{
new gagvc::FinalAppUrl(),
},
ShoppingComparisonListingAd = new gagvc::ShoppingComparisonListingAdInfo(),
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
VideoResponsiveAd = new gagvc::VideoResponsiveAdInfo(),
Id = -6774108720365892680L,
FinalUrls =
{
"final_urls3ed0b71b",
},
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
DisplayUrl = "display_url12de0d0c",
AddedByGoogleAds = true,
AdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
SmartCampaignAd = new gagvc::SmartCampaignAdInfo(),
CallAd = new gagvc::CallAdInfo(),
};
mockGrpcClient.Setup(x => x.GetAd(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdServiceClient client = new AdServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Ad response = client.GetAd(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdRequestObjectAsync()
{
moq::Mock<AdService.AdServiceClient> mockGrpcClient = new moq::Mock<AdService.AdServiceClient>(moq::MockBehavior.Strict);
GetAdRequest request = new GetAdRequest
{
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
};
gagvr::Ad expectedResponse = new gagvr::Ad
{
Type = gagve::AdTypeEnum.Types.AdType.VideoTrueviewDiscoveryAd,
TextAd = new gagvc::TextAdInfo(),
ExpandedTextAd = new gagvc::ExpandedTextAdInfo(),
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
ExpandedDynamicSearchAd = new gagvc::ExpandedDynamicSearchAdInfo(),
HotelAd = new gagvc::HotelAdInfo(),
ShoppingSmartAd = new gagvc::ShoppingSmartAdInfo(),
ShoppingProductAd = new gagvc::ShoppingProductAdInfo(),
DevicePreference = gagve::DeviceEnum.Types.Device.Desktop,
GmailAd = new gagvc::GmailAdInfo(),
ImageAd = new gagvc::ImageAdInfo(),
VideoAd = new gagvc::VideoAdInfo(),
ResponsiveSearchAd = new gagvc::ResponsiveSearchAdInfo(),
UrlCollections =
{
new gagvc::UrlCollection(),
},
SystemManagedResourceSource = gagve::SystemManagedResourceSourceEnum.Types.SystemManagedResourceSource.AdVariations,
LegacyResponsiveDisplayAd = new gagvc::LegacyResponsiveDisplayAdInfo(),
AppAd = new gagvc::AppAdInfo(),
LegacyAppInstallAd = new gagvc::LegacyAppInstallAdInfo(),
ResponsiveDisplayAd = new gagvc::ResponsiveDisplayAdInfo(),
LocalAd = new gagvc::LocalAdInfo(),
DisplayUploadAd = new gagvc::DisplayUploadAdInfo(),
AppEngagementAd = new gagvc::AppEngagementAdInfo(),
FinalAppUrls =
{
new gagvc::FinalAppUrl(),
},
ShoppingComparisonListingAd = new gagvc::ShoppingComparisonListingAdInfo(),
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
VideoResponsiveAd = new gagvc::VideoResponsiveAdInfo(),
Id = -6774108720365892680L,
FinalUrls =
{
"final_urls3ed0b71b",
},
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
DisplayUrl = "display_url12de0d0c",
AddedByGoogleAds = true,
AdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
SmartCampaignAd = new gagvc::SmartCampaignAdInfo(),
CallAd = new gagvc::CallAdInfo(),
};
mockGrpcClient.Setup(x => x.GetAdAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Ad>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdServiceClient client = new AdServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Ad responseCallSettings = await client.GetAdAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Ad responseCancellationToken = await client.GetAdAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAd()
{
moq::Mock<AdService.AdServiceClient> mockGrpcClient = new moq::Mock<AdService.AdServiceClient>(moq::MockBehavior.Strict);
GetAdRequest request = new GetAdRequest
{
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
};
gagvr::Ad expectedResponse = new gagvr::Ad
{
Type = gagve::AdTypeEnum.Types.AdType.VideoTrueviewDiscoveryAd,
TextAd = new gagvc::TextAdInfo(),
ExpandedTextAd = new gagvc::ExpandedTextAdInfo(),
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
ExpandedDynamicSearchAd = new gagvc::ExpandedDynamicSearchAdInfo(),
HotelAd = new gagvc::HotelAdInfo(),
ShoppingSmartAd = new gagvc::ShoppingSmartAdInfo(),
ShoppingProductAd = new gagvc::ShoppingProductAdInfo(),
DevicePreference = gagve::DeviceEnum.Types.Device.Desktop,
GmailAd = new gagvc::GmailAdInfo(),
ImageAd = new gagvc::ImageAdInfo(),
VideoAd = new gagvc::VideoAdInfo(),
ResponsiveSearchAd = new gagvc::ResponsiveSearchAdInfo(),
UrlCollections =
{
new gagvc::UrlCollection(),
},
SystemManagedResourceSource = gagve::SystemManagedResourceSourceEnum.Types.SystemManagedResourceSource.AdVariations,
LegacyResponsiveDisplayAd = new gagvc::LegacyResponsiveDisplayAdInfo(),
AppAd = new gagvc::AppAdInfo(),
LegacyAppInstallAd = new gagvc::LegacyAppInstallAdInfo(),
ResponsiveDisplayAd = new gagvc::ResponsiveDisplayAdInfo(),
LocalAd = new gagvc::LocalAdInfo(),
DisplayUploadAd = new gagvc::DisplayUploadAdInfo(),
AppEngagementAd = new gagvc::AppEngagementAdInfo(),
FinalAppUrls =
{
new gagvc::FinalAppUrl(),
},
ShoppingComparisonListingAd = new gagvc::ShoppingComparisonListingAdInfo(),
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
VideoResponsiveAd = new gagvc::VideoResponsiveAdInfo(),
Id = -6774108720365892680L,
FinalUrls =
{
"final_urls3ed0b71b",
},
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
DisplayUrl = "display_url12de0d0c",
AddedByGoogleAds = true,
AdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
SmartCampaignAd = new gagvc::SmartCampaignAdInfo(),
CallAd = new gagvc::CallAdInfo(),
};
mockGrpcClient.Setup(x => x.GetAd(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdServiceClient client = new AdServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Ad response = client.GetAd(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdAsync()
{
moq::Mock<AdService.AdServiceClient> mockGrpcClient = new moq::Mock<AdService.AdServiceClient>(moq::MockBehavior.Strict);
GetAdRequest request = new GetAdRequest
{
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
};
gagvr::Ad expectedResponse = new gagvr::Ad
{
Type = gagve::AdTypeEnum.Types.AdType.VideoTrueviewDiscoveryAd,
TextAd = new gagvc::TextAdInfo(),
ExpandedTextAd = new gagvc::ExpandedTextAdInfo(),
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
ExpandedDynamicSearchAd = new gagvc::ExpandedDynamicSearchAdInfo(),
HotelAd = new gagvc::HotelAdInfo(),
ShoppingSmartAd = new gagvc::ShoppingSmartAdInfo(),
ShoppingProductAd = new gagvc::ShoppingProductAdInfo(),
DevicePreference = gagve::DeviceEnum.Types.Device.Desktop,
GmailAd = new gagvc::GmailAdInfo(),
ImageAd = new gagvc::ImageAdInfo(),
VideoAd = new gagvc::VideoAdInfo(),
ResponsiveSearchAd = new gagvc::ResponsiveSearchAdInfo(),
UrlCollections =
{
new gagvc::UrlCollection(),
},
SystemManagedResourceSource = gagve::SystemManagedResourceSourceEnum.Types.SystemManagedResourceSource.AdVariations,
LegacyResponsiveDisplayAd = new gagvc::LegacyResponsiveDisplayAdInfo(),
AppAd = new gagvc::AppAdInfo(),
LegacyAppInstallAd = new gagvc::LegacyAppInstallAdInfo(),
ResponsiveDisplayAd = new gagvc::ResponsiveDisplayAdInfo(),
LocalAd = new gagvc::LocalAdInfo(),
DisplayUploadAd = new gagvc::DisplayUploadAdInfo(),
AppEngagementAd = new gagvc::AppEngagementAdInfo(),
FinalAppUrls =
{
new gagvc::FinalAppUrl(),
},
ShoppingComparisonListingAd = new gagvc::ShoppingComparisonListingAdInfo(),
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
VideoResponsiveAd = new gagvc::VideoResponsiveAdInfo(),
Id = -6774108720365892680L,
FinalUrls =
{
"final_urls3ed0b71b",
},
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
DisplayUrl = "display_url12de0d0c",
AddedByGoogleAds = true,
AdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
SmartCampaignAd = new gagvc::SmartCampaignAdInfo(),
CallAd = new gagvc::CallAdInfo(),
};
mockGrpcClient.Setup(x => x.GetAdAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Ad>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdServiceClient client = new AdServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Ad responseCallSettings = await client.GetAdAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Ad responseCancellationToken = await client.GetAdAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAdResourceNames()
{
moq::Mock<AdService.AdServiceClient> mockGrpcClient = new moq::Mock<AdService.AdServiceClient>(moq::MockBehavior.Strict);
GetAdRequest request = new GetAdRequest
{
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
};
gagvr::Ad expectedResponse = new gagvr::Ad
{
Type = gagve::AdTypeEnum.Types.AdType.VideoTrueviewDiscoveryAd,
TextAd = new gagvc::TextAdInfo(),
ExpandedTextAd = new gagvc::ExpandedTextAdInfo(),
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
ExpandedDynamicSearchAd = new gagvc::ExpandedDynamicSearchAdInfo(),
HotelAd = new gagvc::HotelAdInfo(),
ShoppingSmartAd = new gagvc::ShoppingSmartAdInfo(),
ShoppingProductAd = new gagvc::ShoppingProductAdInfo(),
DevicePreference = gagve::DeviceEnum.Types.Device.Desktop,
GmailAd = new gagvc::GmailAdInfo(),
ImageAd = new gagvc::ImageAdInfo(),
VideoAd = new gagvc::VideoAdInfo(),
ResponsiveSearchAd = new gagvc::ResponsiveSearchAdInfo(),
UrlCollections =
{
new gagvc::UrlCollection(),
},
SystemManagedResourceSource = gagve::SystemManagedResourceSourceEnum.Types.SystemManagedResourceSource.AdVariations,
LegacyResponsiveDisplayAd = new gagvc::LegacyResponsiveDisplayAdInfo(),
AppAd = new gagvc::AppAdInfo(),
LegacyAppInstallAd = new gagvc::LegacyAppInstallAdInfo(),
ResponsiveDisplayAd = new gagvc::ResponsiveDisplayAdInfo(),
LocalAd = new gagvc::LocalAdInfo(),
DisplayUploadAd = new gagvc::DisplayUploadAdInfo(),
AppEngagementAd = new gagvc::AppEngagementAdInfo(),
FinalAppUrls =
{
new gagvc::FinalAppUrl(),
},
ShoppingComparisonListingAd = new gagvc::ShoppingComparisonListingAdInfo(),
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
VideoResponsiveAd = new gagvc::VideoResponsiveAdInfo(),
Id = -6774108720365892680L,
FinalUrls =
{
"final_urls3ed0b71b",
},
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
DisplayUrl = "display_url12de0d0c",
AddedByGoogleAds = true,
AdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
SmartCampaignAd = new gagvc::SmartCampaignAdInfo(),
CallAd = new gagvc::CallAdInfo(),
};
mockGrpcClient.Setup(x => x.GetAd(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdServiceClient client = new AdServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Ad response = client.GetAd(request.ResourceNameAsAdName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdResourceNamesAsync()
{
moq::Mock<AdService.AdServiceClient> mockGrpcClient = new moq::Mock<AdService.AdServiceClient>(moq::MockBehavior.Strict);
GetAdRequest request = new GetAdRequest
{
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
};
gagvr::Ad expectedResponse = new gagvr::Ad
{
Type = gagve::AdTypeEnum.Types.AdType.VideoTrueviewDiscoveryAd,
TextAd = new gagvc::TextAdInfo(),
ExpandedTextAd = new gagvc::ExpandedTextAdInfo(),
UrlCustomParameters =
{
new gagvc::CustomParameter(),
},
ExpandedDynamicSearchAd = new gagvc::ExpandedDynamicSearchAdInfo(),
HotelAd = new gagvc::HotelAdInfo(),
ShoppingSmartAd = new gagvc::ShoppingSmartAdInfo(),
ShoppingProductAd = new gagvc::ShoppingProductAdInfo(),
DevicePreference = gagve::DeviceEnum.Types.Device.Desktop,
GmailAd = new gagvc::GmailAdInfo(),
ImageAd = new gagvc::ImageAdInfo(),
VideoAd = new gagvc::VideoAdInfo(),
ResponsiveSearchAd = new gagvc::ResponsiveSearchAdInfo(),
UrlCollections =
{
new gagvc::UrlCollection(),
},
SystemManagedResourceSource = gagve::SystemManagedResourceSourceEnum.Types.SystemManagedResourceSource.AdVariations,
LegacyResponsiveDisplayAd = new gagvc::LegacyResponsiveDisplayAdInfo(),
AppAd = new gagvc::AppAdInfo(),
LegacyAppInstallAd = new gagvc::LegacyAppInstallAdInfo(),
ResponsiveDisplayAd = new gagvc::ResponsiveDisplayAdInfo(),
LocalAd = new gagvc::LocalAdInfo(),
DisplayUploadAd = new gagvc::DisplayUploadAdInfo(),
AppEngagementAd = new gagvc::AppEngagementAdInfo(),
FinalAppUrls =
{
new gagvc::FinalAppUrl(),
},
ShoppingComparisonListingAd = new gagvc::ShoppingComparisonListingAdInfo(),
ResourceNameAsAdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
VideoResponsiveAd = new gagvc::VideoResponsiveAdInfo(),
Id = -6774108720365892680L,
FinalUrls =
{
"final_urls3ed0b71b",
},
FinalMobileUrls =
{
"final_mobile_urlsf4131aa0",
},
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
DisplayUrl = "display_url12de0d0c",
AddedByGoogleAds = true,
AdName = gagvr::AdName.FromCustomerAd("[CUSTOMER_ID]", "[AD_ID]"),
SmartCampaignAd = new gagvc::SmartCampaignAdInfo(),
CallAd = new gagvc::CallAdInfo(),
};
mockGrpcClient.Setup(x => x.GetAdAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Ad>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdServiceClient client = new AdServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Ad responseCallSettings = await client.GetAdAsync(request.ResourceNameAsAdName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Ad responseCancellationToken = await client.GetAdAsync(request.ResourceNameAsAdName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAdsRequestObject()
{
moq::Mock<AdService.AdServiceClient> mockGrpcClient = new moq::Mock<AdService.AdServiceClient>(moq::MockBehavior.Strict);
MutateAdsRequest request = new MutateAdsRequest
{
CustomerId = "customer_id3b3724cb",
Operations = { new AdOperation(), },
ValidateOnly = true,
PartialFailure = false,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateAdsResponse expectedResponse = new MutateAdsResponse
{
Results =
{
new MutateAdResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdServiceClient client = new AdServiceClientImpl(mockGrpcClient.Object, null);
MutateAdsResponse response = client.MutateAds(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAdsRequestObjectAsync()
{
moq::Mock<AdService.AdServiceClient> mockGrpcClient = new moq::Mock<AdService.AdServiceClient>(moq::MockBehavior.Strict);
MutateAdsRequest request = new MutateAdsRequest
{
CustomerId = "customer_id3b3724cb",
Operations = { new AdOperation(), },
ValidateOnly = true,
PartialFailure = false,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateAdsResponse expectedResponse = new MutateAdsResponse
{
Results =
{
new MutateAdResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdServiceClient client = new AdServiceClientImpl(mockGrpcClient.Object, null);
MutateAdsResponse responseCallSettings = await client.MutateAdsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAdsResponse responseCancellationToken = await client.MutateAdsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateAds()
{
moq::Mock<AdService.AdServiceClient> mockGrpcClient = new moq::Mock<AdService.AdServiceClient>(moq::MockBehavior.Strict);
MutateAdsRequest request = new MutateAdsRequest
{
CustomerId = "customer_id3b3724cb",
Operations = { new AdOperation(), },
};
MutateAdsResponse expectedResponse = new MutateAdsResponse
{
Results =
{
new MutateAdResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdServiceClient client = new AdServiceClientImpl(mockGrpcClient.Object, null);
MutateAdsResponse response = client.MutateAds(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateAdsAsync()
{
moq::Mock<AdService.AdServiceClient> mockGrpcClient = new moq::Mock<AdService.AdServiceClient>(moq::MockBehavior.Strict);
MutateAdsRequest request = new MutateAdsRequest
{
CustomerId = "customer_id3b3724cb",
Operations = { new AdOperation(), },
};
MutateAdsResponse expectedResponse = new MutateAdsResponse
{
Results =
{
new MutateAdResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateAdsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdServiceClient client = new AdServiceClientImpl(mockGrpcClient.Object, null);
MutateAdsResponse responseCallSettings = await client.MutateAdsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateAdsResponse responseCancellationToken = await client.MutateAdsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (C) 2015-2021 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using Neo.IO;
using Neo.SmartContract.Manifest;
using Neo.VM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Neo.SmartContract.Native
{
/// <summary>
/// The base class of all native contracts.
/// </summary>
public abstract class NativeContract
{
private static readonly List<NativeContract> contractsList = new();
private static readonly Dictionary<UInt160, NativeContract> contractsDictionary = new();
private readonly Dictionary<int, ContractMethodMetadata> methods = new();
private static int id_counter = 0;
#region Named Native Contracts
/// <summary>
/// Gets the instance of the <see cref="Native.ContractManagement"/> class.
/// </summary>
public static ContractManagement ContractManagement { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="Native.StdLib"/> class.
/// </summary>
public static StdLib StdLib { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="Native.CryptoLib"/> class.
/// </summary>
public static CryptoLib CryptoLib { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="LedgerContract"/> class.
/// </summary>
public static LedgerContract Ledger { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="NeoToken"/> class.
/// </summary>
public static NeoToken NEO { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="GasToken"/> class.
/// </summary>
public static GasToken GAS { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="PolicyContract"/> class.
/// </summary>
public static PolicyContract Policy { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="Native.RoleManagement"/> class.
/// </summary>
public static RoleManagement RoleManagement { get; } = new();
/// <summary>
/// Gets the instance of the <see cref="OracleContract"/> class.
/// </summary>
public static OracleContract Oracle { get; } = new();
#endregion
/// <summary>
/// Gets all native contracts.
/// </summary>
public static IReadOnlyCollection<NativeContract> Contracts { get; } = contractsList;
/// <summary>
/// The name of the native contract.
/// </summary>
public string Name => GetType().Name;
/// <summary>
/// The nef of the native contract.
/// </summary>
public NefFile Nef { get; }
/// <summary>
/// The hash of the native contract.
/// </summary>
public UInt160 Hash { get; }
/// <summary>
/// The id of the native contract.
/// </summary>
public int Id { get; } = --id_counter;
/// <summary>
/// The manifest of the native contract.
/// </summary>
public ContractManifest Manifest { get; }
/// <summary>
/// Initializes a new instance of the <see cref="NativeContract"/> class.
/// </summary>
protected NativeContract()
{
List<ContractMethodMetadata> descriptors = new();
foreach (MemberInfo member in GetType().GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
{
ContractMethodAttribute attribute = member.GetCustomAttribute<ContractMethodAttribute>();
if (attribute is null) continue;
descriptors.Add(new ContractMethodMetadata(member, attribute));
}
descriptors = descriptors.OrderBy(p => p.Name).ThenBy(p => p.Parameters.Length).ToList();
byte[] script;
using (ScriptBuilder sb = new())
{
foreach (ContractMethodMetadata method in descriptors)
{
method.Descriptor.Offset = sb.Length;
sb.EmitPush(0); //version
methods.Add(sb.Length, method);
sb.EmitSysCall(ApplicationEngine.System_Contract_CallNative);
sb.Emit(OpCode.RET);
}
script = sb.ToArray();
}
this.Nef = new NefFile
{
Compiler = "neo-core-v3.0",
Source = string.Empty,
Tokens = Array.Empty<MethodToken>(),
Script = script
};
this.Nef.CheckSum = NefFile.ComputeChecksum(Nef);
this.Hash = Helper.GetContractHash(UInt160.Zero, 0, Name);
this.Manifest = new ContractManifest
{
Name = Name,
Groups = Array.Empty<ContractGroup>(),
SupportedStandards = Array.Empty<string>(),
Abi = new ContractAbi()
{
Events = Array.Empty<ContractEventDescriptor>(),
Methods = descriptors.Select(p => p.Descriptor).ToArray()
},
Permissions = new[] { ContractPermission.DefaultPermission },
Trusts = WildcardContainer<ContractPermissionDescriptor>.Create(),
Extra = null
};
contractsList.Add(this);
contractsDictionary.Add(Hash, this);
}
/// <summary>
/// Checks whether the committee has witnessed the current transaction.
/// </summary>
/// <param name="engine">The <see cref="ApplicationEngine"/> that is executing the contract.</param>
/// <returns><see langword="true"/> if the committee has witnessed the current transaction; otherwise, <see langword="false"/>.</returns>
protected static bool CheckCommittee(ApplicationEngine engine)
{
UInt160 committeeMultiSigAddr = NEO.GetCommitteeAddress(engine.Snapshot);
return engine.CheckWitnessInternal(committeeMultiSigAddr);
}
private protected KeyBuilder CreateStorageKey(byte prefix)
{
return new KeyBuilder(Id, prefix);
}
/// <summary>
/// Gets the native contract with the specified hash.
/// </summary>
/// <param name="hash">The hash of the native contract.</param>
/// <returns>The native contract with the specified hash.</returns>
public static NativeContract GetContract(UInt160 hash)
{
contractsDictionary.TryGetValue(hash, out var contract);
return contract;
}
internal async void Invoke(ApplicationEngine engine, byte version)
{
try
{
if (version != 0)
throw new InvalidOperationException($"The native contract of version {version} is not active.");
ExecutionContext context = engine.CurrentContext;
ContractMethodMetadata method = methods[context.InstructionPointer];
ExecutionContextState state = context.GetState<ExecutionContextState>();
if (!state.CallFlags.HasFlag(method.RequiredCallFlags))
throw new InvalidOperationException($"Cannot call this method with the flag {state.CallFlags}.");
engine.AddGas(method.CpuFee * Policy.GetExecFeeFactor(engine.Snapshot) + method.StorageFee * Policy.GetStoragePrice(engine.Snapshot));
List<object> parameters = new();
if (method.NeedApplicationEngine) parameters.Add(engine);
if (method.NeedSnapshot) parameters.Add(engine.Snapshot);
for (int i = 0; i < method.Parameters.Length; i++)
parameters.Add(engine.Convert(context.EvaluationStack.Pop(), method.Parameters[i]));
object returnValue = method.Handler.Invoke(this, parameters.ToArray());
if (returnValue is ContractTask task)
{
await task;
returnValue = task.GetResult();
}
if (method.Handler.ReturnType != typeof(void) && method.Handler.ReturnType != typeof(ContractTask))
{
context.EvaluationStack.Push(engine.Convert(returnValue));
}
}
catch (Exception ex)
{
engine.Throw(ex);
}
}
/// <summary>
/// Determine whether the specified contract is a native contract.
/// </summary>
/// <param name="hash">The hash of the contract.</param>
/// <returns><see langword="true"/> if the contract is native; otherwise, <see langword="false"/>.</returns>
public static bool IsNative(UInt160 hash)
{
return contractsDictionary.ContainsKey(hash);
}
internal virtual ContractTask Initialize(ApplicationEngine engine)
{
return ContractTask.CompletedTask;
}
internal virtual ContractTask OnPersist(ApplicationEngine engine)
{
return ContractTask.CompletedTask;
}
internal virtual ContractTask PostPersist(ApplicationEngine engine)
{
return ContractTask.CompletedTask;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace HTTPApp.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// MailMessageTest.cs - NUnit Test Cases for System.Net.MailAddress.MailMessage
//
// Authors:
// John Luke (john.luke@gmail.com)
//
// (C) 2005, 2006 John Luke
//
using System.IO;
using System.Reflection;
using System.Text;
using Xunit;
namespace System.Net.Mail.Tests
{
public class MailMessageTest
{
MailMessage messageWithSubjectAndBody;
MailMessage emptyMessage;
public MailMessageTest()
{
messageWithSubjectAndBody = new MailMessage("from@example.com", "to@example.com");
messageWithSubjectAndBody.Subject = "the subject";
messageWithSubjectAndBody.Body = "hello";
messageWithSubjectAndBody.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("<html><body>hello</body></html>", null, "text/html"));
Attachment a = Attachment.CreateAttachmentFromString("blah blah", "text/plain");
messageWithSubjectAndBody.Attachments.Add(a);
emptyMessage = new MailMessage("from@example.com", "r1@t1.com, r2@t1.com");
}
[Fact]
public void TestRecipients()
{
Assert.Equal(emptyMessage.To.Count, 2);
Assert.Equal(emptyMessage.To[0].Address, "r1@t1.com");
Assert.Equal(emptyMessage.To[1].Address, "r2@t1.com");
}
[Fact]
public void TestForNullException()
{
Assert.Throws<ArgumentNullException>(() => new MailMessage("from@example.com", null));
Assert.Throws<ArgumentNullException>(() => new MailMessage(null, new MailAddress("to@example.com")));
Assert.Throws<ArgumentNullException>(() => new MailMessage(new MailAddress("from@example.com"), null));
Assert.Throws<ArgumentNullException>(() => new MailMessage(null, "to@example.com"));
}
[Fact]
public void AlternateViewTest()
{
Assert.Equal(messageWithSubjectAndBody.AlternateViews.Count, 1);
AlternateView av = messageWithSubjectAndBody.AlternateViews[0];
Assert.Equal(0, av.LinkedResources.Count);
Assert.Equal("text/html; charset=us-ascii", av.ContentType.ToString());
}
[Fact]
public void AttachmentTest()
{
Assert.Equal(messageWithSubjectAndBody.Attachments.Count, 1);
Attachment at = messageWithSubjectAndBody.Attachments[0];
Assert.Equal("text/plain", at.ContentType.MediaType);
}
[Fact]
public void BodyTest()
{
Assert.Equal(messageWithSubjectAndBody.Body, "hello");
}
[Fact]
public void BodyEncodingTest()
{
Assert.Equal(messageWithSubjectAndBody.BodyEncoding, Encoding.ASCII);
}
[Fact]
public void FromTest()
{
Assert.Equal(messageWithSubjectAndBody.From.Address, "from@example.com");
}
[Fact]
public void IsBodyHtmlTest()
{
Assert.False(messageWithSubjectAndBody.IsBodyHtml);
}
[Fact]
public void PriorityTest()
{
Assert.Equal(messageWithSubjectAndBody.Priority, MailPriority.Normal);
}
[Fact]
public void SubjectTest()
{
Assert.Equal(messageWithSubjectAndBody.Subject, "the subject");
}
[Fact]
public void ToTest()
{
Assert.Equal(messageWithSubjectAndBody.To.Count, 1);
Assert.Equal(messageWithSubjectAndBody.To[0].Address, "to@example.com");
messageWithSubjectAndBody = new MailMessage();
messageWithSubjectAndBody.To.Add("to@example.com");
messageWithSubjectAndBody.To.Add("you@nowhere.com");
Assert.Equal(messageWithSubjectAndBody.To.Count, 2);
Assert.Equal(messageWithSubjectAndBody.To[0].Address, "to@example.com");
Assert.Equal(messageWithSubjectAndBody.To[1].Address, "you@nowhere.com");
}
[Fact]
public void BodyAndEncodingTest()
{
MailMessage msg = new MailMessage("from@example.com", "to@example.com");
Assert.Equal(null, msg.BodyEncoding);
msg.Body = "test";
Assert.Equal(Encoding.ASCII, msg.BodyEncoding);
msg.Body = "test\u3067\u3059";
Assert.Equal(Encoding.ASCII, msg.BodyEncoding);
msg.BodyEncoding = null;
msg.Body = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.BodyEncoding.CodePage);
}
[Fact]
public void SubjectAndEncodingTest()
{
MailMessage msg = new MailMessage("from@example.com", "to@example.com");
Assert.Equal(null, msg.SubjectEncoding);
msg.Subject = "test";
Assert.Equal(null, msg.SubjectEncoding);
msg.Subject = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.SubjectEncoding.CodePage);
msg.SubjectEncoding = null;
msg.Subject = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.SubjectEncoding.CodePage);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "MailWriter is reflection blocked.")]
public void SentSpecialLengthMailAttachment_Base64Decode_Success()
{
// The special length follows pattern: (3N - 1) * 0x4400 + 1
// This length will trigger WriteState.Padding = 2 & count = 1 (byte to write)
// The smallest number to match the pattern is 34817.
int specialLength = 34817;
string stringLength34817 = new string('A', specialLength - 1) + 'Z';
byte[] toBytes = Encoding.ASCII.GetBytes(stringLength34817);
using (var tempFile = TempFile.Create(toBytes))
{
var message = new MailMessage("sender@test.com", "user1@pop.local", "testSubject", "testBody");
message.Attachments.Add(new Attachment(tempFile.Path));
string decodedAttachment = DecodeSentMailMessage(message);
// Make sure last byte is not encoded twice.
Assert.Equal(specialLength, decodedAttachment.Length);
Assert.Equal("AAAAAAAAAAAAAAAAZ", decodedAttachment.Substring(34800));
}
}
private static string DecodeSentMailMessage(MailMessage mail)
{
// Create a MIME message that would be sent using System.Net.Mail.
var stream = new MemoryStream();
var mailWriterType = mail.GetType().Assembly.GetType("System.Net.Mail.MailWriter");
var mailWriter = Activator.CreateInstance(
type: mailWriterType,
bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic,
binder: null,
args: new object[] { stream },
culture: null,
activationAttributes: null);
// Send the message.
mail.GetType().InvokeMember(
name: "Send",
invokeAttr: BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
binder: null,
target: mail,
args: new object[] { mailWriter, true, true });
// Decode contents.
string result = Encoding.UTF8.GetString(stream.ToArray());
string encodedAttachment = result.Split(new[] { "attachment" }, StringSplitOptions.None)[1].Trim().Split('-')[0].Trim();
byte[] data = Convert.FromBase64String(encodedAttachment);
string decodedString = Encoding.UTF8.GetString(data);
return decodedString;
}
}
}
| |
// -----
// Copyright 2010 Deyan Timnev
// This file is part of the Matrix Platform (www.matrixplatform.com).
// The Matrix Platform is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version. The Matrix Platform is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License along with the Matrix Platform. If not, see http://www.gnu.org/licenses/lgpl.html
// -----
//********************************************************************************************
// This code based on public domain code by Sergey Stoyan.
//********************************************************************************************
using System;
using System.Text.RegularExpressions;
namespace Matrix.Common.Core
{
/// <summary>
/// Miscellaneous and parsing thread-safe methods for DateTime,
/// class helps with parsing multiple date time formats.
/// </summary>
public static class DateTimeHelper
{
static object lock_variable = new object();
#region miscellaneous methods
public static uint GetSecondsSinceUnixEpoch(System.DateTime date_time)
{
lock (lock_variable)
{
TimeSpan t = date_time - new System.DateTime(1970, 1, 1);
int ss = (int)t.TotalSeconds;
if (ss < 0)
return 0;
return (uint)ss;
}
}
#endregion
#region parsing definitions
/// <summary>
/// Defines a substring where date-time was found and result of conversion
/// </summary>
public class ParsedDateTime
{
readonly public int IndexOfDate = -1;
readonly public int LengthOfDate = -1;
readonly public int IndexOfTime = -1;
readonly public int LengthOfTime = -1;
readonly public System.DateTime DateTime;
/// <summary>
/// True if a date was found within string
/// </summary>
readonly public bool IsDateFound;
/// <summary>
/// True if a time was found within string
/// </summary>
readonly public bool IsTimeFound;
internal ParsedDateTime(int index_of_date, int length_of_date, int index_of_time, int length_of_time, System.DateTime date_time)
{
IndexOfDate = index_of_date;
LengthOfDate = length_of_date;
IndexOfTime = index_of_time;
LengthOfTime = length_of_time;
DateTime = date_time;
IsDateFound = index_of_date > -1;
IsTimeFound = index_of_time > -1;
}
}
/// <summary>
/// Date that is accepted in the following cases:
/// - no date was parsed by TryParse();
/// - no year was found by TryParseDate();
/// It is ignored when DefaultDateIsCurrent = true
/// </summary>
public static System.DateTime DefaultDate
{
set
{
_DefaultDate = value;
}
get
{
if (DefaultDateIsNow)
return System.DateTime.Now;
else
return _DefaultDate;
}
}
static System.DateTime _DefaultDate = System.DateTime.Now;
/// <summary>
/// If true then DefaultDate property is ignored and DefaultDate is always DateTime.Now
/// </summary>
public static bool DefaultDateIsNow = true;
/// <summary>
/// Defines default date-time format.
/// </summary>
public enum DateTimeFormat
{
/// <summary>
/// month number goes before day number
/// </summary>
USA_DATE,
/// <summary>
/// day number goes before month number
/// </summary>
UK_DATE,
///// <summary>
///// time is specifed through AM or PM
///// </summary>
//USA_TIME,
}
#endregion
#region parsing derived methods for DateTime output
/// <summary>
/// Tries to find date and time within the passed string and return it as DateTime structure.
/// </summary>
/// <param name="str">string that contains date and(or) time</param>
/// <param name="default_format">format that must be used preferably in ambivalent instances</param>
/// <param name="date_time">parsed date-time output</param>
/// <returns>true if both date and time were found, else false</returns>
static public bool TryParseDateTime(string str, DateTimeFormat default_format, out System.DateTime date_time)
{
lock (lock_variable)
{
ParsedDateTime parsed_date_time;
if (!TryParseDateTime(str, default_format, out parsed_date_time))
{
date_time = new System.DateTime(1, 1, 1);
return false;
}
date_time = parsed_date_time.DateTime;
return true;
}
}
/// <summary>
/// Tries to find date and(or) time within the passed string and return it as DateTime structure.
/// If only date was found, time in the returned DateTime is always 0:0:0.
/// If only time was found, date in the returned DateTime is DefaultDate.
/// </summary>
/// <param name="str">string that contains date and(or) time</param>
/// <param name="default_format">format that must be used preferably in ambivalent instances</param>
/// <param name="date_time">parsed date-time output</param>
/// <returns>true if date and(or) time was found, else false</returns>
static public bool TryParse(string str, DateTimeFormat default_format, out System.DateTime date_time)
{
lock (lock_variable)
{
ParsedDateTime parsed_date_time;
if (!TryParse(str, default_format, out parsed_date_time))
{
date_time = new System.DateTime(1, 1, 1);
return false;
}
date_time = parsed_date_time.DateTime;
return true;
}
}
/// <summary>
/// Tries to find time within the passed string and return it as DateTime structure.
/// It recognizes only time while ignoring date, so date in the returned DateTime is always 1/1/1.
/// </summary>
/// <param name="str">string that contains time</param>
/// <param name="default_format">format that must be used preferably in ambivalent instances</param>
/// <param name="time">parsed time output</param>
/// <returns>true if time was found, else false</returns>
public static bool TryParseTime(string str, DateTimeFormat default_format, out System.DateTime time)
{
lock (lock_variable)
{
ParsedDateTime parsed_time;
if (!TryParseTime(str, default_format, out parsed_time, null))
{
time = new System.DateTime(1, 1, 1);
return false;
}
time = parsed_time.DateTime;
return true;
}
}
/// <summary>
/// Tries to find date within the passed string and return it as DateTime structure.
/// It recognizes only date while ignoring time, so time in the returned DateTime is always 0:0:0.
/// If year of the date was not found then it accepts the current year.
/// </summary>
/// <param name="str">string that contains date</param>
/// <param name="default_format">format that must be used preferably in ambivalent instances</param>
/// <param name="date">parsed date output</param>
/// <returns>true if date was found, else false</returns>
static public bool TryParseDate(string str, DateTimeFormat default_format, out System.DateTime date)
{
lock (lock_variable)
{
ParsedDateTime parsed_date;
if (!TryParseDate(str, default_format, out parsed_date))
{
date = new System.DateTime(1, 1, 1);
return false;
}
date = parsed_date.DateTime;
return true;
}
}
#endregion
#region parsing derived methods for ParsedDateTime output
/// <summary>
/// Tries to find date and time within the passed string and return it as ParsedDateTime object.
/// </summary>
/// <param name="str">string that contains date-time</param>
/// <param name="default_format">format that must be used preferably in ambivalent instances</param>
/// <param name="parsed_date_time">parsed date-time output</param>
/// <returns>true if both date and time were found, else false</returns>
static public bool TryParseDateTime(string str, DateTimeFormat default_format, out ParsedDateTime parsed_date_time)
{
lock (lock_variable)
{
if (DateTimeHelper.TryParse(str, DateTimeHelper.DateTimeFormat.USA_DATE, out parsed_date_time)
&& parsed_date_time.IsDateFound
&& parsed_date_time.IsTimeFound
)
return true;
parsed_date_time = null;
return false;
}
}
/// <summary>
/// Tries to find time within the passed string and return it as ParsedDateTime object.
/// It recognizes only time while ignoring date, so date in the returned ParsedDateTime is always 1/1/1
/// </summary>
/// <param name="str">string that contains date-time</param>
/// <param name="default_format">format that must be used preferably in ambivalent instances</param>
/// <param name="parsed_time">parsed date-time output</param>
/// <returns>true if time was found, else false</returns>
static public bool TryParseTime(string str, DateTimeFormat default_format, out ParsedDateTime parsed_time)
{
lock (lock_variable)
{
return TryParseTime(str, default_format, out parsed_time, null);
}
}
/// <summary>
/// Tries to find date and(or) time within the passed string and return it as ParsedDateTime object.
/// If only date was found, time in the returned ParsedDateTime is always 0:0:0.
/// If only time was found, date in the returned ParsedDateTime is DefaultDate.
/// </summary>
/// <param name="str">string that contains date-time</param>
/// <param name="default_format">format that must be used preferably in ambivalent instances</param>
/// <param name="parsed_date_time">parsed date-time output</param>
/// <returns>true if date or time was found, else false</returns>
static public bool TryParse(string str, DateTimeFormat default_format, out ParsedDateTime parsed_date_time)
{
lock (lock_variable)
{
parsed_date_time = null;
ParsedDateTime parsed_date;
ParsedDateTime parsed_time;
if (!TryParseDate(str, default_format, out parsed_date))
{
if (!TryParseTime(str, default_format, out parsed_time, null))
return false;
System.DateTime date_time = new System.DateTime(DefaultDate.Year, DefaultDate.Month, DefaultDate.Day, parsed_time.DateTime.Hour, parsed_time.DateTime.Minute, parsed_time.DateTime.Second);
parsed_date_time = new ParsedDateTime(-1, -1, parsed_time.IndexOfTime, parsed_time.LengthOfTime, date_time);
}
else
{
if (!TryParseTime(str, default_format, out parsed_time, parsed_date))
{
System.DateTime date_time = new System.DateTime(parsed_date.DateTime.Year, parsed_date.DateTime.Month, parsed_date.DateTime.Day, 0, 0, 0);
parsed_date_time = new ParsedDateTime(parsed_date.IndexOfDate, parsed_date.LengthOfDate, -1, -1, date_time);
}
else
{
System.DateTime date_time = new System.DateTime(parsed_date.DateTime.Year, parsed_date.DateTime.Month, parsed_date.DateTime.Day, parsed_time.DateTime.Hour, parsed_time.DateTime.Minute, parsed_time.DateTime.Second);
parsed_date_time = new ParsedDateTime(parsed_date.IndexOfDate, parsed_date.LengthOfDate, parsed_time.IndexOfTime, parsed_time.LengthOfTime, date_time);
}
}
return true;
}
}
#endregion
#region parsing base methods
/// <summary>
/// Tries to find time within the passed string (relatively to the passed parsed_date if any) and return it as ParsedDateTime object.
/// It recognizes only time while ignoring date, so date in the returned ParsedDateTime is always 1/1/1
/// </summary>
/// <param name="str">string that contains date</param>
/// <param name="default_format">format that must be used preferably in ambivalent instances</param>
/// <param name="parsed_time">parsed date-time output</param>
/// <param name="parsed_date">ParsedDateTime object if the date was found within this string, else NULL</param>
/// <returns>true if time was found, else false</returns>
public static bool TryParseTime(string str, DateTimeFormat default_format, out ParsedDateTime parsed_time, ParsedDateTime parsed_date)
{
lock (lock_variable)
{
parsed_time = null;
Match m;
if (parsed_date != null && parsed_date.IndexOfDate > -1)
{//look around the found date
//look for <date> [h]h:mm[:ss] [PM/AM]
m = Regex.Match(str.Substring(parsed_date.IndexOfDate + parsed_date.LengthOfDate), @"(?<=^\s*,?\s+|^\s*at\s*|^\s*[T\-]\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (!m.Success)
//look for [h]h:mm:ss <date>
m = Regex.Match(str.Substring(0, parsed_date.IndexOfDate), @"(?<=^|[^\d])(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[\s,]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
else//look anywere within string
//look for [h]h:mm[:ss] [PM/AM]
m = Regex.Match(str, @"(?<=^|\s+|\s*T\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (m.Success)
{
try
{
int hour = int.Parse(m.Groups["hour"].Value);
if (hour < 0 || hour > 23)
return false;
int minute = int.Parse(m.Groups["minute"].Value);
if (minute < 0 || minute > 59)
return false;
int second = 0;
if (!string.IsNullOrEmpty(m.Groups["second"].Value))
{
second = int.Parse(m.Groups["second"].Value);
if (second < 0 || second > 59)
return false;
}
if (string.Compare(m.Groups[4].Value, "PM", true) > -1)
hour += 12;
System.DateTime date_time = new System.DateTime(1, 1, 1, hour, minute, second);
parsed_time = new ParsedDateTime(-1, -1, m.Index, m.Length, date_time);
}
catch
{
return false;
}
return true;
}
return false;
}
}
/// <summary>
/// Tries to find date within the passed string and return it as ParsedDateTime object.
/// It recognizes only date while ignoring time, so time in the returned ParsedDateTime is always 0:0:0.
/// If year of the date was not found then it accepts the current year.
/// </summary>
/// <param name="str">string that contains date</param>
/// <param name="default_format">format that must be used preferably in ambivalent instances</param>
/// <param name="parsed_date">parsed date output</param>
/// <returns>true if date was found, else false</returns>
static public bool TryParseDate(string str, DateTimeFormat default_format, out ParsedDateTime parsed_date)
{
lock (lock_variable)
{
parsed_date = null;
if (string.IsNullOrEmpty(str))
return false;
//look for dd/mm/yy
Match m = Regex.Match(str, @"(?<=^|[^\d])(?'day'\d{1,2})\s*(?'separator'[\\/\.])+\s*(?'month'\d{1,2})\s*\'separator'+\s*(?'year'\d{2,4})(?=$|[^\d])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (m.Success && m.Groups["year"].Value.Length != 3)
{
System.DateTime date;
if ((default_format ^ DateTimeFormat.USA_DATE) == DateTimeFormat.USA_DATE)
{
if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["day"].Value), int.Parse(m.Groups["month"].Value), out date))
return false;
}
else
{
if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["month"].Value), int.Parse(m.Groups["day"].Value), out date))
return false;
}
parsed_date = new ParsedDateTime(m.Index, m.Length, -1, -1, date);
return true;
}
//look for yy-mm-dd
m = Regex.Match(str, @"(?<=^|[^\d])(?'year'\d{2,4})\s*(?'separator'[\-])\s*(?'month'\d{1,2})\s*\'separator'+\s*(?'day'\d{1,2})(?=$|[^\d])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (m.Success && m.Groups["year"].Value.Length != 3)
{
System.DateTime date;
if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["month"].Value), int.Parse(m.Groups["day"].Value), out date))
return false;
parsed_date = new ParsedDateTime(m.Index, m.Length, -1, -1, date);
return true;
}
//look for month dd yyyy
m = Regex.Match(str, @"(?:^|[^\d\w])(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th)?\s*,?\s*(?'year'\d{4})(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (!m.Success)
//look for dd month [yy]yy
m = Regex.Match(str, @"(?:^|[^\d\w:])(?'day'\d{1,2})(?:-?st|-?th)?\s+(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*(?:\s*,?\s*(?:'?(?'year'\d{2})|(?'year'\d{4})))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (!m.Success)
//look for yyyy month dd
m = Regex.Match(str, @"(?:^|[^\d\w])(?'year'\d{4})\s+(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th)?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (!m.Success)
//look for month dd [yyyy]
m = Regex.Match(str, @"(?:^|[^\d\w])(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th)?(?:\s*,?\s*(?'year'\d{4}))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (m.Success)
{
int month = -1;
int index_of_date = m.Index;
int length_of_date = m.Length;
switch (m.Groups["month"].Value)
{
case "Jan":
month = 1;
break;
case "Feb":
month = 2;
break;
case "Mar":
month = 3;
break;
case "Apr":
month = 4;
break;
case "May":
month = 5;
break;
case "Jun":
month = 6;
break;
case "Jul":
month = 7;
break;
case "Aug":
month = 8;
break;
case "Sep":
month = 9;
break;
case "Oct":
month = 10;
break;
case "Nov":
month = 11;
break;
case "Dec":
month = 12;
break;
}
int year;
if (!string.IsNullOrEmpty(m.Groups["year"].Value))
year = int.Parse(m.Groups["year"].Value);
else
year = DefaultDate.Year;
System.DateTime date;
if (!convert_to_date(year, month, int.Parse(m.Groups["day"].Value), out date))
return false;
parsed_date = new ParsedDateTime(index_of_date, length_of_date, -1, -1, date);
return true;
}
return false;
}
}
static bool convert_to_date(int year, int month, int day, out System.DateTime date)
{
if (year >= 100)
{
if (year < 1000)
{
date = new System.DateTime(1, 1, 1);
return false;
}
}
else
if (year > 30)
year += 1900;
else
year += 2000;
try
{
date = new System.DateTime(year, month, day);
}
catch
{
date = new System.DateTime(1, 1, 1);
return false;
}
return true;
}
#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.Text;
using System.Globalization;
using log4net.Core;
using log4net.Layout;
using log4net.Util;
namespace log4net.Appender
{
/// <summary>
/// Appends logging events to the terminal using ANSI color escape sequences.
/// </summary>
/// <remarks>
/// <para>
/// AnsiColorTerminalAppender appends log events to the standard output stream
/// or the error output stream using a layout specified by the
/// user. It also allows the color of a specific level of message to be set.
/// </para>
/// <note>
/// This appender expects the terminal to understand the VT100 control set
/// in order to interpret the color codes. If the terminal or console does not
/// understand the control codes the behavior is not defined.
/// </note>
/// <para>
/// By default, all output is written to the console's standard output stream.
/// The <see cref="Target"/> property can be set to direct the output to the
/// error stream.
/// </para>
/// <para>
/// NOTE: This appender writes each message to the <c>System.Console.Out</c> or
/// <c>System.Console.Error</c> that is set at the time the event is appended.
/// Therefore it is possible to programmatically redirect the output of this appender
/// (for example NUnit does this to capture program output). While this is the desired
/// behavior of this appender it may have security implications in your application.
/// </para>
/// <para>
/// When configuring the ANSI colored terminal appender, a mapping should be
/// specified to map a logging level to a color. For example:
/// </para>
/// <code lang="XML" escaped="true">
/// <mapping>
/// <level value="ERROR" />
/// <foreColor value="White" />
/// <backColor value="Red" />
/// <attributes value="Bright,Underscore" />
/// </mapping>
/// <mapping>
/// <level value="DEBUG" />
/// <backColor value="Green" />
/// </mapping>
/// </code>
/// <para>
/// The Level is the standard log4net logging level and ForeColor and BackColor can be any
/// of the following values:
/// <list type="bullet">
/// <item><term>Blue</term><description></description></item>
/// <item><term>Green</term><description></description></item>
/// <item><term>Red</term><description></description></item>
/// <item><term>White</term><description></description></item>
/// <item><term>Yellow</term><description></description></item>
/// <item><term>Purple</term><description></description></item>
/// <item><term>Cyan</term><description></description></item>
/// </list>
/// These color values cannot be combined together to make new colors.
/// </para>
/// <para>
/// The attributes can be any combination of the following:
/// <list type="bullet">
/// <item><term>Bright</term><description>foreground is brighter</description></item>
/// <item><term>Dim</term><description>foreground is dimmer</description></item>
/// <item><term>Underscore</term><description>message is underlined</description></item>
/// <item><term>Blink</term><description>foreground is blinking (does not work on all terminals)</description></item>
/// <item><term>Reverse</term><description>foreground and background are reversed</description></item>
/// <item><term>Hidden</term><description>output is hidden</description></item>
/// <item><term>Strikethrough</term><description>message has a line through it</description></item>
/// </list>
/// While any of these attributes may be combined together not all combinations
/// work well together, for example setting both <i>Bright</i> and <i>Dim</i> attributes makes
/// no sense.
/// </para>
/// </remarks>
/// <author>Patrick Wagstrom</author>
/// <author>Nicko Cadell</author>
public class AnsiColorTerminalAppender : AppenderSkeleton
{
#region Colors Enum
/// <summary>
/// The enum of possible display attributes
/// </summary>
/// <remarks>
/// <para>
/// The following flags can be combined together to
/// form the ANSI color attributes.
/// </para>
/// </remarks>
/// <seealso cref="AnsiColorTerminalAppender" />
[Flags]
public enum AnsiAttributes : int
{
/// <summary>
/// text is bright
/// </summary>
Bright = 1,
/// <summary>
/// text is dim
/// </summary>
Dim = 2,
/// <summary>
/// text is underlined
/// </summary>
Underscore = 4,
/// <summary>
/// text is blinking
/// </summary>
/// <remarks>
/// Not all terminals support this attribute
/// </remarks>
Blink = 8,
/// <summary>
/// text and background colors are reversed
/// </summary>
Reverse = 16,
/// <summary>
/// text is hidden
/// </summary>
Hidden = 32,
/// <summary>
/// text is displayed with a strikethrough
/// </summary>
Strikethrough = 64,
/// <summary>
/// text color is light
/// </summary>
Light = 128
}
/// <summary>
/// The enum of possible foreground or background color values for
/// use with the color mapping method
/// </summary>
/// <remarks>
/// <para>
/// The output can be in one for the following ANSI colors.
/// </para>
/// </remarks>
/// <seealso cref="AnsiColorTerminalAppender" />
public enum AnsiColor : int
{
/// <summary>
/// color is black
/// </summary>
Black = 0,
/// <summary>
/// color is red
/// </summary>
Red = 1,
/// <summary>
/// color is green
/// </summary>
Green = 2,
/// <summary>
/// color is yellow
/// </summary>
Yellow = 3,
/// <summary>
/// color is blue
/// </summary>
Blue = 4,
/// <summary>
/// color is magenta
/// </summary>
Magenta = 5,
/// <summary>
/// color is cyan
/// </summary>
Cyan = 6,
/// <summary>
/// color is white
/// </summary>
White = 7
}
#endregion
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="AnsiColorTerminalAppender" /> class.
/// </summary>
/// <remarks>
/// The instance of the <see cref="AnsiColorTerminalAppender" /> class is set up to write
/// to the standard output stream.
/// </remarks>
public AnsiColorTerminalAppender()
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Target is the value of the console output stream.
/// </summary>
/// <value>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </value>
/// <remarks>
/// <para>
/// Target is the value of the console output stream.
/// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>.
/// </para>
/// </remarks>
virtual public string Target
{
get { return m_writeToErrorStream ? ConsoleError : ConsoleOut; }
set
{
string trimmedTargetName = value.Trim();
if (string.Compare(ConsoleError, trimmedTargetName, true, CultureInfo.InvariantCulture) == 0)
{
m_writeToErrorStream = true;
}
else
{
m_writeToErrorStream = false;
}
}
}
/// <summary>
/// Add a mapping of level to color
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Add a <see cref="LevelColors"/> mapping to this appender.
/// Each mapping defines the foreground and background colours
/// for a level.
/// </para>
/// </remarks>
public void AddMapping(LevelColors mapping)
{
m_levelMapping.Add(mapping);
}
#endregion Public Instance Properties
#region Override implementation of AppenderSkeleton
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes the event to the console.
/// </para>
/// <para>
/// The format of the output will depend on the appender's layout.
/// </para>
/// </remarks>
override protected void Append(log4net.Core.LoggingEvent loggingEvent)
{
string loggingMessage = RenderLoggingEvent(loggingEvent);
// see if there is a specified lookup.
LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors;
if (levelColors != null)
{
// Prepend the Ansi Color code
loggingMessage = levelColors.CombinedColor + loggingMessage;
}
// on most terminals there are weird effects if we don't clear the background color
// before the new line. This checks to see if it ends with a newline, and if
// so, inserts the clear codes before the newline, otherwise the clear codes
// are inserted afterwards.
if (loggingMessage.Length > 1)
{
if (loggingMessage.EndsWith("\r\n") || loggingMessage.EndsWith("\n\r"))
{
loggingMessage = loggingMessage.Insert(loggingMessage.Length - 2, PostEventCodes);
}
else if (loggingMessage.EndsWith("\n") || loggingMessage.EndsWith("\r"))
{
loggingMessage = loggingMessage.Insert(loggingMessage.Length - 1, PostEventCodes);
}
else
{
loggingMessage = loggingMessage + PostEventCodes;
}
}
else
{
if (loggingMessage[0] == '\n' || loggingMessage[0] == '\r')
{
loggingMessage = PostEventCodes + loggingMessage;
}
else
{
loggingMessage = loggingMessage + PostEventCodes;
}
}
if (m_writeToErrorStream)
{
// Write to the error stream
Console.Error.Write(loggingMessage);
}
else
{
// Write to the output stream
Console.Write(loggingMessage);
}
}
/// <summary>
/// This appender requires a <see cref="Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
/// <summary>
/// Initialize the options for this appender
/// </summary>
/// <remarks>
/// <para>
/// Initialize the level to color mappings set on this appender.
/// </para>
/// </remarks>
public override void ActivateOptions()
{
base.ActivateOptions();
m_levelMapping.ActivateOptions();
}
#endregion Override implementation of AppenderSkeleton
#region Public Static Fields
/// <summary>
/// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console
/// standard output stream.
/// </para>
/// </remarks>
public const string ConsoleOut = "Console.Out";
/// <summary>
/// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="AnsiColorTerminalAppender.Target"/> to use when writing to the Console
/// standard error output stream.
/// </para>
/// </remarks>
public const string ConsoleError = "Console.Error";
#endregion Public Static Fields
#region Private Instances Fields
/// <summary>
/// Flag to write output to the error stream rather than the standard output stream
/// </summary>
private bool m_writeToErrorStream = false;
/// <summary>
/// Mapping from level object to color value
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
/// <summary>
/// Ansi code to reset terminal
/// </summary>
private const string PostEventCodes = "\x1b[0m";
#endregion Private Instances Fields
#region LevelColors LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the color it should be displayed as.
/// </summary>
/// <remarks>
/// <para>
/// Defines the mapping between a level and the color it should be displayed in.
/// </para>
/// </remarks>
public class LevelColors : LevelMappingEntry
{
private AnsiColor m_foreColor;
private AnsiColor m_backColor;
private AnsiAttributes m_attributes;
private string m_combinedColor = "";
/// <summary>
/// The mapped foreground color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped foreground color for the specified level
/// </para>
/// </remarks>
public AnsiColor ForeColor
{
get { return m_foreColor; }
set { m_foreColor = value; }
}
/// <summary>
/// The mapped background color for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped background color for the specified level
/// </para>
/// </remarks>
public AnsiColor BackColor
{
get { return m_backColor; }
set { m_backColor = value; }
}
/// <summary>
/// The color attributes for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The color attributes for the specified level
/// </para>
/// </remarks>
public AnsiAttributes Attributes
{
get { return m_attributes; }
set { m_attributes = value; }
}
/// <summary>
/// Initialize the options for the object
/// </summary>
/// <remarks>
/// <para>
/// Combine the <see cref="ForeColor"/> and <see cref="BackColor"/> together
/// and append the attributes.
/// </para>
/// </remarks>
public override void ActivateOptions()
{
base.ActivateOptions();
StringBuilder buf = new StringBuilder();
// Reset any existing codes
buf.Append("\x1b[0;");
int lightAdjustment = ((m_attributes & AnsiAttributes.Light) > 0) ? 60 : 0;
// set the foreground color
buf.Append(30 + lightAdjustment + (int)m_foreColor);
buf.Append(';');
// set the background color
buf.Append(40 + lightAdjustment + (int)m_backColor);
// set the attributes
if ((m_attributes & AnsiAttributes.Bright) > 0)
{
buf.Append(";1");
}
if ((m_attributes & AnsiAttributes.Dim) > 0)
{
buf.Append(";2");
}
if ((m_attributes & AnsiAttributes.Underscore) > 0)
{
buf.Append(";4");
}
if ((m_attributes & AnsiAttributes.Blink) > 0)
{
buf.Append(";5");
}
if ((m_attributes & AnsiAttributes.Reverse) > 0)
{
buf.Append(";7");
}
if ((m_attributes & AnsiAttributes.Hidden) > 0)
{
buf.Append(";8");
}
if ((m_attributes & AnsiAttributes.Strikethrough) > 0)
{
buf.Append(";9");
}
buf.Append('m');
m_combinedColor = buf.ToString();
}
/// <summary>
/// The combined <see cref="ForeColor"/>, <see cref="BackColor"/> and
/// <see cref="Attributes"/> suitable for setting the ansi terminal color.
/// </summary>
internal string CombinedColor
{
get { return m_combinedColor; }
}
}
#endregion // LevelColors LevelMapping Entry
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Translate.V3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedTranslationServiceClientTest
{
[xunit::FactAttribute]
public void TranslateTextRequestObject()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateTextRequest request = new TranslateTextRequest
{
Contents =
{
"contents8c7dbf98",
},
MimeType = "mime_type606a0ffc",
SourceLanguageCode = "source_language_code14998292",
TargetLanguageCode = "target_language_code6ec12c87",
Model = "model635ef320",
GlossaryConfig = new TranslateTextGlossaryConfig(),
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
TranslateTextResponse expectedResponse = new TranslateTextResponse
{
Translations = { new Translation(), },
GlossaryTranslations = { new Translation(), },
};
mockGrpcClient.Setup(x => x.TranslateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateTextResponse response = client.TranslateText(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TranslateTextRequestObjectAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateTextRequest request = new TranslateTextRequest
{
Contents =
{
"contents8c7dbf98",
},
MimeType = "mime_type606a0ffc",
SourceLanguageCode = "source_language_code14998292",
TargetLanguageCode = "target_language_code6ec12c87",
Model = "model635ef320",
GlossaryConfig = new TranslateTextGlossaryConfig(),
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
TranslateTextResponse expectedResponse = new TranslateTextResponse
{
Translations = { new Translation(), },
GlossaryTranslations = { new Translation(), },
};
mockGrpcClient.Setup(x => x.TranslateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateTextResponse responseCallSettings = await client.TranslateTextAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TranslateTextResponse responseCancellationToken = await client.TranslateTextAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TranslateText1()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateTextRequest request = new TranslateTextRequest
{
Contents =
{
"contents8c7dbf98",
},
TargetLanguageCode = "target_language_code6ec12c87",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
TranslateTextResponse expectedResponse = new TranslateTextResponse
{
Translations = { new Translation(), },
GlossaryTranslations = { new Translation(), },
};
mockGrpcClient.Setup(x => x.TranslateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateTextResponse response = client.TranslateText(request.Parent, request.TargetLanguageCode, request.Contents);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TranslateText1Async()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateTextRequest request = new TranslateTextRequest
{
Contents =
{
"contents8c7dbf98",
},
TargetLanguageCode = "target_language_code6ec12c87",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
TranslateTextResponse expectedResponse = new TranslateTextResponse
{
Translations = { new Translation(), },
GlossaryTranslations = { new Translation(), },
};
mockGrpcClient.Setup(x => x.TranslateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateTextResponse responseCallSettings = await client.TranslateTextAsync(request.Parent, request.TargetLanguageCode, request.Contents, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TranslateTextResponse responseCancellationToken = await client.TranslateTextAsync(request.Parent, request.TargetLanguageCode, request.Contents, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TranslateText1ResourceNames()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateTextRequest request = new TranslateTextRequest
{
Contents =
{
"contents8c7dbf98",
},
TargetLanguageCode = "target_language_code6ec12c87",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
TranslateTextResponse expectedResponse = new TranslateTextResponse
{
Translations = { new Translation(), },
GlossaryTranslations = { new Translation(), },
};
mockGrpcClient.Setup(x => x.TranslateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateTextResponse response = client.TranslateText(request.ParentAsLocationName, request.TargetLanguageCode, request.Contents);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TranslateText1ResourceNamesAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateTextRequest request = new TranslateTextRequest
{
Contents =
{
"contents8c7dbf98",
},
TargetLanguageCode = "target_language_code6ec12c87",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
TranslateTextResponse expectedResponse = new TranslateTextResponse
{
Translations = { new Translation(), },
GlossaryTranslations = { new Translation(), },
};
mockGrpcClient.Setup(x => x.TranslateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateTextResponse responseCallSettings = await client.TranslateTextAsync(request.ParentAsLocationName, request.TargetLanguageCode, request.Contents, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TranslateTextResponse responseCancellationToken = await client.TranslateTextAsync(request.ParentAsLocationName, request.TargetLanguageCode, request.Contents, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TranslateText2()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateTextRequest request = new TranslateTextRequest
{
Contents =
{
"contents8c7dbf98",
},
MimeType = "mime_type606a0ffc",
SourceLanguageCode = "source_language_code14998292",
TargetLanguageCode = "target_language_code6ec12c87",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
TranslateTextResponse expectedResponse = new TranslateTextResponse
{
Translations = { new Translation(), },
GlossaryTranslations = { new Translation(), },
};
mockGrpcClient.Setup(x => x.TranslateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateTextResponse response = client.TranslateText(request.Parent, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TranslateText2Async()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateTextRequest request = new TranslateTextRequest
{
Contents =
{
"contents8c7dbf98",
},
MimeType = "mime_type606a0ffc",
SourceLanguageCode = "source_language_code14998292",
TargetLanguageCode = "target_language_code6ec12c87",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
TranslateTextResponse expectedResponse = new TranslateTextResponse
{
Translations = { new Translation(), },
GlossaryTranslations = { new Translation(), },
};
mockGrpcClient.Setup(x => x.TranslateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateTextResponse responseCallSettings = await client.TranslateTextAsync(request.Parent, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TranslateTextResponse responseCancellationToken = await client.TranslateTextAsync(request.Parent, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TranslateText2ResourceNames()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateTextRequest request = new TranslateTextRequest
{
Contents =
{
"contents8c7dbf98",
},
MimeType = "mime_type606a0ffc",
SourceLanguageCode = "source_language_code14998292",
TargetLanguageCode = "target_language_code6ec12c87",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
TranslateTextResponse expectedResponse = new TranslateTextResponse
{
Translations = { new Translation(), },
GlossaryTranslations = { new Translation(), },
};
mockGrpcClient.Setup(x => x.TranslateText(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateTextResponse response = client.TranslateText(request.ParentAsLocationName, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TranslateText2ResourceNamesAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateTextRequest request = new TranslateTextRequest
{
Contents =
{
"contents8c7dbf98",
},
MimeType = "mime_type606a0ffc",
SourceLanguageCode = "source_language_code14998292",
TargetLanguageCode = "target_language_code6ec12c87",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
TranslateTextResponse expectedResponse = new TranslateTextResponse
{
Translations = { new Translation(), },
GlossaryTranslations = { new Translation(), },
};
mockGrpcClient.Setup(x => x.TranslateTextAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateTextResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateTextResponse responseCallSettings = await client.TranslateTextAsync(request.ParentAsLocationName, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TranslateTextResponse responseCancellationToken = await client.TranslateTextAsync(request.ParentAsLocationName, request.Model, request.MimeType, request.SourceLanguageCode, request.TargetLanguageCode, request.Contents, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DetectLanguageRequestObject()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DetectLanguageRequest request = new DetectLanguageRequest
{
Content = "contentb964039a",
MimeType = "mime_type606a0ffc",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
DetectLanguageResponse expectedResponse = new DetectLanguageResponse
{
Languages =
{
new DetectedLanguage(),
},
};
mockGrpcClient.Setup(x => x.DetectLanguage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
DetectLanguageResponse response = client.DetectLanguage(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DetectLanguageRequestObjectAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DetectLanguageRequest request = new DetectLanguageRequest
{
Content = "contentb964039a",
MimeType = "mime_type606a0ffc",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
DetectLanguageResponse expectedResponse = new DetectLanguageResponse
{
Languages =
{
new DetectedLanguage(),
},
};
mockGrpcClient.Setup(x => x.DetectLanguageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DetectLanguageResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
DetectLanguageResponse responseCallSettings = await client.DetectLanguageAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
DetectLanguageResponse responseCancellationToken = await client.DetectLanguageAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DetectLanguage()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DetectLanguageRequest request = new DetectLanguageRequest
{
Content = "contentb964039a",
MimeType = "mime_type606a0ffc",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
DetectLanguageResponse expectedResponse = new DetectLanguageResponse
{
Languages =
{
new DetectedLanguage(),
},
};
mockGrpcClient.Setup(x => x.DetectLanguage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
DetectLanguageResponse response = client.DetectLanguage(request.Parent, request.Model, request.MimeType, request.Content);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DetectLanguageAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DetectLanguageRequest request = new DetectLanguageRequest
{
Content = "contentb964039a",
MimeType = "mime_type606a0ffc",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
DetectLanguageResponse expectedResponse = new DetectLanguageResponse
{
Languages =
{
new DetectedLanguage(),
},
};
mockGrpcClient.Setup(x => x.DetectLanguageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DetectLanguageResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
DetectLanguageResponse responseCallSettings = await client.DetectLanguageAsync(request.Parent, request.Model, request.MimeType, request.Content, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
DetectLanguageResponse responseCancellationToken = await client.DetectLanguageAsync(request.Parent, request.Model, request.MimeType, request.Content, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DetectLanguageResourceNames()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DetectLanguageRequest request = new DetectLanguageRequest
{
Content = "contentb964039a",
MimeType = "mime_type606a0ffc",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
DetectLanguageResponse expectedResponse = new DetectLanguageResponse
{
Languages =
{
new DetectedLanguage(),
},
};
mockGrpcClient.Setup(x => x.DetectLanguage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
DetectLanguageResponse response = client.DetectLanguage(request.ParentAsLocationName, request.Model, request.MimeType, request.Content);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DetectLanguageResourceNamesAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DetectLanguageRequest request = new DetectLanguageRequest
{
Content = "contentb964039a",
MimeType = "mime_type606a0ffc",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
DetectLanguageResponse expectedResponse = new DetectLanguageResponse
{
Languages =
{
new DetectedLanguage(),
},
};
mockGrpcClient.Setup(x => x.DetectLanguageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DetectLanguageResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
DetectLanguageResponse responseCallSettings = await client.DetectLanguageAsync(request.ParentAsLocationName, request.Model, request.MimeType, request.Content, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
DetectLanguageResponse responseCancellationToken = await client.DetectLanguageAsync(request.ParentAsLocationName, request.Model, request.MimeType, request.Content, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSupportedLanguagesRequestObject()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
{
DisplayLanguageCode = "display_language_code67946a7b",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
SupportedLanguages expectedResponse = new SupportedLanguages
{
Languages =
{
new SupportedLanguage(),
},
};
mockGrpcClient.Setup(x => x.GetSupportedLanguages(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
SupportedLanguages response = client.GetSupportedLanguages(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSupportedLanguagesRequestObjectAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
{
DisplayLanguageCode = "display_language_code67946a7b",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
SupportedLanguages expectedResponse = new SupportedLanguages
{
Languages =
{
new SupportedLanguage(),
},
};
mockGrpcClient.Setup(x => x.GetSupportedLanguagesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SupportedLanguages>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
SupportedLanguages responseCallSettings = await client.GetSupportedLanguagesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SupportedLanguages responseCancellationToken = await client.GetSupportedLanguagesAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSupportedLanguages()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
{
DisplayLanguageCode = "display_language_code67946a7b",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
SupportedLanguages expectedResponse = new SupportedLanguages
{
Languages =
{
new SupportedLanguage(),
},
};
mockGrpcClient.Setup(x => x.GetSupportedLanguages(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
SupportedLanguages response = client.GetSupportedLanguages(request.Parent, request.Model, request.DisplayLanguageCode);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSupportedLanguagesAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
{
DisplayLanguageCode = "display_language_code67946a7b",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
SupportedLanguages expectedResponse = new SupportedLanguages
{
Languages =
{
new SupportedLanguage(),
},
};
mockGrpcClient.Setup(x => x.GetSupportedLanguagesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SupportedLanguages>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
SupportedLanguages responseCallSettings = await client.GetSupportedLanguagesAsync(request.Parent, request.Model, request.DisplayLanguageCode, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SupportedLanguages responseCancellationToken = await client.GetSupportedLanguagesAsync(request.Parent, request.Model, request.DisplayLanguageCode, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSupportedLanguagesResourceNames()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
{
DisplayLanguageCode = "display_language_code67946a7b",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
SupportedLanguages expectedResponse = new SupportedLanguages
{
Languages =
{
new SupportedLanguage(),
},
};
mockGrpcClient.Setup(x => x.GetSupportedLanguages(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
SupportedLanguages response = client.GetSupportedLanguages(request.ParentAsLocationName, request.Model, request.DisplayLanguageCode);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSupportedLanguagesResourceNamesAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
{
DisplayLanguageCode = "display_language_code67946a7b",
Model = "model635ef320",
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
};
SupportedLanguages expectedResponse = new SupportedLanguages
{
Languages =
{
new SupportedLanguage(),
},
};
mockGrpcClient.Setup(x => x.GetSupportedLanguagesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SupportedLanguages>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
SupportedLanguages responseCallSettings = await client.GetSupportedLanguagesAsync(request.ParentAsLocationName, request.Model, request.DisplayLanguageCode, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
SupportedLanguages responseCancellationToken = await client.GetSupportedLanguagesAsync(request.ParentAsLocationName, request.Model, request.DisplayLanguageCode, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TranslateDocumentRequestObject()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateDocumentRequest request = new TranslateDocumentRequest
{
Parent = "parent7858e4d0",
SourceLanguageCode = "source_language_code14998292",
TargetLanguageCode = "target_language_code6ec12c87",
DocumentInputConfig = new DocumentInputConfig(),
DocumentOutputConfig = new DocumentOutputConfig(),
Model = "model635ef320",
GlossaryConfig = new TranslateTextGlossaryConfig(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
TranslateDocumentResponse expectedResponse = new TranslateDocumentResponse
{
DocumentTranslation = new DocumentTranslation(),
GlossaryDocumentTranslation = new DocumentTranslation(),
Model = "model635ef320",
GlossaryConfig = new TranslateTextGlossaryConfig(),
};
mockGrpcClient.Setup(x => x.TranslateDocument(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateDocumentResponse response = client.TranslateDocument(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TranslateDocumentRequestObjectAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
TranslateDocumentRequest request = new TranslateDocumentRequest
{
Parent = "parent7858e4d0",
SourceLanguageCode = "source_language_code14998292",
TargetLanguageCode = "target_language_code6ec12c87",
DocumentInputConfig = new DocumentInputConfig(),
DocumentOutputConfig = new DocumentOutputConfig(),
Model = "model635ef320",
GlossaryConfig = new TranslateTextGlossaryConfig(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
};
TranslateDocumentResponse expectedResponse = new TranslateDocumentResponse
{
DocumentTranslation = new DocumentTranslation(),
GlossaryDocumentTranslation = new DocumentTranslation(),
Model = "model635ef320",
GlossaryConfig = new TranslateTextGlossaryConfig(),
};
mockGrpcClient.Setup(x => x.TranslateDocumentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TranslateDocumentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
TranslateDocumentResponse responseCallSettings = await client.TranslateDocumentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TranslateDocumentResponse responseCancellationToken = await client.TranslateDocumentAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGlossaryRequestObject()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGlossaryRequest request = new GetGlossaryRequest
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
};
Glossary expectedResponse = new Glossary
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
LanguagePair = new Glossary.Types.LanguageCodePair(),
LanguageCodesSet = new Glossary.Types.LanguageCodesSet(),
InputConfig = new GlossaryInputConfig(),
EntryCount = -1925390589,
SubmitTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetGlossary(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
Glossary response = client.GetGlossary(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGlossaryRequestObjectAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGlossaryRequest request = new GetGlossaryRequest
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
};
Glossary expectedResponse = new Glossary
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
LanguagePair = new Glossary.Types.LanguageCodePair(),
LanguageCodesSet = new Glossary.Types.LanguageCodesSet(),
InputConfig = new GlossaryInputConfig(),
EntryCount = -1925390589,
SubmitTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetGlossaryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Glossary>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
Glossary responseCallSettings = await client.GetGlossaryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Glossary responseCancellationToken = await client.GetGlossaryAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGlossary()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGlossaryRequest request = new GetGlossaryRequest
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
};
Glossary expectedResponse = new Glossary
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
LanguagePair = new Glossary.Types.LanguageCodePair(),
LanguageCodesSet = new Glossary.Types.LanguageCodesSet(),
InputConfig = new GlossaryInputConfig(),
EntryCount = -1925390589,
SubmitTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetGlossary(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
Glossary response = client.GetGlossary(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGlossaryAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGlossaryRequest request = new GetGlossaryRequest
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
};
Glossary expectedResponse = new Glossary
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
LanguagePair = new Glossary.Types.LanguageCodePair(),
LanguageCodesSet = new Glossary.Types.LanguageCodesSet(),
InputConfig = new GlossaryInputConfig(),
EntryCount = -1925390589,
SubmitTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetGlossaryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Glossary>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
Glossary responseCallSettings = await client.GetGlossaryAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Glossary responseCancellationToken = await client.GetGlossaryAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGlossaryResourceNames()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGlossaryRequest request = new GetGlossaryRequest
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
};
Glossary expectedResponse = new Glossary
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
LanguagePair = new Glossary.Types.LanguageCodePair(),
LanguageCodesSet = new Glossary.Types.LanguageCodesSet(),
InputConfig = new GlossaryInputConfig(),
EntryCount = -1925390589,
SubmitTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetGlossary(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
Glossary response = client.GetGlossary(request.GlossaryName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGlossaryResourceNamesAsync()
{
moq::Mock<TranslationService.TranslationServiceClient> mockGrpcClient = new moq::Mock<TranslationService.TranslationServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGlossaryRequest request = new GetGlossaryRequest
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
};
Glossary expectedResponse = new Glossary
{
GlossaryName = GlossaryName.FromProjectLocationGlossary("[PROJECT]", "[LOCATION]", "[GLOSSARY]"),
LanguagePair = new Glossary.Types.LanguageCodePair(),
LanguageCodesSet = new Glossary.Types.LanguageCodesSet(),
InputConfig = new GlossaryInputConfig(),
EntryCount = -1925390589,
SubmitTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetGlossaryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Glossary>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TranslationServiceClient client = new TranslationServiceClientImpl(mockGrpcClient.Object, null);
Glossary responseCallSettings = await client.GetGlossaryAsync(request.GlossaryName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Glossary responseCancellationToken = await client.GetGlossaryAsync(request.GlossaryName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Xunit;
public class VersionTests
{
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void TestCtor_String(string input, Version expected)
{
Assert.Equal(expected, new Version(input));
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void TestCtor_String_Invalid(string input, Type exceptionType)
{
Assert.Throws(exceptionType, () => new Version(input)); // Input is invalid
}
[Theory]
[InlineData(0, 0)]
[InlineData(2, 3)]
[InlineData(int.MaxValue, int.MaxValue)]
public static void TestCtor_Int_Int(int major, int minor)
{
VerifyVersion(new Version(major, minor), major, minor, -1, -1);
}
[Fact]
public static void TestCtor_Int_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0)); // Major < 0
Assert.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1)); // Minor < 0
}
[Theory]
[InlineData(0, 0, 0)]
[InlineData(2, 3, 4)]
[InlineData(int.MaxValue, int.MaxValue, int.MaxValue)]
public static void TestCtor_Int_Int_Int(int major, int minor, int build)
{
VerifyVersion(new Version(major, minor, build), major, minor, build, -1);
}
[Fact]
public static void TestCtor_Int_Int_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0)); // Major < 0
Assert.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0)); // Minor < 0
Assert.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1)); // Build < 0
}
[Theory]
[InlineData(0, 0, 0, 0)]
[InlineData(2, 3, 4, 7)]
[InlineData(2, 3, 4, 32767)]
[InlineData(2, 3, 4, 32768)]
[InlineData(2, 3, 4, 65535)]
[InlineData(2, 3, 4, 65536)]
[InlineData(2, 3, 4, 2147483647)]
[InlineData(2, 3, 4, 2147450879)]
[InlineData(2, 3, 4, 2147418112)]
[InlineData(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue)]
public static void TestCtor_Int_Int_Int_Int(int major, int minor, int build, int revision)
{
VerifyVersion(new Version(major, minor, build, revision), major, minor, build, revision);
}
[Fact]
public static void TestCtor_Int_Int_Int_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0, 0)); // Major < 0
Assert.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0, 0)); // Minor < 0
Assert.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1, 0)); // Build < 0
Assert.Throws<ArgumentOutOfRangeException>("revision", () => new Version(0, 0, 0, -1)); // Revision < 0
}
public static IEnumerable<object[]> CompareToTestData()
{
yield return new object[] { new Version(1, 2), null, 1 };
yield return new object[] { new Version(1, 2), new Version(1, 2), 0 };
yield return new object[] { new Version(1, 2), new Version(1, 3), -1 };
yield return new object[] { new Version(1, 2), new Version(1, 1), 1 };
yield return new object[] { new Version(1, 2), new Version(2, 0), -1 };
yield return new object[] { new Version(1, 2), new Version(1, 2, 1), -1 };
yield return new object[] { new Version(1, 2), new Version(1, 2, 0, 1), -1 };
yield return new object[] { new Version(1, 2), new Version(1, 0), 1 };
yield return new object[] { new Version(1, 2), new Version(1, 0, 1), 1 };
yield return new object[] { new Version(1, 2), new Version(1, 0, 0, 1), 1 };
yield return new object[] { new Version(3, 2, 1), new Version(2, 2, 1), 1 };
yield return new object[] { new Version(3, 2, 1), new Version(3, 1, 1), 1 };
yield return new object[] { new Version(3, 2, 1), new Version(3, 2, 0), 1 };
yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 4), 0 };
yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 5), -1 };
yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 3), 1 };
}
[Theory]
[MemberData(nameof(CompareToTestData))]
public static void TestCompareTo(Version version1, Version version2, int expectedSign)
{
Assert.Equal(expectedSign, Math.Sign(version1.CompareTo(version2)));
if (version1 != null && version2 != null)
{
if (expectedSign >= 0)
{
Assert.True(version1 >= version2);
Assert.False(version1 < version2);
}
if (expectedSign > 0)
{
Assert.True(version1 > version2);
Assert.False(version1 <= version2);
}
if (expectedSign <= 0)
{
Assert.True(version1 <= version2);
Assert.False(version1 > version2);
}
if (expectedSign < 0)
{
Assert.True(version1 < version2);
Assert.False(version1 >= version2);
}
}
IComparable comparable = version1;
Assert.Equal(expectedSign, Math.Sign(comparable.CompareTo(version2)));
}
[Fact]
public static void TestCompareTo_Invalid()
{
IComparable comparable = new Version(1, 1);
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo(1)); // Obj is not a version
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("1.1")); // Obj is not a version
Version nullVersion = null;
Version testVersion = new Version(1, 2);
Assert.Throws<ArgumentNullException>("v1", () => testVersion >= nullVersion); // V2 is null
Assert.Throws<ArgumentNullException>("v1", () => testVersion > nullVersion); // V2 is null
Assert.Throws<ArgumentNullException>("v1", () => nullVersion < testVersion); // V1 is null
Assert.Throws<ArgumentNullException>("v1", () => nullVersion <= testVersion); // V1 is null
}
private static IEnumerable<object[]> EqualsTestData()
{
yield return new object[] { new Version(2, 3), new Version(2, 3), true };
yield return new object[] { new Version(2, 3), new Version(2, 4), false };
yield return new object[] { new Version(2, 3), new Version(3, 3), false };
yield return new object[] { new Version(2, 3, 4), new Version(2, 3, 4), true };
yield return new object[] { new Version(2, 3, 4), new Version(2, 3, 5), false };
yield return new object[] { new Version(2, 3, 4), new Version(2, 3), false };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4, 5), true };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4, 6), false };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3), false };
yield return new object[] { new Version(2, 3, 4, 5), new Version(2, 3, 4), false };
yield return new object[] { new Version(2, 3, 0), new Version(2, 3), false };
yield return new object[] { new Version(2, 3, 4, 0), new Version(2, 3, 4), false };
yield return new object[] { new Version(2, 3, 4, 5), new TimeSpan(), false };
yield return new object[] { new Version(2, 3, 4, 5), null, false };
}
[Theory]
[MemberData(nameof(EqualsTestData))]
public static void TestEquals(Version version1, object obj, bool expected)
{
Version version2 = obj as Version;
Assert.Equal(expected, version1.Equals(version2));
Assert.Equal(expected, version1.Equals(obj));
Assert.Equal(expected, version1 == version2);
Assert.Equal(!expected, version1 != version2);
if (version2 != null)
{
Assert.Equal(expected, version1.GetHashCode().Equals(version2.GetHashCode()));
}
}
private static IEnumerable<object[]> Parse_Valid_TestData()
{
yield return new object[] { "1.2", new Version(1, 2) };
yield return new object[] { "1.2.3", new Version(1, 2, 3) };
yield return new object[] { "1.2.3.4", new Version(1, 2, 3, 4) };
yield return new object[] { "2 .3. 4. \t\r\n15 ", new Version(2, 3, 4, 15) };
yield return new object[] { " 2 .3. 4. \t\r\n15 ", new Version(2, 3, 4, 15) };
yield return new object[] { "+1.+2.+3.+4", new Version(1, 2, 3, 4) };
}
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void TestParse(string input, Version expected)
{
Assert.Equal(expected, Version.Parse(input));
Version version;
Assert.True(Version.TryParse(input, out version));
Assert.Equal(expected, version);
}
private static IEnumerable<object[]> Parse_Invalid_TestData()
{
yield return new object[] { null, typeof(ArgumentNullException) }; // Input is null
yield return new object[] { "", typeof(ArgumentException) }; // Input is empty
yield return new object[] { "1,2,3,4", typeof(ArgumentException) }; // Input has fewer than 4 version components
yield return new object[] { "1", typeof(ArgumentException) }; // Input has fewer than 2 version components
yield return new object[] { "1.2.3.4.5", typeof(ArgumentException) }; // Input has more than 4 version components
yield return new object[] { "-1.2.3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "1.-2.3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "1.2.-3.4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "1.2.3.-4", typeof(ArgumentOutOfRangeException) }; // Input contains negative value
yield return new object[] { "b.2.3.4", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "1.b.3.4", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "1.2.b.4", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "1.2.3.b", typeof(FormatException) }; // Input contains non-numeric value
yield return new object[] { "2147483648.2.3.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue
yield return new object[] { "1.2147483648.3.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue
yield return new object[] { "1.2.2147483648.4", typeof(OverflowException) }; // Input contains a value > int.MaxValue
yield return new object[] { "1.2.3.2147483648", typeof(OverflowException) }; // Input contains a value > int.MaxValue
// Input contains a value < 0
yield return new object[] { "-1.2.3.4", typeof(ArgumentOutOfRangeException) };
yield return new object[] { "1.-2.3.4", typeof(ArgumentOutOfRangeException) };
yield return new object[] { "1.2.-3.4", typeof(ArgumentOutOfRangeException) };
yield return new object[] { "1.2.3.-4", typeof(ArgumentOutOfRangeException) };
}
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
public static void TestParse_Invalid(string input, Type exceptionType)
{
Assert.Throws(exceptionType, () => Version.Parse(input));
Version version;
Assert.False(Version.TryParse(input, out version));
Assert.Null(version);
}
public static IEnumerable<object[]> ToStringTestData()
{
yield return new object[] { new Version(1, 2), new string[] { "", "1", "1.2" } };
yield return new object[] { new Version(1, 2, 3), new string[] { "", "1", "1.2", "1.2.3" } };
yield return new object[] { new Version(1, 2, 3, 4), new string[] { "", "1", "1.2", "1.2.3", "1.2.3.4" } };
}
[Theory]
[MemberData(nameof(ToStringTestData))]
public static void TestToString(Version version, string[] expected)
{
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], version.ToString(i));
}
int maxFieldCount = expected.Length - 1;
Assert.Equal(expected[maxFieldCount], version.ToString());
Assert.Throws<ArgumentException>("fieldCount", () => version.ToString(-1)); // Index < 0
Assert.Throws<ArgumentException>("fieldCount", () => version.ToString(maxFieldCount + 1)); // Index > version.fieldCount
}
private static void VerifyVersion(Version version, int major, int minor, int build, int revision)
{
Assert.Equal(major, version.Major);
Assert.Equal(minor, version.Minor);
Assert.Equal(build, version.Build);
Assert.Equal(revision, version.Revision);
Assert.Equal((short)(revision >> 16), version.MajorRevision);
Assert.Equal((short)(revision & 0xFFFF), version.MinorRevision);
}
}
| |
using System;
using Eto.Parse.Scanners;
using System.Collections.Generic;
using System.Linq;
using Eto.Parse.Parsers;
using System.Diagnostics;
namespace Eto.Parse
{
/// <summary>
/// Flags to specify optimizations to apply to a grammar when initialized for the first match
/// </summary>
/// <remarks>
/// These may increase startup time for the first match, but usually increase performance on subsequent
/// matches with the same grammar instance.
/// </remarks>
[Flags]
public enum GrammarOptimizations
{
/// <summary>
/// No optimizations
/// </summary>
None = 0,
/// <summary>
/// Optimize alternations with only characters into a single character set parser
/// </summary>
CharacterSetAlternations = 1 << 0,
/// <summary>
/// Replace uncaptured unary parsers with their inner parser
/// </summary>
TrimUnnamedUnaryParsers = 1 << 1,
/// <summary>
/// Replace sequences and alternations with a single child
/// </summary>
TrimSingleItemSequencesOrAlterations = 1 << 2,
/// <summary>
/// Fix recursive grammars by replacing them with a repeating parser
/// </summary>
FixRecursiveGrammars = 1 << 3,
/// <summary>
/// All optimizations turned on
/// </summary>
All = CharacterSetAlternations | TrimUnnamedUnaryParsers | TrimSingleItemSequencesOrAlterations | FixRecursiveGrammars
}
/// <summary>
/// Defines the top level parser (a grammar) used to parse text
/// </summary>
public class Grammar : UnaryParser
{
bool initialized;
/// <summary>
/// Gets or sets a value indicating that the match events will be triggered after a successful match
/// </summary>
/// <value></value>
public bool EnableMatchEvents { get; set; }
/// <summary>
/// Gets or sets the separator to use for <see cref="Parsers.RepeatParser"/> and <see cref="Parsers.SequenceParser"/> if not explicitly defined.
/// </summary>
/// <value>The separator to use inbetween repeats and items of a sequence</value>
public Parser Separator { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this grammar is case sensitive or not
/// </summary>
/// <value><c>true</c> if case sensitive; otherwise, <c>false</c>.</value>
public bool CaseSensitive { get; set; }
/// <summary>
/// Gets or sets a value indicating whether a partial match of the input scanner is allowed
/// </summary>
/// <value><c>true</c> to allow a successful match if partially matched; otherwise, <c>false</c> to indicate that the entire input must be consumed to match.</value>
public bool AllowPartialMatch { get; set; }
public bool Trace { get; set; }
/// <summary>
/// Sets the maximum character set range when <see cref="GrammarOptimizations.CharacterSetAlternations"/> is enabled.
/// </summary>
/// <value></value>
public int MaxCharacterSetRangeOptimization { get; set; } = 100;
public GrammarOptimizations Optimizations { get; set; }
/// <summary>
/// Initializes a new copy of the <see cref="Eto.Parse.Grammar"/> class
/// </summary>
/// <param name="other">Other object to copy</param>
/// <param name="args">Arguments for the copy</param>
protected Grammar(Grammar other, ParserCloneArgs args)
{
this.EnableMatchEvents = other.EnableMatchEvents;
this.Separator = args.Clone(other.Separator);
this.CaseSensitive = other.CaseSensitive;
this.Optimizations = other.Optimizations;
}
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Parse.Grammar"/> class
/// </summary>
/// <param name="name">Name of the grammar</param>
/// <param name="rule">Top level grammar rule</param>
public Grammar(string name = null, Parser rule = null)
: base(name, rule)
{
CaseSensitive = true;
EnableMatchEvents = true;
Optimizations = GrammarOptimizations.All;
}
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Parse.Grammar"/> class
/// </summary>
/// <param name="rule">Top level grammar rule</param>
public Grammar(Parser rule)
: this(null, rule)
{
}
/// <summary>
/// Initializes this instance for parsing
/// </summary>
/// <remarks>
/// Initialization (usually) occurs only once, and should only be called after
/// the grammar is fully defined. This will be called automatically the first
/// time you call the <see cref="Match(string)"/> method.
/// </remarks>
public void Initialize()
{
if (Optimizations.HasFlag(GrammarOptimizations.CharacterSetAlternations))
{
OptimizeCharacterSets();
}
if (Optimizations.HasFlag(GrammarOptimizations.TrimUnnamedUnaryParsers))
{
OptimizeUnmatchedUnaryParsers();
}
if (Optimizations.HasFlag(GrammarOptimizations.FixRecursiveGrammars))
{
FixRecursiveGrammars();
}
if (Optimizations.HasFlag(GrammarOptimizations.TrimSingleItemSequencesOrAlterations))
{
OptimizeSingleItemParsers();
}
//BuildChildren(new ParserChildrenArgs());
Initialize(new ParserInitializeArgs(this));
initialized = true;
}
void FixRecursiveGrammars()
{
var empty = new EmptyParser();
var alternates = Children.OfType<AlternativeParser>();
var first = new List<Parser>();
var second = new List<Parser>();
foreach (var alt in alternates.Distinct().ToList())
{
first.Clear();
second.Clear();
Parser separator = null;
for (int i = 0; i < alt.Items.Count; i++)
{
Parser item = alt.Items[i];
if (item != null && item.IsLeftRecursive(alt))
{
var seqs = item.Scan(filter: p => {
if (ReferenceEquals(p, alt))
return false;
if (p is SequenceParser seq && seq.Items.Count > 0 && seq.Items[0].IsLeftRecursive(alt))
{
seq.Items[0] = empty;
return true;
}
return false;
}).OfType<SequenceParser>();
foreach (var seq in seqs)
{
separator = seq.Separator;
seq.Items.RemoveAt(0);
}
if (!item.IsLeftRecursive(alt))
second.Add(item);
else
Debug.WriteLine(string.Format("Warning: Item in alternate is still recursive {0}", item.DescriptiveName));
}
else
{
first.Add(item);
}
}
if (second.Count > 0)
{
Debug.WriteLine(string.Format("Fixing recursion in alternate: {0}", alt.DescriptiveName));
alt.Items.Clear();
var secondParser = second.Count > 1 ? new AlternativeParser(second) : second[0];
if (first.Count > 0)
{
var firstParser = first.Count > 1 ? new AlternativeParser(first) : first[0];
var repeat = new RepeatParser(secondParser, 0) { Separator = separator };
if (first.Count == 1 && first[0] == null)
{
alt.Items.Add(repeat);
}
else
alt.Items.Add(new SequenceParser(firstParser, repeat) { Separator = separator });
}
else
alt.Items.Add(new RepeatParser(secondParser, 1) { Separator = separator });
}
}
}
void OptimizeSingleItemParsers()
{
var parsers = from r in Children.OfType<ListParser>()
where
r.Items.Count == 1
&& (r is SequenceParser || r is AlternativeParser)
select r;
foreach (var parser in parsers.ToList())
{
var replacement = parser.Items[0];
if (parser.Name != null)
{
replacement = new UnaryParser { Inner = replacement, Name = parser.Name };
}
Replace(new ParserReplaceArgs(parser, replacement));
}
}
void OptimizeUnmatchedUnaryParsers()
{
var parsers = from r in Children.OfType<UnaryParser>()
where !r.AddMatch && !r.AddError && r.Inner != null && r.GetType() == typeof(UnaryParser)
select r;
foreach (var unary in parsers.ToList())
{
Replace(new ParserReplaceArgs(unary, unary.Inner));
}
}
void OptimizeCharacterSets()
{
// turns character sets, ranges, and single characters into a single parser
var parsers = Children.OfType<AlternativeParser>().Where(r => r.Items.Count > 2);
foreach (var alt in parsers.ToList())
{
if (alt.Items.All(r => r != null && r.Name == null &&
(r is CharSetTerminal
|| r is CharRangeTerminal
|| r is SingleCharTerminal
|| (r is LiteralTerminal && ((LiteralTerminal)r).Value.Length == 1)
)
))
{
var chars = new List<char>();
var inverse = new List<char>();
var additionalParsers = new List<Parser>();
for (int i1 = 0; i1 < alt.Items.Count; i1++)
{
Parser item = alt.Items[i1];
var singleChar = item as SingleCharTerminal;
if (singleChar != null)
{
if (singleChar.Inverse)
inverse.Add(singleChar.Character);
else
chars.Add(singleChar.Character);
continue;
}
var charSet = item as CharSetTerminal;
if (charSet != null)
{
if (charSet.Inverse)
inverse.AddRange(charSet.Characters);
else
chars.AddRange(charSet.Characters);
continue;
}
var charRange = item as CharRangeTerminal;
if (charRange != null)
{
if (charRange.End - charRange.Start > MaxCharacterSetRangeOptimization)
{
additionalParsers.Add(charRange);
}
else
{
for (char i = charRange.Start; i <= charRange.End; i++)
{
if (charRange.Inverse)
inverse.Add(i);
else
chars.Add(i);
}
}
continue;
}
var literal = item as LiteralTerminal;
if (literal != null)
{
chars.Add(literal.Value[0]);
continue;
}
}
//Debug.WriteLine("Optimizing characters normal:{0} inverse:{1}", chars.Count, inverse.Count);
alt.Items.Clear();
if (chars.Count > 0)
alt.Items.Add(new CharSetTerminal(chars.ToArray()));
if (inverse.Count > 0)
alt.Items.Add(new CharSetTerminal(inverse.ToArray())
{
Inverse = true
});
if (additionalParsers.Count > 0)
alt.Items.AddRange(additionalParsers);
}
}
}
protected override int InnerParse(ParseArgs args)
{
if (args.IsRoot)
{
var scanner = args.Scanner;
var pos = scanner.Position;
args.Push();
var match = Inner.Parse(args);
var matches = args.Pop();
if (match >= 0 && !AllowPartialMatch && !scanner.IsEof)
{
scanner.Position = pos;
match = -1;
}
var errorIndex = -1;
var childErrorIndex = -1;
IEnumerable<Parser> errors = null;
if (match < 0 || match == args.ErrorIndex)
{
var errorList = new List<Parser>(args.Errors.Count);
for (int i = 0; i < args.Errors.Count; i++)
{
var error = args.Errors[i];
if (!errorList.Contains(error))
errorList.Add(error);
}
errors = errorList;
errorIndex = args.ErrorIndex;
childErrorIndex = args.ChildErrorIndex;
}
args.Root = new GrammarMatch(this, scanner, pos, match, matches, errorIndex, childErrorIndex, errors);
return match;
}
return base.InnerParse(args);
}
public GrammarMatch Match(string value)
{
//value.ThrowIfNull("value");
return Match(new StringScanner(value));
}
public GrammarMatch Match(Scanner scanner)
{
//scanner.ThrowIfNull("scanner");
var args = new ParseArgs(this, scanner);
if (!initialized)
Initialize();
Parse(args);
var root = args.Root;
if (root.Success && EnableMatchEvents)
{
root.TriggerPreMatch();
root.TriggerMatch();
}
return root;
}
public MatchCollection Matches(string value)
{
value.ThrowIfNull("value");
return Matches(new StringScanner(value));
}
public MatchCollection Matches(Scanner scanner)
{
scanner.ThrowIfNull("scanner");
var matches = new MatchCollection();
var eof = scanner.IsEof;
while (!eof)
{
var match = Match(scanner);
if (match.Success)
{
matches.AddRange(match.Matches);
eof = scanner.IsEof;
}
else
eof = scanner.Advance(1) < 0;
}
return matches;
}
public override Parser Clone(ParserCloneArgs args)
{
return new Grammar(this, args);
}
/// <summary>
/// Sets the parsers with the specified names as terminals, e.g. no match is generated
/// </summary>
/// <remarks>
/// Terminals are usually single characters that are not interesting by themselves.
/// Most grammars do not have a way to define a terminal vs. non-terminal, so one could use this
/// method to improve performance on BNF/EBNF grammars on terminals so that match entries are not
/// created for each character in the results.
///
/// This basically sets <see cref="Parser.AddError"/> and <see cref="Parser.AddMatch"/> to false
/// for each matched parser.
/// </remarks>
/// <param name="terminalNames">Array of terminal names</param>
public void SetTerminals(params string[] terminalNames)
{
var children = Children.Where(r => Array.IndexOf(terminalNames, r.Name) >= 0).ToList();
foreach (var child in children)
{
child.AddError = false;
child.AddMatch = false;
}
}
}
}
| |
using UnityEngine;
namespace UnityStandardAssets.ImageEffects
{
public enum LensflareStyle34
{
Ghosting = 0,
Anamorphic = 1,
Combined = 2,
}
public enum TweakMode34
{
Basic = 0,
Complex = 1,
}
public enum HDRBloomMode
{
Auto = 0,
On = 1,
Off = 2,
}
public enum BloomScreenBlendMode
{
Screen = 0,
Add = 1,
}
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Image Effects/Bloom and Glow/BloomAndFlares (3.5, Deprecated)")]
public class BloomAndFlares : PostEffectsBase
{
public TweakMode34 tweakMode = 0;
public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add;
public HDRBloomMode hdr = HDRBloomMode.Auto;
private bool doHdr = false;
public float sepBlurSpread = 1.5f;
public float useSrcAlphaAsMask = 0.5f;
public float bloomIntensity = 1.0f;
public float bloomThreshold = 0.5f;
public int bloomBlurIterations = 2;
public bool lensflares = false;
public int hollywoodFlareBlurIterations = 2;
public LensflareStyle34 lensflareMode = (LensflareStyle34)1;
public float hollyStretchWidth = 3.5f;
public float lensflareIntensity = 1.0f;
public float lensflareThreshold = 0.3f;
public Color flareColorA = new Color(0.4f, 0.4f, 0.8f, 0.75f);
public Color flareColorB = new Color(0.4f, 0.8f, 0.8f, 0.75f);
public Color flareColorC = new Color(0.8f, 0.4f, 0.8f, 0.75f);
public Color flareColorD = new Color(0.8f, 0.4f, 0.0f, 0.75f);
public Texture2D lensFlareVignetteMask;
public Shader lensFlareShader;
private Material lensFlareMaterial;
public Shader vignetteShader;
private Material vignetteMaterial;
public Shader separableBlurShader;
private Material separableBlurMaterial;
public Shader addBrightStuffOneOneShader;
private Material addBrightStuffBlendOneOneMaterial;
public Shader screenBlendShader;
private Material screenBlend;
public Shader hollywoodFlaresShader;
private Material hollywoodFlaresMaterial;
public Shader brightPassFilterShader;
private Material brightPassFilterMaterial;
public override bool CheckResources()
{
CheckSupport(false);
screenBlend = CheckShaderAndCreateMaterial(screenBlendShader, screenBlend);
lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial);
vignetteMaterial = CheckShaderAndCreateMaterial(vignetteShader, vignetteMaterial);
separableBlurMaterial = CheckShaderAndCreateMaterial(separableBlurShader, separableBlurMaterial);
addBrightStuffBlendOneOneMaterial = CheckShaderAndCreateMaterial(addBrightStuffOneOneShader, addBrightStuffBlendOneOneMaterial);
hollywoodFlaresMaterial = CheckShaderAndCreateMaterial(hollywoodFlaresShader, hollywoodFlaresMaterial);
brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial);
if (!isSupported)
ReportAutoDisable();
return isSupported;
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (CheckResources() == false)
{
Graphics.Blit(source, destination);
return;
}
// screen blend is not supported when HDR is enabled (will cap values)
doHdr = false;
if (hdr == HDRBloomMode.Auto)
doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr;
else
{
doHdr = hdr == HDRBloomMode.On;
}
doHdr = doHdr && supportHDRTextures;
BloomScreenBlendMode realBlendMode = screenBlendMode;
if (doHdr)
realBlendMode = BloomScreenBlendMode.Add;
var rtFormat = (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default;
RenderTexture halfRezColor = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0, rtFormat);
RenderTexture quarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat);
float widthOverHeight = (1.0f * source.width) / (1.0f * source.height);
float oneOverBaseSize = 1.0f / 512.0f;
// downsample
Graphics.Blit(source, halfRezColor, screenBlend, 2); // <- 2 is stable downsample
Graphics.Blit(halfRezColor, quarterRezColor, screenBlend, 2); // <- 2 is stable downsample
RenderTexture.ReleaseTemporary(halfRezColor);
// cut colors (thresholding)
BrightFilter(bloomThreshold, useSrcAlphaAsMask, quarterRezColor, secondQuarterRezColor);
quarterRezColor.DiscardContents();
// blurring
if (bloomBlurIterations < 1) bloomBlurIterations = 1;
for (int iter = 0; iter < bloomBlurIterations; iter++)
{
float spreadForPass = (1.0f + (iter * 0.5f)) * sepBlurSpread;
separableBlurMaterial.SetVector("offsets", new Vector4(0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f));
RenderTexture src = iter == 0 ? secondQuarterRezColor : quarterRezColor;
Graphics.Blit(src, thirdQuarterRezColor, separableBlurMaterial);
src.DiscardContents();
separableBlurMaterial.SetVector("offsets", new Vector4((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(thirdQuarterRezColor, quarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
// lens flares: ghosting, anamorphic or a combination
if (lensflares)
{
if (lensflareMode == 0)
{
BrightFilter(lensflareThreshold, 0.0f, quarterRezColor, thirdQuarterRezColor);
quarterRezColor.DiscardContents();
// smooth a little, this needs to be resolution dependent
/*
separableBlurMaterial.SetVector ("offsets", Vector4 (0.0ff, (2.0ff) / (1.0ff * quarterRezColor.height), 0.0ff, 0.0ff));
Graphics.Blit (thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
separableBlurMaterial.SetVector ("offsets", Vector4 ((2.0ff) / (1.0ff * quarterRezColor.width), 0.0ff, 0.0ff, 0.0ff));
Graphics.Blit (secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
*/
// no ugly edges!
Vignette(0.975f, thirdQuarterRezColor, secondQuarterRezColor);
thirdQuarterRezColor.DiscardContents();
BlendFlares(secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
// (b) hollywood/anamorphic flares?
else
{
// thirdQuarter has the brightcut unblurred colors
// quarterRezColor is the blurred, brightcut buffer that will end up as bloom
hollywoodFlaresMaterial.SetVector("_threshold", new Vector4(lensflareThreshold, 1.0f / (1.0f - lensflareThreshold), 0.0f, 0.0f));
hollywoodFlaresMaterial.SetVector("tintColor", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity);
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 2);
thirdQuarterRezColor.DiscardContents();
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 3);
secondQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetVector("offsets", new Vector4((sepBlurSpread * 1.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth);
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
thirdQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 2.0f);
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 1);
secondQuarterRezColor.DiscardContents();
hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 4.0f);
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1);
thirdQuarterRezColor.DiscardContents();
if (lensflareMode == (LensflareStyle34)1)
{
for (int itera = 0; itera < hollywoodFlareBlurIterations; itera++)
{
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
secondQuarterRezColor.DiscardContents();
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
AddTo(1.0f, secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
else
{
// (c) combined
for (int ix = 0; ix < hollywoodFlareBlurIterations; ix++)
{
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial);
secondQuarterRezColor.DiscardContents();
separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial);
thirdQuarterRezColor.DiscardContents();
}
Vignette(1.0f, secondQuarterRezColor, thirdQuarterRezColor);
secondQuarterRezColor.DiscardContents();
BlendFlares(thirdQuarterRezColor, secondQuarterRezColor);
thirdQuarterRezColor.DiscardContents();
AddTo(1.0f, secondQuarterRezColor, quarterRezColor);
secondQuarterRezColor.DiscardContents();
}
}
}
// screen blend bloom results to color buffer
screenBlend.SetFloat("_Intensity", bloomIntensity);
screenBlend.SetTexture("_ColorBuffer", source);
Graphics.Blit(quarterRezColor, destination, screenBlend, (int)realBlendMode);
RenderTexture.ReleaseTemporary(quarterRezColor);
RenderTexture.ReleaseTemporary(secondQuarterRezColor);
RenderTexture.ReleaseTemporary(thirdQuarterRezColor);
}
private void AddTo(float intensity_, RenderTexture from, RenderTexture to)
{
addBrightStuffBlendOneOneMaterial.SetFloat("_Intensity", intensity_);
Graphics.Blit(from, to, addBrightStuffBlendOneOneMaterial);
}
private void BlendFlares(RenderTexture from, RenderTexture to)
{
lensFlareMaterial.SetVector("colorA", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity);
lensFlareMaterial.SetVector("colorB", new Vector4(flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity);
lensFlareMaterial.SetVector("colorC", new Vector4(flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity);
lensFlareMaterial.SetVector("colorD", new Vector4(flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity);
Graphics.Blit(from, to, lensFlareMaterial);
}
private void BrightFilter(float thresh, float useAlphaAsMask, RenderTexture from, RenderTexture to)
{
if (doHdr)
brightPassFilterMaterial.SetVector("threshold", new Vector4(thresh, 1.0f, 0.0f, 0.0f));
else
brightPassFilterMaterial.SetVector("threshold", new Vector4(thresh, 1.0f / (1.0f - thresh), 0.0f, 0.0f));
brightPassFilterMaterial.SetFloat("useSrcAlphaAsMask", useAlphaAsMask);
Graphics.Blit(from, to, brightPassFilterMaterial);
}
private void Vignette(float amount, RenderTexture from, RenderTexture to)
{
if (lensFlareVignetteMask)
{
screenBlend.SetTexture("_ColorBuffer", lensFlareVignetteMask);
Graphics.Blit(from, to, screenBlend, 3);
}
else
{
vignetteMaterial.SetFloat("vignetteIntensity", amount);
Graphics.Blit(from, to, vignetteMaterial);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace Nowin
{
class SslTransportHandler : ITransportLayerHandler, ITransportLayerCallback
{
readonly ITransportLayerHandler _next;
readonly IServerParameters _serverParameters;
SslStream _ssl;
Task _authenticateTask;
byte[] _recvBuffer;
int _recvOffset;
int _recvLength;
readonly InputStream _inputStream;
public SslTransportHandler(ITransportLayerHandler next, IServerParameters serverParameters)
{
_next = next;
_serverParameters = serverParameters;
_inputStream = new InputStream(this);
next.Callback = this;
}
class InputStream : Stream
{
readonly SslTransportHandler _owner;
TaskCompletionSource<int> _tcsReceive;
AsyncCallback _callbackReceive;
TaskCompletionSource<object> _tcsSend;
AsyncCallback _callbackSend;
public InputStream(SslTransportHandler owner)
{
_owner = owner;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new InvalidOperationException();
}
public override void SetLength(long value)
{
throw new InvalidOperationException();
}
public void FinishReceive(int length)
{
if (length == -1)
_tcsReceive.SetCanceled();
else
_tcsReceive.SetResult(length);
_callbackReceive?.Invoke(_tcsReceive.Task);
}
public override int Read(byte[] buffer, int offset, int count)
{
return ReadOverflowAsync(buffer, offset, count, null, null).Result;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return ReadOverflowAsync(buffer, offset, count, null, null);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return ReadOverflowAsync(buffer, offset, count, callback, state);
}
Task<int> ReadOverflowAsync(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
_tcsReceive = new TaskCompletionSource<int>(state);
_callbackReceive = callback;
_owner.Callback.StartReceive(buffer, offset, count);
return _tcsReceive.Task;
}
public override int EndRead(IAsyncResult asyncResult)
{
if (((Task<int>)asyncResult).IsCanceled)
{
return 0;
}
try
{
return ((Task<int>)asyncResult).Result;
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
}
public void FinishSend(Exception exception)
{
if (exception == null)
{
_tcsSend.SetResult(null);
}
else
{
_tcsSend.SetException(exception);
}
_callbackSend?.Invoke(_tcsSend.Task);
}
public override void Flush()
{
}
public override void Write(byte[] buffer, int offset, int count)
{
WriteAsync(buffer, offset, count, CancellationToken.None).Wait();
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
_tcsSend = new TaskCompletionSource<object>();
_owner.Callback.StartSend(buffer, offset, count);
return _tcsSend.Task;
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
_tcsSend = new TaskCompletionSource<object>(state);
_callbackSend = callback;
_owner.Callback.StartSend(buffer, offset, count);
return _tcsSend.Task;
}
public override void EndWrite(IAsyncResult asyncResult)
{
try
{
((Task<object>)asyncResult).Wait();
}
catch (AggregateException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => long.MaxValue;
public override long Position { get; set; }
}
public void Dispose()
{
_next.Dispose();
}
public ITransportLayerCallback Callback { set; private get; }
public void PrepareAccept()
{
_ssl = null;
var t = _authenticateTask;
_authenticateTask = null;
if (t != null && !t.IsCompleted)
{
t.ContinueWith((t2, next) =>
{
((ITransportLayerHandler)next).PrepareAccept();
}, _next);
return;
}
_next.PrepareAccept();
}
public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint)
{
Debug.Assert(length == 0);
try
{
_ssl = new SslStream(_inputStream, true);
_authenticateTask = _ssl.AuthenticateAsServerAsync(_serverParameters.Certificate, _serverParameters.ClientCertificateRequired, _serverParameters.Protocols, false).ContinueWith((t, selfObject) =>
{
var self = (SslTransportHandler)selfObject;
if (t.IsFaulted || t.IsCanceled)
self.Callback.StartDisconnect();
else
_next.SetRemoteCertificate(_ssl.RemoteCertificate);
}, this);
_next.FinishAccept(_recvBuffer, _recvOffset, 0, remoteEndPoint, localEndPoint);
}
catch (Exception)
{
Callback.StartDisconnect();
}
}
public void SetRemoteCertificate(X509Certificate remoteCertificate)
{
throw new InvalidOperationException();
}
public void FinishReceive(byte[] buffer, int offset, int length)
{
_inputStream.FinishReceive(length);
}
public void FinishSend(Exception exception)
{
_inputStream.FinishSend(exception);
}
public void StartAccept(byte[] buffer, int offset, int length)
{
_recvBuffer = buffer;
_recvOffset = offset;
_recvLength = length;
Callback.StartAccept(null, 0, 0);
}
public void StartReceive(byte[] buffer, int offset, int length)
{
_recvBuffer = buffer;
_recvOffset = offset;
_recvLength = length;
try
{
if (!_authenticateTask.IsCompleted)
{
_authenticateTask.ContinueWith((t, selfObject) =>
{
var self = (SslTransportHandler)selfObject;
if (t.IsCanceled || t.IsFaulted)
{
self._next.FinishReceive(null, 0, -1);
}
else
{
_ssl.ReadAsync(self._recvBuffer, self._recvOffset, self._recvLength).ContinueWith((t2, selfObject2) =>
{
var self2 = (SslTransportHandler)selfObject2;
if (t2.IsFaulted || t2.IsCanceled || t2.Result == 0)
self._next.FinishReceive(null, 0, -1);
else
self._next.FinishReceive(self2._recvBuffer, self2._recvOffset, t2.Result);
}, self);
}
}, this);
return;
}
_ssl.ReadAsync(buffer, offset, length).ContinueWith((t, selfObject) =>
{
var self = (SslTransportHandler)selfObject;
if (t.IsFaulted || t.IsCanceled || t.Result == 0)
self._next.FinishReceive(null, 0, -1);
else
self._next.FinishReceive(self._recvBuffer, self._recvOffset, t.Result);
}, this);
}
catch (Exception)
{
_next.FinishReceive(null, 0, -1);
}
}
public void StartSend(byte[] buffer, int offset, int length)
{
try
{
_ssl.WriteAsync(buffer, offset, length).ContinueWith((t, selfObject) =>
{
var self = (SslTransportHandler)selfObject;
if (t.IsCanceled)
{
self._next.FinishSend(new OperationCanceledException());
}
else if (t.IsFaulted)
{
self._next.FinishSend(t.Exception);
}
else
{
self._next.FinishSend(null);
}
}, this);
}
catch (Exception ex)
{
_next.FinishSend(ex);
}
}
public void StartDisconnect()
{
Callback.StartDisconnect();
}
}
}
| |
using System;
using System.Collections.Generic;
using Interop.VixCOM;
namespace Vestris.VMWareLib
{
/// <summary>
/// A VMWare virtual host.
/// </summary>
public class VMWareVirtualHost : VMWareVixHandle<IHost>
{
/// <summary>
/// VMWare service provider type.
/// </summary>
public enum ServiceProviderType
{
/// <summary>
/// No service provider type, not connected.
/// </summary>
None = 0,
/// <summary>
/// VMWare Server.
/// </summary>
Server = Constants.VIX_SERVICEPROVIDER_VMWARE_SERVER,
/// <summary>
/// VMWare Workstation.
/// </summary>
Workstation = Constants.VIX_SERVICEPROVIDER_VMWARE_WORKSTATION,
/// <summary>
/// VMWare Workstation Shared
/// </summary>
WorkstationShared = Constants.VIX_SERVICEPROVIDER_VMWARE_WORKSTATION_SHARED,
/// <summary>
/// Virtual Infrastructure Server, eg. ESX.
/// </summary>
VirtualInfrastructureServer = Constants.VIX_SERVICEPROVIDER_VMWARE_VI_SERVER,
/// <summary>
/// VMWare Player.
/// </summary>
Player = Constants.VIX_SERVICEPROVIDER_VMWARE_PLAYER
}
private ServiceProviderType _serviceProviderType = ServiceProviderType.None;
/// <summary>
/// An IHost2 handle, where supported.
/// </summary>
protected IHost2 _host2
{
get
{
return _handle as IHost2;
}
}
/// <summary>
/// A VMWare virtual host.
/// </summary>
public VMWareVirtualHost()
{
}
/// <summary>
/// Connected host type.
/// </summary>
public ServiceProviderType ConnectionType
{
get
{
return _serviceProviderType;
}
}
/// <summary>
/// Connect to a VMWare Player.
/// </summary>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWarePlayer();
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("C:\Virtual Machines\xp\xp.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
public void ConnectToVMWarePlayer()
{
ConnectToVMWarePlayer(VMWareInterop.Timeouts.ConnectTimeout);
}
/// <summary>
/// Connect to a VMWare Player.
/// </summary>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void ConnectToVMWarePlayer(int timeoutInSeconds)
{
Connect(ServiceProviderType.Player, null, 0, null, null, timeoutInSeconds);
}
/// <summary>
/// Connect to a VMWare Workstation.
/// </summary>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWareWorkstation();
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("C:\Virtual Machines\xp\xp.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
public void ConnectToVMWareWorkstation()
{
ConnectToVMWareWorkstation(VMWareInterop.Timeouts.ConnectTimeout);
}
/// <summary>
/// Connect to a VMWare Workstation.
/// </summary>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void ConnectToVMWareWorkstation(int timeoutInSeconds)
{
Connect(ServiceProviderType.Workstation, null, 0, null, null, timeoutInSeconds);
}
/// <summary>
/// Connects to VMWare Workstation (shared mode).
/// </summary>
/// <param name="hostName">Name of the host.</param>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
public void ConnectToVMWareWorkstation(string hostName, string username, string password)
{
ConnectToVMWareWorkstation(hostName, username, password, VMWareInterop.Timeouts.ConnectTimeout);
}
/// <summary>
/// Connects to VMWare Workstation (shared mode).
/// </summary>
/// <param name="hostName">Name of the host.</param>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <param name="timeoutInSeconds">The timeout in seconds.</param>
public void ConnectToVMWareWorkstation(string hostName, string username, string password, int timeoutInSeconds)
{
Connect(ServiceProviderType.WorkstationShared, string.Format("https://{0}/sdk", hostName), 0, username, password, timeoutInSeconds);
}
/// <summary>
/// Connect to a VMWare Virtual Infrastructure Server (eg. ESX or VMWare Server 2.x).
/// </summary>
/// <param name="hostName">VMWare host name and optional port.</param>
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWareVIServer("esx.mycompany.com", "vmuser", "password");
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("[storage] testvm/testvm.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWareVIServer("localhost:8333", "vmuser", "password");
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("[standard] testvm/testvm.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
public void ConnectToVMWareVIServer(string hostName, string username, string password)
{
ConnectToVMWareVIServer(hostName, username, password, VMWareInterop.Timeouts.ConnectTimeout);
}
/// <summary>
/// Connect to a VMWare Virtual Infrastructure Server (eg. ESX or VMWare Server 2.x).
/// </summary>
/// <param name="hostName">VMWare host name and optional port.</param>
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWareVIServer("esx.mycompany.com", "vmuser", "password");
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("[storage] testvm/testvm.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
/// <example>
/// <code>
/// using System;
/// using System.Collections.Generic;
/// using Vestris.VMWareLib;
///
/// VMWareVirtualHost virtualHost = new VMWareVirtualHost();
/// virtualHost.ConnectToVMWareVIServer("localhost:8333", "vmuser", "password");
/// VMWareVirtualMachine virtualMachine = virtualHost.Open("[standard] testvm/testvm.vmx");
/// virtualMachine.PowerOn();
/// </code>
/// </example>
public void ConnectToVMWareVIServer(string hostName, string username, string password, int timeoutInSeconds)
{
if (string.IsNullOrEmpty(hostName))
{
throw new ArgumentException("The host is required.");
}
ConnectToVMWareVIServer(new Uri(string.Format("https://{0}/sdk", hostName)),
username, password, timeoutInSeconds);
}
/// <summary>
/// Connect to a VMWare Virtual Infrastructure Server (eg. ESX).
/// </summary>
/// <param name="hostUri">Host SDK uri, eg. http://server/sdk.</param>
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void ConnectToVMWareVIServer(Uri hostUri, string username, string password, int timeoutInSeconds)
{
if (string.IsNullOrEmpty(username))
{
throw new ArgumentException("The username is required.");
}
Connect(ServiceProviderType.VirtualInfrastructureServer,
hostUri.ToString(), 0, username, password, timeoutInSeconds);
}
/// <summary>
/// Connect to a VMWare Server.
/// </summary>
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <param name="hostName">DNS name or IP address of a VMWare host, leave blank for localhost.</param>
public void ConnectToVMWareServer(string hostName, string username, string password)
{
ConnectToVMWareServer(hostName, username, password, VMWareInterop.Timeouts.ConnectTimeout);
}
/// <summary>
/// Connect to a VMWare Server.
/// </summary>
/// <param name="hostName">DNS name or IP address of a VMWare host, leave blank for localhost.</param>
/// <param name="username">Username.</param>
/// <param name="password">Password.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void ConnectToVMWareServer(string hostName, string username, string password, int timeoutInSeconds)
{
Connect(ServiceProviderType.Server,
hostName, 0, username, password, timeoutInSeconds);
}
/// <summary>
/// Connects to a VMWare VI Server, VMWare Server or Workstation.
/// </summary>
private void Connect(ServiceProviderType serviceProviderType,
string hostName, int hostPort, string username, string password, int timeout)
{
try
{
int serviceProvider = (int)serviceProviderType;
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(new VixLib().Connect(
Constants.VIX_API_VERSION, serviceProvider, hostName, hostPort,
username, password, 0, null, callback), callback))
{
_handle = job.Wait<IHost>(Constants.VIX_PROPERTY_JOB_RESULT_HANDLE, timeout);
}
_serviceProviderType = serviceProviderType;
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to connect: serviceProviderType=\"{0}\" hostName=\"{1}\" hostPort={2} username=\"{3}\" timeout={4}",
Enum.GetName(serviceProviderType.GetType(), serviceProviderType), hostName, hostPort, username, timeout), ex);
}
}
/// <summary>
/// Open a virtual machine.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
/// <returns>An instance of a virtual machine.</returns>
public VMWareVirtualMachine Open(string fileName)
{
return Open(fileName, VMWareInterop.Timeouts.OpenVMTimeout);
}
/// <summary>
/// Open a virtual machine.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
/// <returns>An instance of a virtual machine.</returns>
public VMWareVirtualMachine Open(string fileName, int timeoutInSeconds)
{
try
{
if (_handle == null)
{
throw new InvalidOperationException("No connection established");
}
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_handle.OpenVM(fileName, callback), callback))
{
return new VMWareVirtualMachine(job.Wait<IVM2>(
Constants.VIX_PROPERTY_JOB_RESULT_HANDLE,
timeoutInSeconds));
}
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to open virtual machine: fileName=\"{0}\" timeoutInSeconds={1}",
fileName, timeoutInSeconds), ex);
}
}
/// <summary>
/// Add a virtual machine to the host's inventory.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
public void Register(string fileName)
{
Register(fileName, VMWareInterop.Timeouts.RegisterVMTimeout);
}
/// <summary>
/// Add a virtual machine to the host's inventory.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void Register(string fileName, int timeoutInSeconds)
{
if (_handle == null)
{
throw new InvalidOperationException("No connection established");
}
switch (ConnectionType)
{
case ServiceProviderType.VirtualInfrastructureServer:
case ServiceProviderType.Server:
case ServiceProviderType.WorkstationShared:
break;
default:
throw new NotSupportedException(string.Format("Register is not supported on {0}",
ConnectionType));
}
try
{
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_handle.RegisterVM(fileName, callback), callback))
{
job.Wait(timeoutInSeconds);
}
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to register virtual machine: fileName=\"{0}\" timeoutInSeconds={1}",
fileName, timeoutInSeconds), ex);
}
}
/// <summary>
/// Remove a virtual machine from the host's inventory.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
public void Unregister(string fileName)
{
Unregister(fileName, VMWareInterop.Timeouts.RegisterVMTimeout);
}
/// <summary>
/// Remove a virtual machine from the host's inventory.
/// </summary>
/// <param name="fileName">Virtual Machine file, local .vmx or [storage] .vmx.</param>
/// <param name="timeoutInSeconds">Timeout in seconds.</param>
public void Unregister(string fileName, int timeoutInSeconds)
{
if (_handle == null)
{
throw new InvalidOperationException("No connection established");
}
switch (ConnectionType)
{
case ServiceProviderType.VirtualInfrastructureServer:
case ServiceProviderType.Server:
case ServiceProviderType.WorkstationShared:
break;
default:
throw new NotSupportedException(string.Format("Unregister is not supported on {0}",
ConnectionType));
}
try
{
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_handle.UnregisterVM(fileName, callback), callback))
{
job.Wait(timeoutInSeconds);
}
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to unregister virtual machine: fileName=\"{0}\" timeoutInSeconds={1}",
fileName, timeoutInSeconds), ex);
}
}
/// <summary>
/// Dispose the object, hard-disconnect from the remote host.
/// </summary>
public override void Dispose()
{
if (_handle != null)
{
Disconnect();
}
GC.SuppressFinalize(this);
}
/// <summary>
/// Disconnect from a remote host.
/// </summary>
public void Disconnect()
{
if (_handle == null)
{
throw new InvalidOperationException("No connection established");
}
_handle.Disconnect();
_handle = null;
_serviceProviderType = ServiceProviderType.None;
}
/// <summary>
/// Returns true when connected to a virtual host, false otherwise.
/// </summary>
public bool IsConnected
{
get
{
return _handle != null;
}
}
/// <summary>
/// Destructor.
/// </summary>
~VMWareVirtualHost()
{
if (_handle != null)
{
Disconnect();
}
}
/// <summary>
/// Returns all running virtual machines.
/// </summary>
public IEnumerable<VMWareVirtualMachine> RunningVirtualMachines
{
get
{
if (_handle == null)
{
throw new InvalidOperationException("No connection established");
}
try
{
List<VMWareVirtualMachine> runningVirtualMachines = new List<VMWareVirtualMachine>();
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_handle.FindItems(
Constants.VIX_FIND_RUNNING_VMS, null, -1, callback),
callback))
{
object[] properties = { Constants.VIX_PROPERTY_FOUND_ITEM_LOCATION };
foreach (object[] runningVirtualMachine in job.YieldWait(
properties, VMWareInterop.Timeouts.FindItemsTimeout))
{
runningVirtualMachines.Add(this.Open((string)runningVirtualMachine[0]));
}
}
return runningVirtualMachines;
}
catch (Exception ex)
{
throw new Exception("Failed to get all running virtual machines", ex);
}
}
}
/// <summary>
/// All registered virtual machines.
/// </summary>
/// <remarks>This function is only supported on Virtual Infrastructure servers.</remarks>
public IEnumerable<VMWareVirtualMachine> RegisteredVirtualMachines
{
get
{
switch (ConnectionType)
{
case ServiceProviderType.VirtualInfrastructureServer:
case ServiceProviderType.Server:
case ServiceProviderType.WorkstationShared:
break;
default:
throw new NotSupportedException(string.Format("RegisteredVirtualMachines is not supported on {0}",
ConnectionType));
}
try
{
List<VMWareVirtualMachine> registeredVirtualMachines = new List<VMWareVirtualMachine>();
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_handle.FindItems(
Constants.VIX_FIND_REGISTERED_VMS, null, -1, callback),
callback))
{
object[] properties = { Constants.VIX_PROPERTY_FOUND_ITEM_LOCATION };
foreach (object[] runningVirtualMachine in job.YieldWait(properties, VMWareInterop.Timeouts.FindItemsTimeout))
{
registeredVirtualMachines.Add(this.Open((string)runningVirtualMachine[0]));
}
}
return registeredVirtualMachines;
}
catch (Exception ex)
{
throw new Exception("Failed to get all registered virtual machines", ex);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
//
// Authors:
// Marek Habersack <mhabersack@novell.com>
//
// Copyright (C) 2010 Novell, Inc. (http://novell.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Runtime.Caching;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using MonoTests.Common;
namespace MonoTests.System.Runtime.Caching
{
public class MemoryCacheTest
{
[Fact]
public void ConstructorParameters()
{
MemoryCache mc;
Assert.Throws<ArgumentNullException>(() =>
{
mc = new MemoryCache(null);
});
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache(String.Empty);
});
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("default");
});
var config = new NameValueCollection();
config.Add("CacheMemoryLimitMegabytes", "invalid");
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("MyCache", config);
});
config.Clear();
config.Add("PhysicalMemoryLimitPercentage", "invalid");
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("MyCache", config);
});
config.Clear();
config.Add("PollingInterval", "invalid");
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("MyCache", config);
});
config.Clear();
config.Add("CacheMemoryLimitMegabytes", "-1");
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("MyCache", config);
});
config.Clear();
config.Add("CacheMemoryLimitMegabytes", UInt64.MaxValue.ToString());
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("MyCache", config);
});
config.Clear();
config.Add("PhysicalMemoryLimitPercentage", "-1");
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("MyCache", config);
});
config.Clear();
config.Add("PhysicalMemoryLimitPercentage", UInt64.MaxValue.ToString());
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("MyCache", config);
});
config.Clear();
config.Add("PhysicalMemoryLimitPercentage", UInt32.MaxValue.ToString());
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("MyCache", config);
});
config.Clear();
config.Add("PhysicalMemoryLimitPercentage", "-10");
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("MyCache", config);
});
config.Clear();
config.Add("PhysicalMemoryLimitPercentage", "0");
// Just make sure it doesn't throw any exception
mc = new MemoryCache("MyCache", config);
config.Clear();
config.Add("PhysicalMemoryLimitPercentage", "101");
Assert.Throws<ArgumentException>(() =>
{
mc = new MemoryCache("MyCache", config);
});
// Just make sure it doesn't throw any exception
config.Clear();
config.Add("UnsupportedSetting", "123");
mc = new MemoryCache("MyCache", config);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Negative case for "physicalMemoryLimitPercentage" on non Windows
public void PhysicalMemoryLimitNotSupported()
{
var config = new NameValueCollection();
config.Add("PhysicalMemoryLimitPercentage", "99");
Assert.Throws<PlatformNotSupportedException>(() =>
{
new MemoryCache("MyCache", config);
});
}
[Fact]
public void Defaults()
{
var mc = new MemoryCache("MyCache");
Assert.Equal("MyCache", mc.Name);
Assert.Equal(TimeSpan.FromMinutes(2), mc.PollingInterval);
Assert.Equal(
DefaultCacheCapabilities.InMemoryProvider |
DefaultCacheCapabilities.CacheEntryChangeMonitors |
DefaultCacheCapabilities.AbsoluteExpirations |
DefaultCacheCapabilities.SlidingExpirations |
DefaultCacheCapabilities.CacheEntryRemovedCallback |
DefaultCacheCapabilities.CacheEntryUpdateCallback,
mc.DefaultCacheCapabilities);
}
[Fact]
public void DefaultInstanceDefaults()
{
var mc = MemoryCache.Default;
Assert.Equal("Default", mc.Name);
Assert.Equal(TimeSpan.FromMinutes(2), mc.PollingInterval);
Assert.Equal(
DefaultCacheCapabilities.InMemoryProvider |
DefaultCacheCapabilities.CacheEntryChangeMonitors |
DefaultCacheCapabilities.AbsoluteExpirations |
DefaultCacheCapabilities.SlidingExpirations |
DefaultCacheCapabilities.CacheEntryRemovedCallback |
DefaultCacheCapabilities.CacheEntryUpdateCallback,
mc.DefaultCacheCapabilities);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses "physicalMemoryLimitPercentage" not supported on other platforms
public void ConstructorValues()
{
var config = new NameValueCollection();
config.Add("CacheMemoryLimitMegabytes", "1");
config.Add("pollingInterval", "00:10:00");
var mc = new MemoryCache("MyCache", config);
Assert.Equal(1048576, mc.CacheMemoryLimit);
Assert.Equal(TimeSpan.FromMinutes(10), mc.PollingInterval);
config.Clear();
config.Add("PhysicalMemoryLimitPercentage", "10");
config.Add("CacheMemoryLimitMegabytes", "5");
config.Add("PollingInterval", "01:10:00");
mc = new MemoryCache("MyCache", config);
Assert.Equal(10, mc.PhysicalMemoryLimit);
Assert.Equal(5242880, mc.CacheMemoryLimit);
Assert.Equal(TimeSpan.FromMinutes(70), mc.PollingInterval);
}
[Fact]
public void Indexer()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<ArgumentNullException>(() =>
{
mc[null] = "value";
});
Assert.Throws<ArgumentNullException>(() =>
{
object v = mc[null];
});
Assert.Throws<ArgumentNullException>(() =>
{
mc["key"] = null;
});
mc.Calls.Clear();
mc["key"] = "value";
Assert.Equal(3, mc.Calls.Count);
Assert.Equal("set_this [string key]", mc.Calls[0]);
Assert.Equal("Set (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)", mc.Calls[1]);
Assert.Equal("Set (string key, object value, CacheItemPolicy policy, string regionName = null)", mc.Calls[2]);
Assert.True(mc.Contains("key"));
mc.Calls.Clear();
object value = mc["key"];
Assert.Equal(1, mc.Calls.Count);
Assert.Equal("get_this [string key]", mc.Calls[0]);
Assert.Equal("value", value);
}
[Fact]
public void Contains()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<ArgumentNullException>(() =>
{
mc.Contains(null);
});
Assert.Throws<NotSupportedException>(() =>
{
mc.Contains("key", "region");
});
mc.Set("key", "value", ObjectCache.InfiniteAbsoluteExpiration);
Assert.True(mc.Contains("key"));
var cip = new CacheItemPolicy();
cip.Priority = CacheItemPriority.NotRemovable;
cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(50);
mc.Set("key", "value", cip);
Assert.True(mc.Contains("key"));
// wait past cip.AbsoluteExpiration
Thread.Sleep(500);
// Attempt to retrieve an expired entry
Assert.False(mc.Contains("key"));
}
[Fact]
public void CreateCacheEntryChangeMonitor()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<NotSupportedException>(() =>
{
mc.CreateCacheEntryChangeMonitor(new string[] { "key" }, "region");
});
Assert.Throws<ArgumentNullException>(() =>
{
mc.CreateCacheEntryChangeMonitor(null);
});
Assert.Throws<ArgumentException>(() =>
{
mc.CreateCacheEntryChangeMonitor(new string[] { });
});
Assert.Throws<ArgumentException>(() =>
{
mc.CreateCacheEntryChangeMonitor(new string[] { "key", null });
});
mc.Set("key1", "value1", ObjectCache.InfiniteAbsoluteExpiration);
mc.Set("key2", "value2", ObjectCache.InfiniteAbsoluteExpiration);
mc.Set("key3", "value3", ObjectCache.InfiniteAbsoluteExpiration);
CacheEntryChangeMonitor monitor = mc.CreateCacheEntryChangeMonitor(new string[] { "key1", "key2" });
Assert.NotNull(monitor);
Assert.Equal("System.Runtime.Caching.MemoryCacheEntryChangeMonitor", monitor.GetType().ToString());
Assert.Equal(2, monitor.CacheKeys.Count);
Assert.Equal("key1", monitor.CacheKeys[0]);
Assert.Equal("key2", monitor.CacheKeys[1]);
Assert.Null(monitor.RegionName);
Assert.False(monitor.HasChanged);
// The actual unique id is constructed from key names followed by the hex value of ticks of their last modifed time
Assert.False(String.IsNullOrEmpty(monitor.UniqueId));
monitor = mc.CreateCacheEntryChangeMonitor (new string [] { "key1", "doesnotexist" });
Assert.NotNull (monitor);
Assert.Equal ("System.Runtime.Caching.MemoryCacheEntryChangeMonitor", monitor.GetType ().ToString ());
Assert.Equal (2, monitor.CacheKeys.Count);
Assert.Equal ("key1", monitor.CacheKeys [0]);
Assert.Null (monitor.RegionName);
Assert.True (monitor.HasChanged);
}
[Fact]
public void AddOrGetExisting_String_Object_DateTimeOffset_String()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<ArgumentNullException>(() =>
{
mc.AddOrGetExisting(null, "value", DateTimeOffset.Now);
});
Assert.Throws<ArgumentNullException>(() =>
{
mc.AddOrGetExisting("key", null, DateTimeOffset.Now);
});
Assert.Throws<NotSupportedException>(() =>
{
mc.AddOrGetExisting("key", "value", DateTimeOffset.Now, "region");
});
object value = mc.AddOrGetExisting("key3_A2-1", "value", DateTimeOffset.Now.AddMinutes(1));
Assert.True(mc.Contains("key3_A2-1"));
Assert.Null(value);
mc.Calls.Clear();
value = mc.AddOrGetExisting("key3_A2-1", "value2", DateTimeOffset.Now.AddMinutes(1));
Assert.True(mc.Contains("key3_A2-1"));
Assert.NotNull(value);
Assert.Equal("value", value);
Assert.Equal(2, mc.Calls.Count);
Assert.Equal("AddOrGetExisting (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)", mc.Calls[0]);
value = mc.AddOrGetExisting("key_expired", "value", DateTimeOffset.MinValue);
Assert.False(mc.Contains("key_expired"));
Assert.Null(value);
}
[Fact]
public void AddOrGetExisting_String_Object_CacheItemPolicy_String()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<ArgumentNullException>(() =>
{
mc.AddOrGetExisting(null, "value", null);
});
Assert.Throws<ArgumentNullException>(() =>
{
mc.AddOrGetExisting("key", null, null);
});
var cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTime.Now.AddMinutes(1);
cip.SlidingExpiration = TimeSpan.FromMinutes(1);
Assert.Throws<ArgumentException>(() =>
{
mc.AddOrGetExisting("key", "value", cip);
});
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.MinValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.AddOrGetExisting("key3", "value", cip);
});
Assert.Throws<NotSupportedException>(() =>
{
mc.AddOrGetExisting("key", "value", null, "region");
});
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromDays(500);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.AddOrGetExisting("key3", "value", cip);
});
cip = new CacheItemPolicy();
cip.Priority = (CacheItemPriority)20;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.AddOrGetExisting("key3", "value", cip);
});
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromTicks(0L);
mc.AddOrGetExisting("key3_A2-1", "value", cip);
Assert.True(mc.Contains("key3_A2-1"));
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromDays(365);
mc.AddOrGetExisting("key3_A2-2", "value", cip);
Assert.True(mc.Contains("key3_A2-2"));
cip = new CacheItemPolicy();
cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
object value = mc.AddOrGetExisting("key3_A2-3", "value", cip);
Assert.True(mc.Contains("key3_A2-3"));
Assert.Null(value);
mc.Calls.Clear();
value = mc.AddOrGetExisting("key3_A2-3", "value2", null);
Assert.True(mc.Contains("key3_A2-3"));
Assert.NotNull(value);
Assert.Equal("value", value);
Assert.Equal(2, mc.Calls.Count);
Assert.Equal("AddOrGetExisting (string key, object value, CacheItemPolicy policy, string regionName = null)", mc.Calls[0]);
cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTimeOffset.MinValue;
value = mc.AddOrGetExisting("key_expired", "value", cip);
Assert.False(mc.Contains("key_expired"));
Assert.Null(value);
}
[Fact]
public void AddOrGetExisting_CacheItem_CacheItemPolicy()
{
var mc = new PokerMemoryCache("MyCache");
CacheItem ci, ci2;
Assert.Throws<ArgumentNullException>(() =>
{
ci = mc.AddOrGetExisting(null, new CacheItemPolicy());
});
ci = new CacheItem("key", "value");
ci2 = mc.AddOrGetExisting(ci, null);
Assert.NotNull(ci2);
Assert.NotEqual(ci, ci2);
Assert.Null(ci2.Value);
Assert.True(mc.Contains(ci.Key));
Assert.Equal(ci.Key, ci2.Key);
ci = new CacheItem("key", "value");
ci2 = mc.AddOrGetExisting(ci, null);
Assert.NotNull(ci2);
Assert.NotEqual(ci, ci2);
Assert.NotNull(ci2.Value);
Assert.Equal(ci.Value, ci2.Value);
Assert.Equal(ci.Key, ci2.Key);
Assert.Throws<ArgumentNullException>(() =>
{
ci = new CacheItem(null, "value");
ci2 = mc.AddOrGetExisting(ci, null);
});
ci = new CacheItem(String.Empty, "value");
ci2 = mc.AddOrGetExisting(ci, null);
Assert.NotNull(ci2);
Assert.NotEqual(ci, ci2);
Assert.Null(ci2.Value);
Assert.True(mc.Contains(ci.Key));
Assert.Equal(ci.Key, ci2.Key);
ci = new CacheItem("key2", null);
// Thrown from:
// at System.Runtime.Caching.MemoryCacheEntry..ctor(String key, Object value, DateTimeOffset absExp, TimeSpan slidingExp, CacheItemPriority priority, Collection`1 dependencies, CacheEntryRemovedCallback removedCallback, MemoryCache cache)
// at System.Runtime.Caching.MemoryCache.AddOrGetExistingInternal(String key, Object value, CacheItemPolicy policy)
// at System.Runtime.Caching.MemoryCache.AddOrGetExisting(CacheItem item, CacheItemPolicy policy)
// at MonoTests.System.Runtime.Caching.MemoryCacheTest.AddOrGetExisting_CacheItem_CacheItemPolicy() in C:\Users\grendel\documents\visual studio 2010\Projects\System.Runtime.Caching.Test\System.Runtime.Caching.Test\System.Runtime.Caching\MemoryCacheTest.cs:line 211
Assert.Throws<ArgumentNullException>(() =>
{
ci2 = mc.AddOrGetExisting(ci, null);
});
ci = new CacheItem("key3", "value");
var cip = new CacheItemPolicy();
cip.UpdateCallback = (CacheEntryUpdateArguments arguments) => { };
Assert.Throws<ArgumentException>(() =>
{
ci2 = mc.AddOrGetExisting(ci, cip);
});
ci = new CacheItem("key3", "value");
cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTimeOffset.Now;
cip.SlidingExpiration = TimeSpan.FromTicks(DateTime.Now.Ticks);
Assert.Throws<ArgumentException>(() =>
{
mc.AddOrGetExisting(ci, cip);
});
ci = new CacheItem("key3", "value");
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.MinValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.AddOrGetExisting(ci, cip);
});
ci = new CacheItem("key4_#B4-2", "value");
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromTicks(0L);
mc.AddOrGetExisting(ci, cip);
Assert.True(mc.Contains("key4_#B4-2"));
ci = new CacheItem("key3", "value");
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromDays(500);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.AddOrGetExisting(ci, cip);
});
ci = new CacheItem("key5_#B5-2", "value");
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromDays(365);
mc.AddOrGetExisting(ci, cip);
Assert.True(mc.Contains("key5_#B5-2"));
ci = new CacheItem("key3", "value");
cip = new CacheItemPolicy();
cip.Priority = (CacheItemPriority)20;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.AddOrGetExisting(ci, cip);
});
ci = new CacheItem("key3_B7", "value");
cip = new CacheItemPolicy();
cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
ci2 = mc.AddOrGetExisting(ci, cip);
Assert.True(mc.Contains("key3_B7"));
Assert.NotNull(ci2);
Assert.NotEqual(ci, ci2);
Assert.Null(ci2.Value);
Assert.True(mc.Contains(ci.Key));
Assert.Equal(ci.Key, ci2.Key);
// The entry is never inserted as its expiration date is before now
ci = new CacheItem("key_D1", "value_D1");
cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTimeOffset.MinValue;
ci2 = mc.AddOrGetExisting(ci, cip);
Assert.False(mc.Contains("key_D1"));
Assert.NotNull(ci2);
Assert.Null(ci2.Value);
Assert.Equal("key_D1", ci2.Key);
mc.Calls.Clear();
ci = new CacheItem("key_D2", "value_D2");
cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTimeOffset.MaxValue;
mc.AddOrGetExisting(ci, cip);
Assert.True(mc.Contains("key_D2"));
Assert.Equal(2, mc.Calls.Count);
Assert.Equal("AddOrGetExisting (CacheItem item, CacheItemPolicy policy)", mc.Calls[0]);
}
[Fact]
public void Set_String_Object_CacheItemPolicy_String()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<NotSupportedException>(() =>
{
mc.Set("key", "value", new CacheItemPolicy(), "region");
});
Assert.Throws<ArgumentNullException>(() =>
{
mc.Set(null, "value", new CacheItemPolicy());
});
Assert.Throws<ArgumentNullException>(() =>
{
mc.Set("key", null, new CacheItemPolicy());
});
var cip = new CacheItemPolicy();
cip.UpdateCallback = (CacheEntryUpdateArguments arguments) => { };
cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
Assert.Throws<ArgumentException>(() =>
{
mc.Set("key", "value", cip);
});
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.MinValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.Set("key", "value", cip);
});
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromTicks(0L);
mc.Set("key_A1-6", "value", cip);
Assert.True(mc.Contains("key_A1-6"));
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromDays(500);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.Set("key", "value", cip);
});
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromDays(365);
mc.Set("key_A1-8", "value", cip);
Assert.True(mc.Contains("key_A1-8"));
cip = new CacheItemPolicy();
cip.Priority = (CacheItemPriority)20;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.Set("key", "value", cip);
});
cip = new CacheItemPolicy();
cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
mc.Set("key_A2", "value_A2", cip);
Assert.True(mc.Contains("key_A2"));
mc.Set("key_A3", "value_A3", new CacheItemPolicy());
Assert.True(mc.Contains("key_A3"));
Assert.Equal("value_A3", mc.Get("key_A3"));
// The entry is never inserted as its expiration date is before now
cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTimeOffset.MinValue;
mc.Set("key_A4", "value_A4", cip);
Assert.False(mc.Contains("key_A4"));
mc.Calls.Clear();
cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTimeOffset.MaxValue;
mc.Set("key_A5", "value_A5", cip);
Assert.True(mc.Contains("key_A5"));
Assert.Equal(2, mc.Calls.Count);
Assert.Equal("Set (string key, object value, CacheItemPolicy policy, string regionName = null)", mc.Calls[0]);
}
[Fact]
public void Set_String_Object_DateTimeOffset_String()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<NotSupportedException>(() =>
{
mc.Set("key", "value", DateTimeOffset.MaxValue, "region");
});
Assert.Throws<ArgumentNullException>(() =>
{
mc.Set(null, "value", DateTimeOffset.MaxValue);
});
Assert.Throws<ArgumentNullException>(() =>
{
mc.Set("key", null, DateTimeOffset.MaxValue);
});
// The entry is never inserted as its expiration date is before now
mc.Set("key_A2", "value_A2", DateTimeOffset.MinValue);
Assert.False(mc.Contains("key_A2"));
mc.Calls.Clear();
mc.Set("key", "value", DateTimeOffset.MaxValue);
Assert.Equal(2, mc.Calls.Count);
Assert.Equal("Set (string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)", mc.Calls[0]);
Assert.Equal("Set (string key, object value, CacheItemPolicy policy, string regionName = null)", mc.Calls[1]);
}
[Fact]
public void Set_CacheItem_CacheItemPolicy()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<ArgumentNullException>(() =>
{
mc.Set(null, new CacheItemPolicy());
});
// Actually thrown from the Set (string, object, CacheItemPolicy, string) overload
var ci = new CacheItem(null, "value");
Assert.Throws<ArgumentNullException>(() =>
{
mc.Set(ci, new CacheItemPolicy());
});
ci = new CacheItem("key", null);
Assert.Throws<ArgumentNullException>(() =>
{
mc.Set(ci, new CacheItemPolicy());
});
ci = new CacheItem("key", "value");
var cip = new CacheItemPolicy();
cip.UpdateCallback = (CacheEntryUpdateArguments arguments) => { };
cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
Assert.Throws<ArgumentException>(() =>
{
mc.Set(ci, cip);
});
ci = new CacheItem("key", "value");
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.MinValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.Set(ci, cip);
});
ci = new CacheItem("key_A1-6", "value");
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromTicks(0L);
mc.Set(ci, cip);
Assert.True(mc.Contains("key_A1-6"));
ci = new CacheItem("key", "value");
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromDays(500);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.Set(ci, cip);
});
ci = new CacheItem("key_A1-8", "value");
cip = new CacheItemPolicy();
cip.SlidingExpiration = TimeSpan.FromDays(365);
mc.Set(ci, cip);
Assert.True(mc.Contains("key_A1-8"));
ci = new CacheItem("key", "value");
cip = new CacheItemPolicy();
cip.Priority = (CacheItemPriority)20;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
mc.Set(ci, cip);
});
ci = new CacheItem("key_A2", "value_A2");
cip = new CacheItemPolicy();
cip.RemovedCallback = (CacheEntryRemovedArguments arguments) => { };
mc.Set(ci, cip);
Assert.True(mc.Contains("key_A2"));
ci = new CacheItem("key_A3", "value_A3");
mc.Set(ci, new CacheItemPolicy());
Assert.True(mc.Contains("key_A3"));
Assert.Equal("value_A3", mc.Get("key_A3"));
// The entry is never inserted as its expiration date is before now
ci = new CacheItem("key_A4", "value");
cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTimeOffset.MinValue;
mc.Set(ci, cip);
Assert.False(mc.Contains("key_A4"));
ci = new CacheItem("key_A5", "value");
mc.Calls.Clear();
mc.Set(ci, new CacheItemPolicy());
Assert.Equal(2, mc.Calls.Count);
Assert.Equal("Set (CacheItem item, CacheItemPolicy policy)", mc.Calls[0]);
Assert.Equal("Set (string key, object value, CacheItemPolicy policy, string regionName = null)", mc.Calls[1]);
}
[Fact]
public void Remove()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<NotSupportedException>(() =>
{
mc.Remove("key", "region");
});
Assert.Throws<ArgumentNullException>(() =>
{
mc.Remove(null);
});
bool callbackInvoked;
CacheEntryRemovedReason reason = (CacheEntryRemovedReason)1000;
var cip = new CacheItemPolicy();
cip.Priority = CacheItemPriority.NotRemovable;
mc.Set("key2", "value1", cip);
object value = mc.Remove("key2");
Assert.NotNull(value);
Assert.False(mc.Contains("key2"));
cip = new CacheItemPolicy();
cip.RemovedCallback = (CacheEntryRemovedArguments args) =>
{
callbackInvoked = true;
reason = args.RemovedReason;
};
mc.Set("key", "value", cip);
callbackInvoked = false;
reason = (CacheEntryRemovedReason)1000;
value = mc.Remove("key");
Assert.NotNull(value);
Assert.True(callbackInvoked);
Assert.Equal(CacheEntryRemovedReason.Removed, reason);
cip = new CacheItemPolicy();
cip.RemovedCallback = (CacheEntryRemovedArguments args) =>
{
callbackInvoked = true;
reason = args.RemovedReason;
throw new ApplicationException("test");
};
mc.Set("key", "value", cip);
callbackInvoked = false;
reason = (CacheEntryRemovedReason)1000;
value = mc.Remove("key");
Assert.NotNull(value);
Assert.True(callbackInvoked);
Assert.Equal(CacheEntryRemovedReason.Removed, reason);
cip = new CacheItemPolicy();
cip.UpdateCallback = (CacheEntryUpdateArguments args) =>
{
callbackInvoked = true;
reason = args.RemovedReason;
};
mc.Set("key", "value", cip);
callbackInvoked = false;
reason = (CacheEntryRemovedReason)1000;
value = mc.Remove("key");
Assert.NotNull(value);
Assert.False(callbackInvoked);
cip = new CacheItemPolicy();
cip.UpdateCallback = (CacheEntryUpdateArguments args) =>
{
callbackInvoked = true;
reason = args.RemovedReason;
throw new ApplicationException("test");
};
mc.Set("key", "value", cip);
callbackInvoked = false;
reason = (CacheEntryRemovedReason)1000;
value = mc.Remove("key");
Assert.NotNull(value);
Assert.False(callbackInvoked);
}
[Fact]
public void GetValues()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<ArgumentNullException>(() =>
{
mc.GetValues((string[])null);
});
Assert.Throws<NotSupportedException>(() =>
{
mc.GetValues(new string[] { }, "region");
});
Assert.Throws<ArgumentException>(() =>
{
mc.GetValues(new string[] { "key", null });
});
IDictionary<string, object> value = mc.GetValues(new string[] { });
Assert.Null(value);
mc.Set("key1", "value1", null);
mc.Set("key2", "value2", null);
mc.Set("key3", "value3", null);
Assert.True(mc.Contains("key1"));
Assert.True(mc.Contains("key2"));
Assert.True(mc.Contains("key3"));
value = mc.GetValues(new string[] { "key1", "key3" });
Assert.NotNull(value);
Assert.Equal(2, value.Count);
Assert.Equal("value1", value["key1"]);
Assert.Equal("value3", value["key3"]);
Assert.Equal(typeof(Dictionary<string, object>), value.GetType());
// MSDN says the number of items in the returned dictionary should be the same as in the
// 'keys' collection - this is not the case. The returned dictionary contains only entries for keys
// that exist in the cache.
value = mc.GetValues(new string[] { "key1", "key3", "nosuchkey" });
Assert.NotNull(value);
Assert.Equal(2, value.Count);
Assert.Equal("value1", value["key1"]);
Assert.Equal("value3", value["key3"]);
Assert.False(value.ContainsKey("Key1"));
}
[Fact]
public void ChangeMonitors()
{
bool removed = false;
var mc = new PokerMemoryCache("MyCache");
var cip = new CacheItemPolicy();
var monitor = new PokerChangeMonitor();
cip.ChangeMonitors.Add(monitor);
cip.RemovedCallback = (CacheEntryRemovedArguments args) =>
{
removed = true;
};
mc.Set("key", "value", cip);
Assert.Equal(0, monitor.Calls.Count);
monitor.SignalChange();
Assert.True(removed);
bool onChangedCalled = false;
monitor = new PokerChangeMonitor();
monitor.NotifyOnChanged((object state) =>
{
onChangedCalled = true;
});
cip = new CacheItemPolicy();
cip.ChangeMonitors.Add(monitor);
// Thrown by ChangeMonitor.NotifyOnChanged
Assert.Throws<InvalidOperationException>(() =>
{
mc.Set("key1", "value1", cip);
});
Assert.False(onChangedCalled);
}
// Due to internal implementation details Trim has very few easily verifiable scenarios
[Fact]
public void Trim()
{
var config = new NameValueCollection();
config["__MonoEmulateOneCPU"] = "true";
var mc = new MemoryCache("MyCache", config);
var numCpuCores = Environment.ProcessorCount;
var numItems = numCpuCores > 1 ? numCpuCores / 2 : 1;
for (int i = 0; i < numItems;)
{
var key = "key" + i*i*i + "key" + ++i;
mc.Set(key, "value" + i.ToString(), null);
}
Assert.Equal(numItems, mc.GetCount());
// Trimming 75% for such a small number of items (supposedly each in its cache store) will end up trimming all of them
long trimmed = mc.Trim(75);
Assert.Equal(numItems, trimmed);
Assert.Equal(0, mc.GetCount());
mc = new MemoryCache("MyCache", config);
var cip = new CacheItemPolicy();
cip.Priority = CacheItemPriority.NotRemovable;
for (int i = 0; i < 11; i++)
{
mc.Set("key" + i.ToString(), "value" + i.ToString(), cip);
}
Assert.Equal(11, mc.GetCount());
trimmed = mc.Trim(50);
Assert.Equal(11, mc.GetCount());
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses "physicalMemoryLimitPercentage" not supported on other platforms
public void TestExpiredGetValues()
{
var config = new NameValueCollection();
config["cacheMemoryLimitMegabytes"] = 0.ToString();
config["physicalMemoryLimitPercentage"] = 100.ToString();
config["pollingInterval"] = new TimeSpan(0, 0, 10).ToString();
using (var mc = new MemoryCache("TestExpiredGetValues", config))
{
Assert.Equal(0, mc.GetCount());
var keys = new List<string>();
// add some short duration entries
for (int i = 0; i < 10; i++)
{
var key = "short-" + i;
var expireAt = DateTimeOffset.Now.AddMilliseconds(50);
mc.Add(key, i.ToString(), expireAt);
keys.Add(key);
}
Assert.Equal(10, mc.GetCount());
// wait past expiration and call GetValues() - this does not affect the count
Thread.Sleep(100);
mc.GetValues(keys);
Assert.Equal(0, mc.GetCount());
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses "physicalMemoryLimitPercentage" not supported on other platforms
[OuterLoop] // makes long wait
public void TestCacheSliding()
{
var config = new NameValueCollection();
config["cacheMemoryLimitMegabytes"] = 0.ToString();
config["physicalMemoryLimitPercentage"] = 100.ToString();
config["pollingInterval"] = new TimeSpan(0, 0, 1).ToString();
using (var mc = new MemoryCache("TestCacheSliding", config))
{
Assert.Equal(0, mc.GetCount());
var cip = new CacheItemPolicy();
// The sliding expiration timeout has to be greater than 1 second because
// .NET implementation ignores timeouts updates smaller than
// CacheExpires.MIN_UPDATE_DELTA which is equal to 1.
const int SlidingExpirationThresholdMSec = 4000;
cip.SlidingExpiration = TimeSpan.FromMilliseconds(SlidingExpirationThresholdMSec);
mc.Add("slidingtest", "42", cip);
mc.Add("expire1", "1", cip);
mc.Add("expire2", "2", cip);
mc.Add("expire3", "3", cip);
mc.Add("expire4", "4", cip);
mc.Add("expire5", "5", cip);
Assert.Equal(6, mc.GetCount());
// The loop below would sleep for ~5 seconds total (in 50 intervals).
// Each of these intervals is only supposed to be ~100ms.
// However due to concurrency with other tests and various system conditions,
// we observe occasional delays that are much longer than the SlidingExpirationThresholdMSec
// expiration period which causes the "slidingtest" cache item to expire
Stopwatch sw = new Stopwatch();
for (int i = 0; i < 50; i++)
{
sw.Restart();
Thread.Sleep(100);
var item = mc.Get("slidingtest");
sw.Stop();
if (sw.ElapsedMilliseconds < SlidingExpirationThresholdMSec)
{
Assert.NotEqual(null, item);
}
else
{
// for the sake of simplicity skip an inversed assert here (Assert.Equal(null, item))
// (to avoid further complicating the test as we would need to address a few more subtle timing cases)
}
}
Assert.Null(mc.Get("expire1"));
Assert.Null(mc.Get("expire2"));
Assert.Null(mc.Get("expire3"));
Assert.Null(mc.Get("expire4"));
Assert.Null(mc.Get("expire5"));
Assert.Equal(1, mc.GetCount());
Thread.Sleep(SlidingExpirationThresholdMSec + 1000);
Assert.Null(mc.Get("slidingtest"));
Assert.Equal(0, mc.GetCount());
}
}
}
public class MemoryCacheTestExpires1
{
[Fact]
[OuterLoop] // makes long wait
public async Task TimedExpirationAsync()
{
bool removed = false;
CacheEntryRemovedReason reason = CacheEntryRemovedReason.CacheSpecificEviction;
int sleepPeriod = 20000;
var mc = new PokerMemoryCache("MyCache");
var cip = new CacheItemPolicy();
cip.RemovedCallback = (CacheEntryRemovedArguments args) =>
{
removed = true;
reason = args.RemovedReason;
};
cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(50);
mc.Set("key", "value", cip);
// Wait past cip.AbsoluteExpiration
Thread.Sleep(500);
object value = mc.Get("key");
Assert.Null(value);
// Rather than waiting for the expiration callback to fire,
// we replace the cache item and verify that the reason is still Expired
mc.Set("key", "value2", cip);
Assert.True(removed);
Assert.Equal(CacheEntryRemovedReason.Expired, reason);
removed = false;
cip = new CacheItemPolicy();
cip.RemovedCallback = (CacheEntryRemovedArguments args) =>
{
removed = true;
reason = args.RemovedReason;
};
cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(50);
mc.Set("key", "value", cip);
await Task.Delay(sleepPeriod);
Assert.Null(mc.Get("key"));
Assert.True(removed);
Assert.Equal(CacheEntryRemovedReason.Expired, reason);
}
}
public class MemoryCacheTestExpires11
{
[Fact]
[OuterLoop] // makes long wait
public async Task TimedExpirationAsync()
{
int sleepPeriod = 20000;
var mc = new PokerMemoryCache("MyCache");
var cip = new CacheItemPolicy();
int expiredCount = 0;
object expiredCountLock = new object();
CacheEntryRemovedCallback removedCb = (CacheEntryRemovedArguments args) =>
{
lock (expiredCountLock)
{
expiredCount++;
}
};
cip = new CacheItemPolicy();
cip.RemovedCallback = removedCb;
cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(20);
mc.Set("key1", "value1", cip);
cip = new CacheItemPolicy();
cip.RemovedCallback = removedCb;
cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(200);
mc.Set("key2", "value2", cip);
cip = new CacheItemPolicy();
cip.RemovedCallback = removedCb;
cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(600);
mc.Set("key3", "value3", cip);
cip = new CacheItemPolicy();
cip.RemovedCallback = removedCb;
cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(sleepPeriod + 55500);
mc.Set("key4", "value4", cip);
await Task.Delay(sleepPeriod);
Assert.Null(mc.Get("key1"));
Assert.Null(mc.Get("key2"));
Assert.Null(mc.Get("key3"));
Assert.NotNull(mc.Get("key4"));
Assert.Equal(3, expiredCount);
}
}
public class MemoryCacheTestExpires2
{
[Fact]
[OuterLoop] // makes long wait
public async Task GetEnumeratorAsync()
{
var mc = new PokerMemoryCache("MyCache");
// This one is a Hashtable enumerator
IEnumerator enumerator = ((IEnumerable)mc).GetEnumerator();
// This one is a Dictionary <string, object> enumerator
IEnumerator enumerator2 = mc.DoGetEnumerator();
Assert.NotNull(enumerator);
Assert.NotNull(enumerator2);
Assert.True(enumerator.GetType() != enumerator2.GetType());
mc.Set("key1", "value1", null);
mc.Set("key2", "value2", null);
mc.Set("key3", "value3", null);
bool expired4 = false;
var cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTime.Now.AddMilliseconds(50);
cip.RemovedCallback = (CacheEntryRemovedArguments args) =>
{
expired4 = true;
};
mc.Set("key4", "value4", cip);
// wait past "key4" AbsoluteExpiration
Thread.Sleep(500);
enumerator = ((IEnumerable)mc).GetEnumerator();
int count = 0;
while (enumerator.MoveNext())
{
count++;
}
Assert.Equal(3, count);
bool expired5 = false;
cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTime.Now.AddMilliseconds(50);
cip.RemovedCallback = (CacheEntryRemovedArguments args) =>
{
expired5 = true;
};
mc.Set("key5", "value5", cip);
await Task.Delay(20500);
enumerator2 = mc.DoGetEnumerator();
count = 0;
while (enumerator2.MoveNext())
{
count++;
}
Assert.True(expired4);
Assert.True(expired5);
Assert.Equal(3, count);
}
}
public class MemoryCacheTestExpires3
{
[Fact]
[OuterLoop] // makes long wait
public async Task GetCacheItem()
{
var mc = new PokerMemoryCache("MyCache");
Assert.Throws<NotSupportedException>(() =>
{
mc.GetCacheItem("key", "region");
});
Assert.Throws<ArgumentNullException>(() =>
{
mc.GetCacheItem(null);
});
CacheItem value;
mc.Set("key", "value", null);
value = mc.GetCacheItem("key");
Assert.NotNull(value);
Assert.Equal("value", value.Value);
Assert.Equal("key", value.Key);
value = mc.GetCacheItem("doesnotexist");
Assert.Null(value);
var cip = new CacheItemPolicy();
bool callbackInvoked = false;
CacheEntryRemovedReason reason = (CacheEntryRemovedReason)1000;
cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(50);
cip.RemovedCallback = (CacheEntryRemovedArguments args) =>
{
callbackInvoked = true;
reason = args.RemovedReason;
};
mc.Set("key", "value", cip);
// wait past the expiration time and verify that the item is gone
await Task.Delay(500);
value = mc.GetCacheItem("key");
Assert.Null(value);
// add a new item with the same key
cip = new CacheItemPolicy();
cip.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(50);
cip.RemovedCallback = (CacheEntryRemovedArguments args) =>
{
callbackInvoked = true;
reason = args.RemovedReason;
throw new ApplicationException("test");
};
mc.Set("key", "value", cip);
// and verify that the old item callback is called
Assert.True(callbackInvoked);
Assert.Equal(CacheEntryRemovedReason.Expired, reason);
callbackInvoked = false;
reason = (CacheEntryRemovedReason)1000;
// wait for both expiration and the callback of the new item
await Task.Delay(20500);
value = mc.GetCacheItem("key");
Assert.Null(value);
Assert.True(callbackInvoked);
Assert.Equal(CacheEntryRemovedReason.Expired, reason);
}
}
public class MemoryCacheTestExpires4
{
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses "physicalMemoryLimitPercentage" not supported on other platforms
public async Task TestCacheShrink()
{
const int HEAP_RESIZE_THRESHOLD = 8192 + 2;
const int HEAP_RESIZE_SHORT_ENTRIES = 2048;
const int HEAP_RESIZE_LONG_ENTRIES = HEAP_RESIZE_THRESHOLD - HEAP_RESIZE_SHORT_ENTRIES;
var config = new NameValueCollection();
config["cacheMemoryLimitMegabytes"] = 0.ToString();
config["physicalMemoryLimitPercentage"] = 100.ToString();
config["pollingInterval"] = new TimeSpan(0, 0, 1).ToString();
using (var mc = new MemoryCache("TestCacheShrink", config))
{
Assert.Equal(0, mc.GetCount());
// add some short duration entries
for (int i = 0; i < HEAP_RESIZE_SHORT_ENTRIES; i++)
{
var expireAt = DateTimeOffset.Now.AddSeconds(3);
mc.Add("short-" + i, i.ToString(), expireAt);
}
Assert.Equal(HEAP_RESIZE_SHORT_ENTRIES, mc.GetCount());
// add some long duration entries
for (int i = 0; i < HEAP_RESIZE_LONG_ENTRIES; i++)
{
var expireAt = DateTimeOffset.Now.AddSeconds(42);
mc.Add("long-" + i, i.ToString(), expireAt);
}
Assert.Equal(HEAP_RESIZE_LONG_ENTRIES + HEAP_RESIZE_SHORT_ENTRIES, mc.GetCount());
// wait past the short duration items expiration time
await Task.Delay(4000);
/// the following will also shrink the size of the cache
for (int i = 0; i < HEAP_RESIZE_SHORT_ENTRIES; i++)
{
Assert.Null(mc.Get("short-" + i));
}
Assert.Equal(HEAP_RESIZE_LONG_ENTRIES, mc.GetCount());
// add some new items into the cache, this will grow the cache again
for (int i = 0; i < HEAP_RESIZE_LONG_ENTRIES; i++)
{
mc.Add("final-" + i, i.ToString(), DateTimeOffset.Now.AddSeconds(4));
}
Assert.Equal(HEAP_RESIZE_LONG_ENTRIES + HEAP_RESIZE_LONG_ENTRIES, mc.GetCount());
}
}
}
public class MemoryCacheTestExpires5
{
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses "physicalMemoryLimitPercentage" not supported on other platforms
public async Task TestCacheExpiryOrdering()
{
var config = new NameValueCollection();
config["cacheMemoryLimitMegabytes"] = 0.ToString();
config["physicalMemoryLimitPercentage"] = 100.ToString();
config["pollingInterval"] = new TimeSpan(0, 0, 1).ToString();
using (var mc = new MemoryCache("TestCacheExpiryOrdering", config))
{
Assert.Equal(0, mc.GetCount());
// add long lived items into the cache first
for (int i = 0; i < 100; i++)
{
var cip = new CacheItemPolicy();
cip.SlidingExpiration = new TimeSpan(0, 0, 4);
mc.Add("long-" + i, i, cip);
}
Assert.Equal(100, mc.GetCount());
// add shorter lived items into the cache, these should expire first
for (int i = 0; i < 100; i++)
{
var cip = new CacheItemPolicy();
cip.SlidingExpiration = new TimeSpan(0, 0, 1);
mc.Add("short-" + i, i, cip);
}
Assert.Equal(200, mc.GetCount());
await Task.Delay(2000);
for (int i = 0; i < 100; i++)
{
Assert.Null(mc.Get("short-" + i));
}
Assert.Equal(100, mc.GetCount());
}
}
}
}
| |
namespace KabMan.Forms
{
partial class ReportForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.CBarManager = new DevExpress.XtraBars.BarManager(this.components);
this.CStatusBar = new DevExpress.XtraBars.Bar();
this.itemResultCount = new DevExpress.XtraBars.BarStaticItem();
this.bar1 = new DevExpress.XtraBars.Bar();
this.itemPreview = new DevExpress.XtraBars.BarButtonItem();
this.ItemBtnClose = new DevExpress.XtraBars.BarButtonItem();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.itemClose = new DevExpress.XtraBars.BarButtonItem();
this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.CSearchType = new DevExpress.XtraEditors.ComboBoxEdit();
this.CResultGrid = new DevExpress.XtraGrid.GridControl();
this.CResultView = new DevExpress.XtraGrid.Views.Grid.GridView();
this.CSearchThis = new DevExpress.XtraEditors.TextEdit();
this.CSearchIn = new DevExpress.XtraEditors.ComboBoxEdit();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
this.layoutControlGroup2 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.CSearchTypeItemControl = new DevExpress.XtraLayout.LayoutControlItem();
((System.ComponentModel.ISupportInitialize)(this.CBarManager)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.CSearchType.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CResultGrid)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CResultView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CSearchThis.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CSearchIn.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CSearchTypeItemControl)).BeginInit();
this.SuspendLayout();
//
// CBarManager
//
this.CBarManager.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.CStatusBar,
this.bar1});
this.CBarManager.DockControls.Add(this.barDockControlTop);
this.CBarManager.DockControls.Add(this.barDockControlBottom);
this.CBarManager.DockControls.Add(this.barDockControlLeft);
this.CBarManager.DockControls.Add(this.barDockControlRight);
this.CBarManager.Form = this;
this.CBarManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.itemClose,
this.itemResultCount,
this.barButtonItem1,
this.itemPreview,
this.ItemBtnClose});
this.CBarManager.MaxItemId = 5;
this.CBarManager.StatusBar = this.CStatusBar;
//
// CStatusBar
//
this.CStatusBar.BarName = "Status Bar";
this.CStatusBar.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom;
this.CStatusBar.DockCol = 0;
this.CStatusBar.DockRow = 0;
this.CStatusBar.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom;
this.CStatusBar.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.itemResultCount)});
this.CStatusBar.OptionsBar.AllowQuickCustomization = false;
this.CStatusBar.OptionsBar.DrawDragBorder = false;
this.CStatusBar.OptionsBar.UseWholeRow = true;
this.CStatusBar.Text = "Status Bar";
//
// itemResultCount
//
this.itemResultCount.Caption = "0";
this.itemResultCount.Id = 1;
this.itemResultCount.Name = "itemResultCount";
this.itemResultCount.TextAlignment = System.Drawing.StringAlignment.Near;
//
// bar1
//
this.bar1.BarName = "Custom 3";
this.bar1.DockCol = 0;
this.bar1.DockRow = 0;
this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(DevExpress.XtraBars.BarLinkUserDefines.PaintStyle, this.itemPreview, "", true, true, true, 0, null, DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph),
new DevExpress.XtraBars.LinkPersistInfo(this.ItemBtnClose, true)});
this.bar1.OptionsBar.AllowQuickCustomization = false;
this.bar1.OptionsBar.DrawDragBorder = false;
this.bar1.OptionsBar.UseWholeRow = true;
this.bar1.Text = "Custom 3";
//
// itemPreview
//
this.itemPreview.Caption = "Print Preview";
this.itemPreview.Id = 3;
this.itemPreview.Name = "itemPreview";
this.itemPreview.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemPreview.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem1_ItemClick);
//
// ItemBtnClose
//
this.ItemBtnClose.Caption = "Exit";
this.ItemBtnClose.Glyph = global::KabMan.Properties.Resources.ManagerExit;
this.ItemBtnClose.Id = 4;
this.ItemBtnClose.Name = "ItemBtnClose";
this.ItemBtnClose.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.ItemBtnClose.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemClose_ItemClick);
//
// itemClose
//
this.itemClose.Caption = "&Close";
this.itemClose.Id = 0;
this.itemClose.Name = "itemClose";
this.itemClose.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemClose.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemClose_ItemClick);
//
// barButtonItem1
//
this.barButtonItem1.Caption = "Print Preview";
this.barButtonItem1.Id = 2;
this.barButtonItem1.Name = "barButtonItem1";
this.barButtonItem1.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.barButtonItem1.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem1_ItemClick);
//
// layoutControl1
//
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.CSearchType);
this.layoutControl1.Controls.Add(this.CResultGrid);
this.layoutControl1.Controls.Add(this.CSearchThis);
this.layoutControl1.Controls.Add(this.CSearchIn);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 26);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(721, 546);
this.layoutControl1.TabIndex = 4;
this.layoutControl1.Text = "layoutControl1";
//
// CSearchType
//
this.CSearchType.Location = new System.Drawing.Point(68, 59);
this.CSearchType.MenuManager = this.CBarManager;
this.CSearchType.Name = "CSearchType";
this.CSearchType.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.CSearchType.Properties.Items.AddRange(new object[] {
"DASD",
"Server",
"DCC"});
this.CSearchType.Properties.NullText = "Select Device!";
this.CSearchType.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
this.CSearchType.Size = new System.Drawing.Size(302, 20);
this.CSearchType.StyleController = this.layoutControl1;
this.CSearchType.TabIndex = 7;
this.CSearchType.SelectedIndexChanged += new System.EventHandler(this.comboBoxEdit1_SelectedIndexChanged);
//
// CResultGrid
//
this.CResultGrid.Location = new System.Drawing.Point(7, 124);
this.CResultGrid.MainView = this.CResultView;
this.CResultGrid.Name = "CResultGrid";
this.CResultGrid.Size = new System.Drawing.Size(708, 416);
this.CResultGrid.TabIndex = 6;
this.CResultGrid.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.CResultView});
//
// CResultView
//
this.CResultView.GridControl = this.CResultGrid;
this.CResultView.Name = "CResultView";
this.CResultView.OptionsBehavior.Editable = false;
this.CResultView.OptionsView.EnableAppearanceEvenRow = true;
this.CResultView.OptionsView.EnableAppearanceOddRow = true;
this.CResultView.OptionsView.ShowGroupPanel = false;
this.CResultView.OptionsView.ShowIndicator = false;
//
// CSearchThis
//
this.CSearchThis.Location = new System.Drawing.Point(68, 90);
this.CSearchThis.Name = "CSearchThis";
this.CSearchThis.Size = new System.Drawing.Size(302, 20);
this.CSearchThis.StyleController = this.layoutControl1;
this.CSearchThis.TabIndex = 5;
this.CSearchThis.EditValueChanged += new System.EventHandler(this.CSearchThis_EditValueChanged);
//
// CSearchIn
//
this.CSearchIn.Location = new System.Drawing.Point(68, 28);
this.CSearchIn.Name = "CSearchIn";
this.CSearchIn.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
this.CSearchIn.Properties.Items.AddRange(new object[] {
"Cable",
"Connection",
"Server",
"Switch",
"DASD",
"DCC"});
this.CSearchIn.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
this.CSearchIn.Size = new System.Drawing.Size(302, 20);
this.CSearchIn.StyleController = this.layoutControl1;
this.CSearchIn.TabIndex = 4;
this.CSearchIn.SelectedIndexChanged += new System.EventHandler(this.CSearchIn_SelectedIndexChanged);
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem3,
this.emptySpaceItem1,
this.layoutControlGroup2});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "Root";
this.layoutControlGroup1.Size = new System.Drawing.Size(721, 546);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "Root";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.CResultGrid;
this.layoutControlItem3.CustomizationFormText = "layoutControlItem3";
this.layoutControlItem3.Location = new System.Drawing.Point(0, 117);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(719, 427);
this.layoutControlItem3.Text = "layoutControlItem3";
this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem3.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem3.TextToControlDistance = 0;
this.layoutControlItem3.TextVisible = false;
//
// emptySpaceItem1
//
this.emptySpaceItem1.CustomizationFormText = "emptySpaceItem1";
this.emptySpaceItem1.Location = new System.Drawing.Point(377, 0);
this.emptySpaceItem1.Name = "emptySpaceItem1";
this.emptySpaceItem1.Size = new System.Drawing.Size(342, 117);
this.emptySpaceItem1.Text = "emptySpaceItem1";
this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
//
// layoutControlGroup2
//
this.layoutControlGroup2.CustomizationFormText = "Kategorized Report";
this.layoutControlGroup2.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1,
this.layoutControlItem2,
this.CSearchTypeItemControl});
this.layoutControlGroup2.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup2.Name = "layoutControlGroup2";
this.layoutControlGroup2.Size = new System.Drawing.Size(377, 117);
this.layoutControlGroup2.Text = "Categorized Report";
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.CSearchIn;
this.layoutControlItem1.CustomizationFormText = "Search in";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem1.MaxSize = new System.Drawing.Size(371, 31);
this.layoutControlItem1.MinSize = new System.Drawing.Size(371, 31);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(371, 31);
this.layoutControlItem1.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.layoutControlItem1.Text = "Search in";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(53, 13);
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.CSearchThis;
this.layoutControlItem2.CustomizationFormText = "Search this";
this.layoutControlItem2.Location = new System.Drawing.Point(0, 62);
this.layoutControlItem2.MaxSize = new System.Drawing.Size(371, 31);
this.layoutControlItem2.MinSize = new System.Drawing.Size(371, 31);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(371, 31);
this.layoutControlItem2.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.layoutControlItem2.Text = "Search this";
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem2.TextSize = new System.Drawing.Size(53, 13);
//
// CSearchTypeItemControl
//
this.CSearchTypeItemControl.Control = this.CSearchType;
this.CSearchTypeItemControl.CustomizationFormText = "Device";
this.CSearchTypeItemControl.Location = new System.Drawing.Point(0, 31);
this.CSearchTypeItemControl.Name = "CSearchTypeItemControl";
this.CSearchTypeItemControl.Size = new System.Drawing.Size(371, 31);
this.CSearchTypeItemControl.Text = "Device";
this.CSearchTypeItemControl.TextLocation = DevExpress.Utils.Locations.Left;
this.CSearchTypeItemControl.TextSize = new System.Drawing.Size(53, 13);
this.CSearchTypeItemControl.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
//
// ReportForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(721, 595);
this.Controls.Add(this.layoutControl1);
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.Name = "ReportForm";
this.Text = "Reports";
((System.ComponentModel.ISupportInitialize)(this.CBarManager)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.CSearchType.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CResultGrid)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CResultView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CSearchThis.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CSearchIn.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CSearchTypeItemControl)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraBars.BarManager CBarManager;
private DevExpress.XtraBars.Bar CStatusBar;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraBars.BarButtonItem itemClose;
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraGrid.GridControl CResultGrid;
private DevExpress.XtraGrid.Views.Grid.GridView CResultView;
private DevExpress.XtraEditors.TextEdit CSearchThis;
private DevExpress.XtraEditors.ComboBoxEdit CSearchIn;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraBars.BarStaticItem itemResultCount;
private DevExpress.XtraBars.BarButtonItem barButtonItem1;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup2;
private DevExpress.XtraBars.Bar bar1;
private DevExpress.XtraBars.BarButtonItem itemPreview;
private DevExpress.XtraBars.BarButtonItem ItemBtnClose;
private DevExpress.XtraEditors.ComboBoxEdit CSearchType;
private DevExpress.XtraLayout.LayoutControlItem CSearchTypeItemControl;
}
}
| |
using System;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using C1.Win.C1Input;
using C1.Win.C1TrueDBGrid;
using PCSComProcurement.Purchase.BO;
using PCSComUtils.Common;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
using CancelEventArgs = System.ComponentModel.CancelEventArgs;
namespace PCSProcurement.Purchase
{
/// <summary>
/// Summary description for DeliveryApproval.
/// </summary>
public class DeliveryApproval : Form
{
private TextBox txtPONo;
private Button btnPONo;
private Label lblPONo;
private Label lblToStartDate;
private Label lblFromStartDate;
private Label lblCategory;
private TextBox txtCategory;
private Button btnCategory;
private TextBox txtPartName;
private TextBox txtModel;
private TextBox txtPartNumber;
private Button btnPartName;
private Label lblPartName;
private Button btnPartNumber;
private Label lblPartNumber;
private Label lblModel;
private C1DateEdit dtmToDate;
private C1DateEdit dtmFromDate;
private Button btnShowDetail;
private Button btnSearch;
private Button btnHelp;
private Button btnApprove;
private Button btnClose;
private CheckBox chkSelectAll;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
const string THIS = "PCSProcurement.Purchase.DeliveryApproval";
private C1TrueDBGrid dgrdData;
private DataTable dtbGridLayOut = new DataTable();
private DataSet dstData = new DataSet();
private bool blnStateOfCheck = false;
public DeliveryApproval()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(DeliveryApproval));
this.txtPONo = new System.Windows.Forms.TextBox();
this.btnPONo = new System.Windows.Forms.Button();
this.lblPONo = new System.Windows.Forms.Label();
this.dtmToDate = new C1.Win.C1Input.C1DateEdit();
this.dtmFromDate = new C1.Win.C1Input.C1DateEdit();
this.lblToStartDate = new System.Windows.Forms.Label();
this.lblFromStartDate = new System.Windows.Forms.Label();
this.lblCategory = new System.Windows.Forms.Label();
this.txtCategory = new System.Windows.Forms.TextBox();
this.btnCategory = new System.Windows.Forms.Button();
this.txtPartName = new System.Windows.Forms.TextBox();
this.txtModel = new System.Windows.Forms.TextBox();
this.txtPartNumber = new System.Windows.Forms.TextBox();
this.btnPartName = new System.Windows.Forms.Button();
this.lblPartName = new System.Windows.Forms.Label();
this.btnPartNumber = new System.Windows.Forms.Button();
this.lblPartNumber = new System.Windows.Forms.Label();
this.lblModel = new System.Windows.Forms.Label();
this.btnShowDetail = new System.Windows.Forms.Button();
this.btnSearch = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.btnApprove = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.dgrdData = new C1.Win.C1TrueDBGrid.C1TrueDBGrid();
this.chkSelectAll = new System.Windows.Forms.CheckBox();
((System.ComponentModel.ISupportInitialize)(this.dtmToDate)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dtmFromDate)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).BeginInit();
this.SuspendLayout();
//
// txtPONo
//
this.txtPONo.Location = new System.Drawing.Point(90, 34);
this.txtPONo.Name = "txtPONo";
this.txtPONo.Size = new System.Drawing.Size(122, 20);
this.txtPONo.TabIndex = 5;
this.txtPONo.Text = "";
this.txtPONo.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtPONo_KeyDown);
this.txtPONo.Validating += new System.ComponentModel.CancelEventHandler(this.txtPONo_Validating);
//
// btnPONo
//
this.btnPONo.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnPONo.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnPONo.Location = new System.Drawing.Point(214, 34);
this.btnPONo.Name = "btnPONo";
this.btnPONo.Size = new System.Drawing.Size(24, 20);
this.btnPONo.TabIndex = 6;
this.btnPONo.Text = "...";
this.btnPONo.Click += new System.EventHandler(this.btnPONo_Click);
//
// lblPONo
//
this.lblPONo.ForeColor = System.Drawing.Color.Black;
this.lblPONo.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblPONo.Location = new System.Drawing.Point(6, 34);
this.lblPONo.Name = "lblPONo";
this.lblPONo.Size = new System.Drawing.Size(82, 20);
this.lblPONo.TabIndex = 4;
this.lblPONo.Text = "PO No.";
this.lblPONo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// dtmToDate
//
//
// dtmToDate.Calendar
//
this.dtmToDate.Calendar.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.dtmToDate.CustomFormat = "dd-MM-yyyy";
this.dtmToDate.EmptyAsNull = true;
this.dtmToDate.FormatType = C1.Win.C1Input.FormatTypeEnum.CustomFormat;
this.dtmToDate.Location = new System.Drawing.Point(288, 12);
this.dtmToDate.Name = "dtmToDate";
this.dtmToDate.Size = new System.Drawing.Size(122, 20);
this.dtmToDate.TabIndex = 3;
this.dtmToDate.Tag = null;
this.dtmToDate.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.dtmToDate.VisibleButtons = C1.Win.C1Input.DropDownControlButtonFlags.DropDown;
//
// dtmFromDate
//
//
// dtmFromDate.Calendar
//
this.dtmFromDate.Calendar.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.dtmFromDate.CustomFormat = "dd-MM-yyyy";
this.dtmFromDate.EmptyAsNull = true;
this.dtmFromDate.FormatType = C1.Win.C1Input.FormatTypeEnum.CustomFormat;
this.dtmFromDate.Location = new System.Drawing.Point(90, 12);
this.dtmFromDate.Name = "dtmFromDate";
this.dtmFromDate.Size = new System.Drawing.Size(122, 20);
this.dtmFromDate.TabIndex = 1;
this.dtmFromDate.Tag = null;
this.dtmFromDate.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.dtmFromDate.VisibleButtons = C1.Win.C1Input.DropDownControlButtonFlags.DropDown;
//
// lblToStartDate
//
this.lblToStartDate.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblToStartDate.Location = new System.Drawing.Point(240, 12);
this.lblToStartDate.Name = "lblToStartDate";
this.lblToStartDate.Size = new System.Drawing.Size(82, 20);
this.lblToStartDate.TabIndex = 2;
this.lblToStartDate.Text = "To Date";
this.lblToStartDate.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblFromStartDate
//
this.lblFromStartDate.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblFromStartDate.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblFromStartDate.Location = new System.Drawing.Point(6, 12);
this.lblFromStartDate.Name = "lblFromStartDate";
this.lblFromStartDate.Size = new System.Drawing.Size(82, 20);
this.lblFromStartDate.TabIndex = 0;
this.lblFromStartDate.Text = "From Date";
this.lblFromStartDate.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblCategory
//
this.lblCategory.AccessibleDescription = "";
this.lblCategory.AccessibleName = "";
this.lblCategory.ForeColor = System.Drawing.Color.Black;
this.lblCategory.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblCategory.Location = new System.Drawing.Point(6, 56);
this.lblCategory.Name = "lblCategory";
this.lblCategory.Size = new System.Drawing.Size(82, 20);
this.lblCategory.TabIndex = 7;
this.lblCategory.Text = "Category";
this.lblCategory.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// txtCategory
//
this.txtCategory.Location = new System.Drawing.Point(90, 56);
this.txtCategory.Name = "txtCategory";
this.txtCategory.Size = new System.Drawing.Size(122, 20);
this.txtCategory.TabIndex = 8;
this.txtCategory.Text = "";
this.txtCategory.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtCategory_KeyDown);
this.txtCategory.Validating += new System.ComponentModel.CancelEventHandler(this.txtCategory_Validating);
//
// btnCategory
//
this.btnCategory.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnCategory.Location = new System.Drawing.Point(214, 56);
this.btnCategory.Name = "btnCategory";
this.btnCategory.Size = new System.Drawing.Size(24, 20);
this.btnCategory.TabIndex = 9;
this.btnCategory.Text = "...";
this.btnCategory.Click += new System.EventHandler(this.btnCategory_Click);
//
// txtPartName
//
this.txtPartName.Location = new System.Drawing.Point(90, 100);
this.txtPartName.Name = "txtPartName";
this.txtPartName.Size = new System.Drawing.Size(332, 20);
this.txtPartName.TabIndex = 16;
this.txtPartName.Text = "";
this.txtPartName.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtPartName_KeyDown);
this.txtPartName.Validating += new System.ComponentModel.CancelEventHandler(this.txtPartName_Validating);
//
// txtModel
//
this.txtModel.Location = new System.Drawing.Point(288, 78);
this.txtModel.Name = "txtModel";
this.txtModel.ReadOnly = true;
this.txtModel.Size = new System.Drawing.Size(134, 20);
this.txtModel.TabIndex = 14;
this.txtModel.Text = "";
//
// txtPartNumber
//
this.txtPartNumber.Location = new System.Drawing.Point(90, 78);
this.txtPartNumber.Name = "txtPartNumber";
this.txtPartNumber.Size = new System.Drawing.Size(122, 20);
this.txtPartNumber.TabIndex = 11;
this.txtPartNumber.Text = "";
this.txtPartNumber.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtPartNumber_KeyDown);
this.txtPartNumber.Validating += new System.ComponentModel.CancelEventHandler(this.txtPartNumber_Validating);
//
// btnPartName
//
this.btnPartName.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnPartName.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnPartName.Location = new System.Drawing.Point(424, 100);
this.btnPartName.Name = "btnPartName";
this.btnPartName.Size = new System.Drawing.Size(24, 20);
this.btnPartName.TabIndex = 17;
this.btnPartName.Text = "...";
this.btnPartName.Click += new System.EventHandler(this.btnPartName_Click);
//
// lblPartName
//
this.lblPartName.ForeColor = System.Drawing.Color.Black;
this.lblPartName.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblPartName.Location = new System.Drawing.Point(6, 100);
this.lblPartName.Name = "lblPartName";
this.lblPartName.Size = new System.Drawing.Size(82, 20);
this.lblPartName.TabIndex = 15;
this.lblPartName.Text = "Part Name";
this.lblPartName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnPartNumber
//
this.btnPartNumber.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnPartNumber.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnPartNumber.Location = new System.Drawing.Point(214, 78);
this.btnPartNumber.Name = "btnPartNumber";
this.btnPartNumber.Size = new System.Drawing.Size(24, 20);
this.btnPartNumber.TabIndex = 12;
this.btnPartNumber.Text = "...";
this.btnPartNumber.Click += new System.EventHandler(this.btnPartNumber_Click);
//
// lblPartNumber
//
this.lblPartNumber.ForeColor = System.Drawing.Color.Black;
this.lblPartNumber.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblPartNumber.Location = new System.Drawing.Point(6, 78);
this.lblPartNumber.Name = "lblPartNumber";
this.lblPartNumber.Size = new System.Drawing.Size(82, 20);
this.lblPartNumber.TabIndex = 10;
this.lblPartNumber.Text = "Part Number";
this.lblPartNumber.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblModel
//
this.lblModel.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.lblModel.Location = new System.Drawing.Point(240, 78);
this.lblModel.Name = "lblModel";
this.lblModel.Size = new System.Drawing.Size(82, 20);
this.lblModel.TabIndex = 13;
this.lblModel.Text = "Model";
this.lblModel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// btnShowDetail
//
this.btnShowDetail.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnShowDetail.Location = new System.Drawing.Point(453, 442);
this.btnShowDetail.Name = "btnShowDetail";
this.btnShowDetail.Size = new System.Drawing.Size(84, 22);
this.btnShowDetail.TabIndex = 22;
this.btnShowDetail.Text = "Show D&etail";
this.btnShowDetail.Click += new System.EventHandler(this.btnShowDetail_Click);
//
// btnSearch
//
this.btnSearch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnSearch.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnSearch.Location = new System.Drawing.Point(586, 100);
this.btnSearch.Name = "btnSearch";
this.btnSearch.Size = new System.Drawing.Size(80, 22);
this.btnSearch.TabIndex = 18;
this.btnSearch.Text = "Sea&rch";
this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
//
// btnHelp
//
this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnHelp.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnHelp.Location = new System.Drawing.Point(538, 442);
this.btnHelp.Name = "btnHelp";
this.btnHelp.Size = new System.Drawing.Size(64, 22);
this.btnHelp.TabIndex = 23;
this.btnHelp.Text = "&Help";
//
// btnApprove
//
this.btnApprove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnApprove.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnApprove.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnApprove.Location = new System.Drawing.Point(6, 442);
this.btnApprove.Name = "btnApprove";
this.btnApprove.Size = new System.Drawing.Size(76, 22);
this.btnApprove.TabIndex = 21;
this.btnApprove.Text = "&Save";
this.btnApprove.Click += new System.EventHandler(this.btnApprove_Click);
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnClose.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnClose.Location = new System.Drawing.Point(603, 442);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(64, 22);
this.btnClose.TabIndex = 24;
this.btnClose.Text = "&Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// dgrdData
//
this.dgrdData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dgrdData.CaptionHeight = 17;
this.dgrdData.CollapseColor = System.Drawing.Color.Black;
this.dgrdData.ExpandColor = System.Drawing.Color.Black;
this.dgrdData.FlatStyle = C1.Win.C1TrueDBGrid.FlatModeEnum.System;
this.dgrdData.GroupByCaption = "Drag a column header here to group by that column";
this.dgrdData.Images.Add(((System.Drawing.Image)(resources.GetObject("resource"))));
this.dgrdData.Location = new System.Drawing.Point(6, 124);
this.dgrdData.MarqueeStyle = C1.Win.C1TrueDBGrid.MarqueeEnum.DottedCellBorder;
this.dgrdData.Name = "dgrdData";
this.dgrdData.PreviewInfo.Location = new System.Drawing.Point(0, 0);
this.dgrdData.PreviewInfo.Size = new System.Drawing.Size(0, 0);
this.dgrdData.PreviewInfo.ZoomFactor = 75;
this.dgrdData.PrintInfo.ShowOptionsDialog = false;
this.dgrdData.RecordSelectorWidth = 17;
this.dgrdData.RowDivider.Color = System.Drawing.Color.DarkGray;
this.dgrdData.RowDivider.Style = C1.Win.C1TrueDBGrid.LineStyleEnum.Single;
this.dgrdData.RowHeight = 14;
this.dgrdData.RowSubDividerColor = System.Drawing.Color.DarkGray;
this.dgrdData.Size = new System.Drawing.Size(660, 314);
this.dgrdData.TabIndex = 19;
this.dgrdData.Text = "c1TrueDBGrid1";
this.dgrdData.AfterColUpdate += new C1.Win.C1TrueDBGrid.ColEventHandler(this.dgrdData_AfterColUpdate);
this.dgrdData.PropBag = "<?xml version=\"1.0\"?><Blob><DataCols><C1DataColumn Level=\"0\" Caption=\"PO No.\" Dat" +
"aField=\"PONo\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" " +
"Caption=\"Cancel\" DataField=\"CancelDelivery\"><ValueItems Presentation=\"CheckBox\" " +
"/><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"PO Line\" DataFiel" +
"d=\"Line\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Capti" +
"on=\"Category\" DataField=\"ITM_CategoryCode\"><ValueItems /><GroupInfo /></C1DataCo" +
"lumn><C1DataColumn Level=\"0\" Caption=\"Part Number\" DataField=\"Code\"><ValueItems " +
"/><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Part Name\" DataFi" +
"eld=\"Description\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=" +
"\"0\" Caption=\"Model\" DataField=\"Revision\"><ValueItems /><GroupInfo /></C1DataColu" +
"mn><C1DataColumn Level=\"0\" Caption=\"Buying UM\" DataField=\"BuyingUM\"><ValueItems " +
"/><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Order Quantity \" " +
"DataField=\"OrderQuantity\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColum" +
"n Level=\"0\" Caption=\"Del. Line\" DataField=\"DeliveryLine\"><ValueItems /><GroupInf" +
"o /></C1DataColumn><C1DataColumn Level=\"0\" Caption=\"Schedule Date\" DataField=\"Sc" +
"heduleDate\"><ValueItems /><GroupInfo /></C1DataColumn><C1DataColumn Level=\"0\" Ca" +
"ption=\"Delivery Quantity\" DataField=\"DeliveryQuantity\"><ValueItems /><GroupInfo " +
"/></C1DataColumn></DataCols><Styles type=\"C1.Win.C1TrueDBGrid.Design.ContextWrap" +
"per\"><Data>HighlightRow{ForeColor:HighlightText;BackColor:Highlight;}Inactive{Fo" +
"reColor:InactiveCaptionText;BackColor:InactiveCaption;}Style78{}Style79{}Style85" +
"{}Editor{}Style72{}Style73{}Style70{AlignHorz:Center;}Style71{AlignHorz:Near;}St" +
"yle76{AlignHorz:Center;}Style77{AlignHorz:Near;}Style74{}Style75{}Style84{}Style" +
"87{}Style86{}Style81{}Style80{}Style83{AlignHorz:Far;}Style82{AlignHorz:Center;}" +
"FilterBar{}Heading{Wrap:True;AlignVert:Center;Border:Raised,,1, 1, 1, 1;ForeColo" +
"r:ControlText;BackColor:Control;}Style18{}Style19{}Style14{}Style15{}Style16{Ali" +
"gnHorz:Center;}Style17{AlignHorz:Near;}Style10{AlignHorz:Near;}Style11{}Style12{" +
"}Style13{}Selected{ForeColor:HighlightText;BackColor:Highlight;}Style29{AlignHor" +
"z:Center;}Style28{AlignHorz:Center;}Style27{}Style25{}Style22{AlignHorz:Center;}" +
"Style9{}Style8{}Style24{}Style26{}Style5{}Style4{}Style7{}Style6{}Style1{}Style2" +
"3{AlignHorz:Far;}Style3{}Style2{}Style21{}Style20{}OddRow{}Style38{}Style39{}Sty" +
"le36{}Style37{}Style34{AlignHorz:Center;}Style35{AlignHorz:Center;}Style32{}Styl" +
"e33{}Style30{}Style49{}Style48{}Style31{}Normal{}Style41{AlignHorz:Near;}Style40" +
"{AlignHorz:Center;}Style43{}Style42{}Style45{}Style44{}Style47{AlignHorz:Far;}St" +
"yle46{AlignHorz:Center;}EvenRow{BackColor:Aqua;}Style59{AlignHorz:Near;}Style58{" +
"AlignHorz:Center;}RecordSelector{AlignImage:Center;}Style51{}Style50{}Footer{}St" +
"yle52{AlignHorz:Center;}Style53{AlignHorz:Far;}Style54{}Style55{}Style56{}Style5" +
"7{}Caption{AlignHorz:Center;}Style69{}Style68{}Style63{}Style62{}Style61{}Style6" +
"0{}Style67{}Style66{}Style65{AlignHorz:Near;}Style64{AlignHorz:Center;}Group{Bac" +
"kColor:ControlDark;Border:None,,0, 0, 0, 0;AlignVert:Center;}</Data></Styles><Sp" +
"lits><C1.Win.C1TrueDBGrid.MergeView Name=\"\" CaptionHeight=\"17\" ColumnCaptionHeig" +
"ht=\"17\" ColumnFooterHeight=\"17\" MarqueeStyle=\"DottedCellBorder\" RecordSelectorWi" +
"dth=\"17\" DefRecSelWidth=\"17\" VerticalScrollGroup=\"1\" HorizontalScrollGroup=\"1\"><" +
"ClientRect>0, 0, 656, 310</ClientRect><BorderSide>0</BorderSide><CaptionStyle pa" +
"rent=\"Style2\" me=\"Style10\" /><EditorStyle parent=\"Editor\" me=\"Style5\" /><EvenRow" +
"Style parent=\"EvenRow\" me=\"Style8\" /><FilterBarStyle parent=\"FilterBar\" me=\"Styl" +
"e13\" /><FooterStyle parent=\"Footer\" me=\"Style3\" /><GroupStyle parent=\"Group\" me=" +
"\"Style12\" /><HeadingStyle parent=\"Heading\" me=\"Style2\" /><HighLightRowStyle pare" +
"nt=\"HighlightRow\" me=\"Style7\" /><InactiveStyle parent=\"Inactive\" me=\"Style4\" /><" +
"OddRowStyle parent=\"OddRow\" me=\"Style9\" /><RecordSelectorStyle parent=\"RecordSel" +
"ector\" me=\"Style11\" /><SelectedStyle parent=\"Selected\" me=\"Style6\" /><Style pare" +
"nt=\"Normal\" me=\"Style1\" /><internalCols><C1DisplayColumn><HeadingStyle parent=\"S" +
"tyle2\" me=\"Style16\" /><Style parent=\"Style1\" me=\"Style17\" /><FooterStyle parent=" +
"\"Style3\" me=\"Style18\" /><EditorStyle parent=\"Style5\" me=\"Style19\" /><GroupHeader" +
"Style parent=\"Style1\" me=\"Style21\" /><GroupFooterStyle parent=\"Style1\" me=\"Style" +
"20\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Widt" +
"h>121</Width><Height>15</Height><DCIdx>0</DCIdx></C1DisplayColumn><C1DisplayColu" +
"mn><HeadingStyle parent=\"Style2\" me=\"Style46\" /><Style parent=\"Style1\" me=\"Style" +
"47\" /><FooterStyle parent=\"Style3\" me=\"Style48\" /><EditorStyle parent=\"Style5\" m" +
"e=\"Style49\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style51\" /><GroupFooterStyle" +
" parent=\"Style1\" me=\"Style50\" /><Visible>True</Visible><ColumnDivider>DarkGray,S" +
"ingle</ColumnDivider><Width>46</Width><Height>15</Height><DCIdx>2</DCIdx></C1Dis" +
"playColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style22\" /><Style " +
"parent=\"Style1\" me=\"Style23\" /><FooterStyle parent=\"Style3\" me=\"Style24\" /><Edit" +
"orStyle parent=\"Style5\" me=\"Style25\" /><GroupHeaderStyle parent=\"Style1\" me=\"Sty" +
"le27\" /><GroupFooterStyle parent=\"Style1\" me=\"Style26\" /><Visible>True</Visible>" +
"<ColumnDivider>DarkGray,Single</ColumnDivider><Width>55</Width><Height>14</Heigh" +
"t><DCIdx>9</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style" +
"2\" me=\"Style40\" /><Style parent=\"Style1\" me=\"Style41\" /><FooterStyle parent=\"Sty" +
"le3\" me=\"Style42\" /><EditorStyle parent=\"Style5\" me=\"Style43\" /><GroupHeaderStyl" +
"e parent=\"Style1\" me=\"Style45\" /><GroupFooterStyle parent=\"Style1\" me=\"Style44\" " +
"/><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>75" +
"</Width><Height>15</Height><DCIdx>3</DCIdx></C1DisplayColumn><C1DisplayColumn><H" +
"eadingStyle parent=\"Style2\" me=\"Style58\" /><Style parent=\"Style1\" me=\"Style59\" /" +
"><FooterStyle parent=\"Style3\" me=\"Style60\" /><EditorStyle parent=\"Style5\" me=\"St" +
"yle61\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style63\" /><GroupFooterStyle pare" +
"nt=\"Style1\" me=\"Style62\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single" +
"</ColumnDivider><Width>145</Width><Height>15</Height><DCIdx>4</DCIdx></C1Display" +
"Column><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style64\" /><Style pare" +
"nt=\"Style1\" me=\"Style65\" /><FooterStyle parent=\"Style3\" me=\"Style66\" /><EditorSt" +
"yle parent=\"Style5\" me=\"Style67\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style69" +
"\" /><GroupFooterStyle parent=\"Style1\" me=\"Style68\" /><Visible>True</Visible><Col" +
"umnDivider>DarkGray,Single</ColumnDivider><Width>150</Width><Height>15</Height><" +
"DCIdx>5</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" " +
"me=\"Style70\" /><Style parent=\"Style1\" me=\"Style71\" /><FooterStyle parent=\"Style3" +
"\" me=\"Style72\" /><EditorStyle parent=\"Style5\" me=\"Style73\" /><GroupHeaderStyle p" +
"arent=\"Style1\" me=\"Style75\" /><GroupFooterStyle parent=\"Style1\" me=\"Style74\" /><" +
"Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Width>79</W" +
"idth><Height>15</Height><DCIdx>6</DCIdx></C1DisplayColumn><C1DisplayColumn><Head" +
"ingStyle parent=\"Style2\" me=\"Style76\" /><Style parent=\"Style1\" me=\"Style77\" /><F" +
"ooterStyle parent=\"Style3\" me=\"Style78\" /><EditorStyle parent=\"Style5\" me=\"Style" +
"79\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style81\" /><GroupFooterStyle parent=" +
"\"Style1\" me=\"Style80\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</C" +
"olumnDivider><Width>61</Width><Height>15</Height><DCIdx>7</DCIdx></C1DisplayColu" +
"mn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style28\" /><Style parent=\"" +
"Style1\" me=\"Style29\" /><FooterStyle parent=\"Style3\" me=\"Style30\" /><EditorStyle " +
"parent=\"Style5\" me=\"Style31\" /><GroupHeaderStyle parent=\"Style1\" me=\"Style33\" />" +
"<GroupFooterStyle parent=\"Style1\" me=\"Style32\" /><Visible>True</Visible><ColumnD" +
"ivider>DarkGray,Single</ColumnDivider><Height>14</Height><DCIdx>10</DCIdx></C1Di" +
"splayColumn><C1DisplayColumn><HeadingStyle parent=\"Style2\" me=\"Style82\" /><Style" +
" parent=\"Style1\" me=\"Style83\" /><FooterStyle parent=\"Style3\" me=\"Style84\" /><Edi" +
"torStyle parent=\"Style5\" me=\"Style85\" /><GroupHeaderStyle parent=\"Style1\" me=\"St" +
"yle87\" /><GroupFooterStyle parent=\"Style1\" me=\"Style86\" /><Visible>True</Visible" +
"><ColumnDivider>DarkGray,Single</ColumnDivider><Width>86</Width><Height>15</Heig" +
"ht><DCIdx>8</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle parent=\"Styl" +
"e2\" me=\"Style52\" /><Style parent=\"Style1\" me=\"Style53\" /><FooterStyle parent=\"St" +
"yle3\" me=\"Style54\" /><EditorStyle parent=\"Style5\" me=\"Style55\" /><GroupHeaderSty" +
"le parent=\"Style1\" me=\"Style57\" /><GroupFooterStyle parent=\"Style1\" me=\"Style56\"" +
" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider><Height>" +
"14</Height><DCIdx>11</DCIdx></C1DisplayColumn><C1DisplayColumn><HeadingStyle par" +
"ent=\"Style2\" me=\"Style34\" /><Style parent=\"Style1\" me=\"Style35\" /><FooterStyle p" +
"arent=\"Style3\" me=\"Style36\" /><EditorStyle parent=\"Style5\" me=\"Style37\" /><Group" +
"HeaderStyle parent=\"Style1\" me=\"Style39\" /><GroupFooterStyle parent=\"Style1\" me=" +
"\"Style38\" /><Visible>True</Visible><ColumnDivider>DarkGray,Single</ColumnDivider" +
"><Width>57</Width><Height>15</Height><DCIdx>1</DCIdx></C1DisplayColumn></interna" +
"lCols></C1.Win.C1TrueDBGrid.MergeView></Splits><NamedStyles><Style parent=\"\" me=" +
"\"Normal\" /><Style parent=\"Normal\" me=\"Heading\" /><Style parent=\"Heading\" me=\"Foo" +
"ter\" /><Style parent=\"Heading\" me=\"Caption\" /><Style parent=\"Heading\" me=\"Inacti" +
"ve\" /><Style parent=\"Normal\" me=\"Selected\" /><Style parent=\"Normal\" me=\"Editor\" " +
"/><Style parent=\"Normal\" me=\"HighlightRow\" /><Style parent=\"Normal\" me=\"EvenRow\"" +
" /><Style parent=\"Normal\" me=\"OddRow\" /><Style parent=\"Heading\" me=\"RecordSelect" +
"or\" /><Style parent=\"Normal\" me=\"FilterBar\" /><Style parent=\"Caption\" me=\"Group\"" +
" /></NamedStyles><vertSplits>1</vertSplits><horzSplits>1</horzSplits><Layout>Mod" +
"ified</Layout><DefaultRecSelWidth>17</DefaultRecSelWidth><ClientArea>0, 0, 656, " +
"310</ClientArea><PrintPageHeaderStyle parent=\"\" me=\"Style14\" /><PrintPageFooterS" +
"tyle parent=\"\" me=\"Style15\" /></Blob>";
//
// chkSelectAll
//
this.chkSelectAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.chkSelectAll.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.chkSelectAll.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.chkSelectAll.Location = new System.Drawing.Point(84, 442);
this.chkSelectAll.Name = "chkSelectAll";
this.chkSelectAll.Size = new System.Drawing.Size(70, 22);
this.chkSelectAll.TabIndex = 20;
this.chkSelectAll.Text = "Se&lect All";
this.chkSelectAll.Enter += new System.EventHandler(this.chkSelectAll_Enter);
this.chkSelectAll.Leave += new System.EventHandler(this.chkSelectAll_Leave);
this.chkSelectAll.CheckedChanged += new System.EventHandler(this.chkSelectAll_CheckedChanged);
//
// DeliveryApproval
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(670, 468);
this.Controls.Add(this.btnShowDetail);
this.Controls.Add(this.btnSearch);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnApprove);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.dgrdData);
this.Controls.Add(this.txtPartName);
this.Controls.Add(this.txtModel);
this.Controls.Add(this.txtPartNumber);
this.Controls.Add(this.txtCategory);
this.Controls.Add(this.txtPONo);
this.Controls.Add(this.chkSelectAll);
this.Controls.Add(this.btnPartName);
this.Controls.Add(this.lblPartName);
this.Controls.Add(this.btnPartNumber);
this.Controls.Add(this.lblPartNumber);
this.Controls.Add(this.lblModel);
this.Controls.Add(this.lblCategory);
this.Controls.Add(this.btnCategory);
this.Controls.Add(this.dtmToDate);
this.Controls.Add(this.dtmFromDate);
this.Controls.Add(this.lblToStartDate);
this.Controls.Add(this.lblFromStartDate);
this.Controls.Add(this.btnPONo);
this.Controls.Add(this.lblPONo);
this.Name = "DeliveryApproval";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Approve/Cancel Delivery Schedule";
this.Load += new System.EventHandler(this.DeliveryApproval_Load);
((System.ComponentModel.ISupportInitialize)(this.dtmToDate)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dtmFromDate)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dgrdData)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void DeliveryApproval_Load(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".DeliveryApproval_Load()";
try
{
//Set authorization for user
Security objSecurity = new Security();
this.Name = THIS;
if(objSecurity.SetRightForUserOnForm(this, SystemProperty.UserName) == 0)
{
this.Close();
// You don't have the right to view this item
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
return;
}
dtbGridLayOut = FormControlComponents.StoreGridLayout(dgrdData);
txtPONo.Tag = string.Empty;
txtCategory.Tag = string.Empty;
txtPartNumber.Tag = string.Empty;
dtmFromDate.FormatType = FormatTypeEnum.CustomFormat;
dtmFromDate.CustomFormat = Constants.DATETIME_FORMAT_HOUR;
dtmToDate.FormatType = FormatTypeEnum.CustomFormat;
dtmToDate.CustomFormat = Constants.DATETIME_FORMAT_HOUR;
}
catch (PCSException ex)
{
// Displays the error message if throwed from PCSException.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// Displays the error message if throwed from system.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
try
{
// Log error message into log file.
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
// Show message if logger has an error.
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
}
private void txtPONo_Validating(object sender, CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".txtPONo_Validating()";
try
{
if (!txtPONo.Modified) return;
if (txtPONo.Text.Trim() == string.Empty)
{
txtPONo.Tag = string.Empty;
return;
}
DataRowView drvResult = FormControlComponents.OpenSearchForm(PO_PurchaseOrderMasterTable.TABLE_NAME, PO_PurchaseOrderMasterTable.CODE_FLD, txtPONo.Text.Trim(), null, false);
if (drvResult != null)
{
txtPONo.Text = drvResult[PO_PurchaseOrderMasterTable.CODE_FLD].ToString();
txtPONo.Tag = drvResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD];
}
else
e.Cancel = true;
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void txtPONo_KeyDown(object sender, KeyEventArgs e)
{
const string METHOD_NAME = THIS + ".txtPONo_KeyDown()";
try
{
if (e.KeyCode == Keys.F4)
btnPONo_Click(null, null);
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void btnPONo_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnPONo_Click()";
try
{
DataRowView drvResult = FormControlComponents.OpenSearchForm(PO_PurchaseOrderMasterTable.TABLE_NAME, PO_PurchaseOrderMasterTable.CODE_FLD, txtPONo.Text.Trim(), null, true);
if (drvResult != null)
{
txtPONo.Text = drvResult[PO_PurchaseOrderMasterTable.CODE_FLD].ToString();
txtPONo.Tag = drvResult[PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD];
}
else
txtPONo.Focus();
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void txtCategory_Validating(object sender, CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".txtCategory_Validating()";
try
{
if (!txtCategory.Modified) return;
if (txtCategory.Text.Trim() == string.Empty)
{
txtCategory.Tag = string.Empty;
txtPartNumber.Text = string.Empty;
txtPartNumber.Tag = string.Empty;
txtPartName.Text = string.Empty;
return;
}
DataRowView drvResult = FormControlComponents.OpenSearchForm(ITM_CategoryTable.TABLE_NAME, ITM_CategoryTable.CODE_FLD, txtCategory.Text.Trim(), null, false);
if (drvResult != null)
{
txtCategory.Text = drvResult[ITM_CategoryTable.CODE_FLD].ToString();
txtCategory.Tag = drvResult[ITM_CategoryTable.CATEGORYID_FLD];
txtPartNumber.Text = string.Empty;
txtPartNumber.Tag = string.Empty;
txtPartName.Text = string.Empty;
}
else
e.Cancel = true;
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void txtCategory_KeyDown(object sender, KeyEventArgs e)
{
const string METHOD_NAME = THIS + ".txtCategory_KeyDown()";
try
{
if (e.KeyCode == Keys.F4)
btnCategory_Click(null, null);
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void btnCategory_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnCategory_Click()";
try
{
DataRowView drvResult = FormControlComponents.OpenSearchForm(ITM_CategoryTable.TABLE_NAME, ITM_CategoryTable.CODE_FLD, txtCategory.Text.Trim(), null, true);
if (drvResult != null)
{
txtCategory.Text = drvResult[ITM_CategoryTable.CODE_FLD].ToString();
txtCategory.Tag = drvResult[ITM_CategoryTable.CATEGORYID_FLD];
txtPartNumber.Text = string.Empty;
txtPartNumber.Tag = string.Empty;
txtPartName.Text = string.Empty;
}
else
txtPONo.Focus();
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void txtPartNumber_Validating(object sender, CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".txtPONo_Validating()";
try
{
if (!txtPartNumber.Modified) return;
if (txtPartNumber.Text.Trim() == string.Empty)
{
txtPartNumber.Tag = string.Empty;
txtPartName.Text = string.Empty;
return;
}
string strFilter = string.Empty;
if(txtCategory.Tag != null && txtCategory.Tag.ToString() != string.Empty)
strFilter = ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.CATEGORYID_FLD + " = " + txtCategory.Tag.ToString();
DataTable dtbData = FormControlComponents.OpenSearchFormForMultiSelectedRow(ITM_ProductTable.TABLE_NAME, ITM_ProductTable.CODE_FLD, txtPartNumber.Text, strFilter, false);
if (dtbData != null && dtbData.Rows.Count > 0)
{
StringBuilder sbID = new StringBuilder();
foreach (DataRow drowData in dtbData.Rows)
sbID.Append(drowData[ITM_ProductTable.PRODUCTID_FLD].ToString()).Append(",");
txtPartNumber.Text = (dtbData.Rows.Count > 1) ? "Multi Selection" : dtbData.Rows[0][ITM_ProductTable.CODE_FLD].ToString();
txtPartNumber.Tag = sbID.ToString(0, sbID.Length - 1);
txtPartName.Text = (dtbData.Rows.Count > 1) ? "Multi Selection" : dtbData.Rows[0][ITM_ProductTable.DESCRIPTION_FLD].ToString();
}
else
e.Cancel = true;
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void txtPartNumber_KeyDown(object sender, KeyEventArgs e)
{
const string METHOD_NAME = THIS + ".txtPartNumber_KeyDown()";
try
{
if (e.KeyCode == Keys.F4)
btnPartNumber_Click(null, null);
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void btnPartNumber_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnPartNumber_Click()";
try
{
string strFilter = string.Empty;
if(txtCategory.Tag != null && txtCategory.Tag.ToString() != string.Empty)
strFilter = ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.CATEGORYID_FLD + "=" + txtCategory.Tag.ToString();
DataTable dtbData = FormControlComponents.OpenSearchFormForMultiSelectedRow(ITM_ProductTable.TABLE_NAME, ITM_ProductTable.CODE_FLD, txtPartNumber.Text, strFilter, true);
if (dtbData != null && dtbData.Rows.Count > 0)
{
StringBuilder sbID = new StringBuilder();
foreach (DataRow drowData in dtbData.Rows)
sbID.Append(drowData[ITM_ProductTable.PRODUCTID_FLD].ToString()).Append(",");
txtPartNumber.Text = (dtbData.Rows.Count > 1) ? "Multi Selection" : dtbData.Rows[0][ITM_ProductTable.CODE_FLD].ToString();
txtPartNumber.Tag = sbID.ToString(0, sbID.Length - 1);
txtPartName.Text = (dtbData.Rows.Count > 1) ? "Multi Selection" : dtbData.Rows[0][ITM_ProductTable.DESCRIPTION_FLD].ToString();
}
else
txtPartNumber.Focus();
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void txtPartName_Validating(object sender, CancelEventArgs e)
{
const string METHOD_NAME = THIS + ".txtPartName_Validating()";
try
{
if (!txtPartName.Modified) return;
if (txtPartName.Text.Trim() == string.Empty)
{
txtPartNumber.Text = string.Empty;
txtPartNumber.Tag = null;
txtPartName.Text = string.Empty;
return;
}
string strFilter = string.Empty;
if(txtCategory.Tag != null && txtCategory.Tag.ToString() != string.Empty)
strFilter = ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.CATEGORYID_FLD + "=" + txtCategory.Tag.ToString();
DataTable dtbData = FormControlComponents.OpenSearchFormForMultiSelectedRow(ITM_ProductTable.TABLE_NAME, ITM_ProductTable.CODE_FLD, txtPartNumber.Text, strFilter, false);
if (dtbData != null && dtbData.Rows.Count > 0)
{
StringBuilder sbID = new StringBuilder();
foreach (DataRow drowData in dtbData.Rows)
sbID.Append(drowData[ITM_ProductTable.PRODUCTID_FLD].ToString()).Append(",");
txtPartNumber.Text = (dtbData.Rows.Count > 1) ? "Multi Selection" : dtbData.Rows[0][ITM_ProductTable.CODE_FLD].ToString();
txtPartNumber.Tag = sbID.ToString(0, sbID.Length - 1);
txtPartName.Text = (dtbData.Rows.Count > 1) ? "Multi Selection" : dtbData.Rows[0][ITM_ProductTable.DESCRIPTION_FLD].ToString();
}
else
e.Cancel = true;
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void txtPartName_KeyDown(object sender, KeyEventArgs e)
{
const string METHOD_NAME = THIS + ".txtPartName_KeyDown()";
try
{
if (e.KeyCode == Keys.F4)
btnPartName_Click(null, null);
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void btnPartName_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnPartName_Click()";
try
{
string strFilter = string.Empty;
if(txtCategory.Tag != null && txtCategory.Tag.ToString() != string.Empty)
strFilter = ITM_ProductTable.TABLE_NAME + "." + ITM_ProductTable.CATEGORYID_FLD + "=" + txtCategory.Tag.ToString();
DataTable dtbData = FormControlComponents.OpenSearchFormForMultiSelectedRow(ITM_ProductTable.TABLE_NAME, ITM_ProductTable.CODE_FLD, txtPartNumber.Text, strFilter, true);
if (dtbData != null && dtbData.Rows.Count > 0)
{
StringBuilder sbID = new StringBuilder();
foreach (DataRow drowData in dtbData.Rows)
sbID.Append(drowData[ITM_ProductTable.PRODUCTID_FLD].ToString()).Append(",");
txtPartNumber.Text = (dtbData.Rows.Count > 1) ? "Multi Selection" : dtbData.Rows[0][ITM_ProductTable.CODE_FLD].ToString();
txtPartNumber.Tag = sbID.ToString(0, sbID.Length - 1);
txtPartName.Text = (dtbData.Rows.Count > 1) ? "Multi Selection" : dtbData.Rows[0][ITM_ProductTable.DESCRIPTION_FLD].ToString();
}
else
txtPartName.Focus();
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnSearch_Click()";
try
{
Cursor = Cursors.WaitCursor;
DeliveryApprovalBO boDeliveryApprove = new DeliveryApprovalBO();
DateTime dtmStartDate = DateTime.MinValue, dtmEndDate = DateTime.MinValue;
try
{
dtmStartDate = Convert.ToDateTime(dtmFromDate.Value);
}
catch{}
try
{
dtmEndDate = Convert.ToDateTime(dtmToDate.Value);
}
catch{}
int intPOMasterID = 0, intCategoryID = 0;
try
{
intPOMasterID = Convert.ToInt32(txtPONo.Tag);
}
catch{}
try
{
intCategoryID = Convert.ToInt32(txtCategory.Tag);
}
catch{}
dstData = boDeliveryApprove.SearchDeliverySchedule(dtmStartDate, dtmEndDate,
intPOMasterID, intCategoryID, txtPartNumber.Tag.ToString());
dstData.AcceptChanges();
BindDataToGrid();
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
finally
{
Cursor = Cursors.Default;
}
}
private void btnShowDetail_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnShowDetail_Click()";
try
{
if (dgrdData.RowCount > 0)
{
PurchaseOrder frmPurchaseOrder = new PurchaseOrder();
frmPurchaseOrder.Show();
frmPurchaseOrder.LoadMaster((int) dgrdData[dgrdData.Row, PO_PurchaseOrderMasterTable.PURCHASEORDERMASTERID_FLD]);
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void btnApprove_Click(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".btnApprove_Click()";
try
{
if (dstData == null || dstData.Tables.Count == 0 || dstData.Tables[0].Rows.Count == 0)
return;
Cursor = Cursors.WaitCursor;
DeliveryApprovalBO boApproval = new DeliveryApprovalBO();
string strCancelList = string.Empty, strApprovedList = string.Empty;
DataTable dtbModified = dstData.Tables[0].GetChanges(DataRowState.Modified);
foreach (DataRow drowData in dtbModified.Rows)
{
bool blnCancel = Convert.ToBoolean(drowData[PO_DeliveryScheduleTable.CANCELDELIVERY_FLD]);
if (blnCancel)
strCancelList += drowData[PO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD] + ",";
else
strApprovedList += drowData[PO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD] + ",";
}
boApproval.UpdateDelivery(strCancelList, strApprovedList);
btnSearch_Click(null, null);
PCSMessageBox.Show(ErrorCode.MESSAGE_AFTER_SAVE_DATA);
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
finally
{
Cursor = Cursors.Default;
}
}
private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
{
const string METHOD_NAME = THIS + ".chkSelectAll_CheckedChanged()";
try
{
Cursor = Cursors.WaitCursor;
if (blnStateOfCheck)
foreach (DataRow drowData in dstData.Tables[0].Rows)
if (drowData.RowState != DataRowState.Deleted)
drowData[PO_DeliveryScheduleTable.CANCELDELIVERY_FLD] = chkSelectAll.Checked;
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
finally
{
Cursor = Cursors.Default;
}
}
private void BindDataToGrid()
{
dgrdData.DataSource = dstData.Tables[0];
FormControlComponents.RestoreGridLayout(dgrdData, dtbGridLayOut);
foreach (C1DisplayColumn c1Col in dgrdData.Splits[0].DisplayColumns)
c1Col.Locked = true;
dgrdData.Columns[PO_PurchaseOrderDetailTable.ORDERQUANTITY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
dgrdData.Columns[PO_DeliveryScheduleTable.DELIVERYQUANTITY_FLD].NumberFormat = Constants.DECIMAL_NUMBERFORMAT;
dgrdData.Columns[PO_DeliveryScheduleTable.SCHEDULEDATE_FLD].NumberFormat = Constants.DATETIME_FORMAT_HOUR;
dgrdData.Splits[0].DisplayColumns[PO_DeliveryScheduleTable.CANCELDELIVERY_FLD].Locked = false;
}
private void chkSelectAll_Enter(object sender, System.EventArgs e)
{
blnStateOfCheck = true;
}
private void chkSelectAll_Leave(object sender, System.EventArgs e)
{
blnStateOfCheck = false;
}
private void btnClose_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void dgrdData_AfterColUpdate(object sender, ColEventArgs e)
{
const string METHOD_NAME = THIS + ".dgrdData_AfterColUpdate()";
try
{
if (e.Column.DataColumn.DataField == PO_DeliveryScheduleTable.CANCELDELIVERY_FLD)
{
for (int i =0; i <dgrdData.RowCount; i++)
{
if (!Convert.ToBoolean(dgrdData[i, PO_DeliveryScheduleTable.CANCELDELIVERY_FLD]))
{
chkSelectAll.Checked = false;
return;
}
}
chkSelectAll.Checked = true;
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This Class defines behaviors specific to a writing system.
// A writing system is the collection of scripts and
// orthographic rules required to represent a language as text.
//
//
////////////////////////////////////////////////////////////////////////////
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
namespace System.Globalization
{
public partial class TextInfo : ICloneable, IDeserializationCallback
{
private enum Tristate : byte
{
NotInitialized,
True,
False,
}
private string _listSeparator;
private bool _isReadOnly = false;
/* _cultureName is the name of the creating culture.
_cultureData is the data that backs this class.
_textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
In the desktop, when we call the sorting dll, it doesn't
know how to resolve custom locle names to sort ids so we have to have already resolved this.
*/
private readonly string _cultureName; // Name of the culture that created this text info
private readonly CultureData _cultureData; // Data record for the culture that made us, not for this textinfo
private readonly string _textInfoName; // Name of the text info we're using (ie: _cultureData.STEXTINFO)
private Tristate _isAsciiCasingSameAsInvariant = Tristate.NotInitialized;
// _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant
private readonly bool _invariantMode = GlobalizationMode.Invariant;
// Invariant text info
internal static TextInfo Invariant
{
get
{
if (s_Invariant == null)
s_Invariant = new TextInfo(CultureData.Invariant);
return s_Invariant;
}
}
internal volatile static TextInfo s_Invariant;
//////////////////////////////////////////////////////////////////////////
////
//// TextInfo Constructors
////
//// Implements CultureInfo.TextInfo.
////
//////////////////////////////////////////////////////////////////////////
internal TextInfo(CultureData cultureData)
{
// This is our primary data source, we don't need most of the rest of this
_cultureData = cultureData;
_cultureName = _cultureData.CultureName;
_textInfoName = _cultureData.STEXTINFO;
FinishInitialization();
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
throw new PlatformNotSupportedException();
}
public virtual int ANSICodePage => _cultureData.IDEFAULTANSICODEPAGE;
public virtual int OEMCodePage => _cultureData.IDEFAULTOEMCODEPAGE;
public virtual int MacCodePage => _cultureData.IDEFAULTMACCODEPAGE;
public virtual int EBCDICCodePage => _cultureData.IDEFAULTEBCDICCODEPAGE;
// Just use the LCID from our text info name
public int LCID => CultureInfo.GetCultureInfo(_textInfoName).LCID;
public string CultureName => _textInfoName;
public bool IsReadOnly => _isReadOnly;
//////////////////////////////////////////////////////////////////////////
////
//// Clone
////
//// Is the implementation of ICloneable.
////
//////////////////////////////////////////////////////////////////////////
public virtual object Clone()
{
object o = MemberwiseClone();
((TextInfo)o).SetReadOnlyState(false);
return o;
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
public static TextInfo ReadOnly(TextInfo textInfo)
{
if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); }
if (textInfo.IsReadOnly) { return textInfo; }
TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone());
clonedTextInfo.SetReadOnlyState(true);
return clonedTextInfo;
}
private void VerifyWritable()
{
if (_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
_isReadOnly = readOnly;
}
////////////////////////////////////////////////////////////////////////
//
// ListSeparator
//
// Returns the string used to separate items in a list.
//
////////////////////////////////////////////////////////////////////////
public virtual string ListSeparator
{
get
{
if (_listSeparator == null)
{
_listSeparator = _cultureData.SLIST;
}
return _listSeparator;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String);
}
VerifyWritable();
_listSeparator = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// ToLower
//
// Converts the character or string to lower case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToLower(char c)
{
if (_invariantMode || (IsAscii(c) && IsAsciiCasingSameAsInvariant))
{
return ToLowerAsciiInvariant(c);
}
return ChangeCase(c, toUpper: false);
}
public unsafe virtual string ToLower(string str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
if (_invariantMode)
{
return ToLowerAsciiInvariant(str);
}
return ChangeCase(str, toUpper: false);
}
private unsafe char ChangeCase(char c, bool toUpper)
{
Debug.Assert(!_invariantMode);
char dst = default;
ChangeCase(&c, 1, &dst, 1, toUpper);
return dst;
}
private unsafe string ChangeCase(string source, bool toUpper)
{
Debug.Assert(!_invariantMode);
Debug.Assert(source != null);
// If the string is empty, we're done.
if (source.Length == 0)
{
return string.Empty;
}
int sourcePos = 0;
string result = null;
// If this culture's casing for ASCII is the same as invariant, try to take
// a fast path that'll work in managed code and ASCII rather than calling out
// to the OS for culture-aware casing.
if (IsAsciiCasingSameAsInvariant)
{
if (toUpper)
{
// Loop through each character.
for (sourcePos = 0; sourcePos < source.Length; sourcePos++)
{
// If the character is lower-case, we're going to need to allocate a string.
char c = source[sourcePos];
if ((uint)(c - 'a') <= 'z' - 'a')
{
// Allocate the result string.
result = string.FastAllocateString(source.Length);
fixed (char* pResult = result)
{
// Store all of characters examined thus far.
if (sourcePos > 0)
{
source.AsSpan(0, sourcePos).CopyTo(new Span<char>(pResult, sourcePos));
}
// And store the current character, upper-cased.
char* d = pResult + sourcePos;
*d++ = (char)(c & ~0x20);
sourcePos++;
// Then continue looping through the remainder of the characters. If we hit
// a non-ASCII character, bail to fall back to culture-aware casing.
for (; sourcePos < source.Length; sourcePos++)
{
c = source[sourcePos];
if ((uint)(c - 'a') <= 'z' - 'a')
{
*d++ = (char)(c & ~0x20);
}
else if (!IsAscii(c))
{
break;
}
else
{
*d++ = c;
}
}
}
break;
}
else if (!IsAscii(c))
{
// The character isn't ASCII; bail to fall back to a culture-aware casing.
break;
}
}
}
else // toUpper == false
{
// Loop through each character.
for (sourcePos = 0; sourcePos < source.Length; sourcePos++)
{
// If the character is upper-case, we're going to need to allocate a string.
char c = source[sourcePos];
if ((uint)(c - 'A') <= 'Z' - 'A')
{
// Allocate the result string.
result = string.FastAllocateString(source.Length);
fixed (char* pResult = result)
{
// Store all of characters examined thus far.
if (sourcePos > 0)
{
source.AsSpan(0, sourcePos).CopyTo(new Span<char>(pResult, sourcePos));
}
// And store the current character, upper-cased.
char* d = pResult + sourcePos;
*d++ = (char)(c | 0x20);
sourcePos++;
// Then continue looping through the remainder of the characters. If we hit
// a non-ASCII character, bail to fall back to culture-aware casing.
for (; sourcePos < source.Length; sourcePos++)
{
c = source[sourcePos];
if ((uint)(c - 'A') <= 'Z' - 'A')
{
*d++ = (char)(c | 0x20);
}
else if (!IsAscii(c))
{
break;
}
else
{
*d++ = c;
}
}
}
break;
}
else if (!IsAscii(c))
{
// The character isn't ASCII; bail to fall back to a culture-aware casing.
break;
}
}
}
// If we successfully iterated through all of the characters, we didn't need to fall back
// to culture-aware casing. In that case, if we allocated a result string, use it, otherwise
// just return the original string, as no modifications were necessary.
if (sourcePos == source.Length)
{
return result ?? source;
}
}
// Falling back to culture-aware casing. Make sure we have a result string to write into.
// If we need to allocate the result string, we'll also need to copy over to it any
// characters already examined.
if (result == null)
{
result = string.FastAllocateString(source.Length);
if (sourcePos > 0)
{
fixed (char* pResult = result)
{
source.AsSpan(0, sourcePos).CopyTo(new Span<char>(pResult, sourcePos));
}
}
}
// Do the casing operation on everything after what we already processed.
fixed (char* pSource = source)
{
fixed (char* pResult = result)
{
ChangeCase(pSource + sourcePos, source.Length - sourcePos, pResult + sourcePos, result.Length - sourcePos, toUpper);
}
}
return result;
}
internal unsafe void ChangeCase(ReadOnlySpan<char> source, Span<char> destination, bool toUpper)
{
Debug.Assert(!_invariantMode);
Debug.Assert(destination.Length >= source.Length);
if (source.IsEmpty)
{
return;
}
fixed (char* pSource = &MemoryMarshal.GetReference(source))
fixed (char* pResult = &MemoryMarshal.GetReference(destination))
{
if (IsAsciiCasingSameAsInvariant)
{
int length = 0;
char* a = pSource, b = pResult;
if (toUpper)
{
while (length < source.Length && *a < 0x80)
{
*b++ = ToUpperAsciiInvariant(*a++);
length++;
}
}
else
{
while (length < source.Length && *a < 0x80)
{
*b++ = ToLowerAsciiInvariant(*a++);
length++;
}
}
if (length != source.Length)
{
ChangeCase(a, source.Length - length, b, destination.Length - length, toUpper);
}
}
else
{
ChangeCase(pSource, source.Length, pResult, destination.Length, toUpper);
}
}
}
private unsafe string ToLowerAsciiInvariant(string s)
{
if (s.Length == 0)
{
return string.Empty;
}
fixed (char* pSource = s)
{
int i = 0;
while (i < s.Length)
{
if ((uint)(pSource[i] - 'A') <= (uint)('Z' - 'A'))
{
break;
}
i++;
}
if (i >= s.Length)
{
return s;
}
string result = string.FastAllocateString(s.Length);
fixed (char* pResult = result)
{
for (int j = 0; j < i; j++)
{
pResult[j] = pSource[j];
}
pResult[i] = (char)(pSource[i] | 0x20);
i++;
while (i < s.Length)
{
pResult[i] = ToLowerAsciiInvariant(pSource[i]);
i++;
}
}
return result;
}
}
internal void ToLowerAsciiInvariant(ReadOnlySpan<char> source, Span<char> destination)
{
Debug.Assert(destination.Length >= source.Length);
for (int i = 0; i < source.Length; i++)
{
destination[i] = ToLowerAsciiInvariant(source[i]);
}
}
private unsafe string ToUpperAsciiInvariant(string s)
{
if (s.Length == 0)
{
return string.Empty;
}
fixed (char* pSource = s)
{
int i = 0;
while (i < s.Length)
{
if ((uint)(pSource[i] - 'a') <= (uint)('z' - 'a'))
{
break;
}
i++;
}
if (i >= s.Length)
{
return s;
}
string result = string.FastAllocateString(s.Length);
fixed (char* pResult = result)
{
for (int j = 0; j < i; j++)
{
pResult[j] = pSource[j];
}
pResult[i] = (char)(pSource[i] & ~0x20);
i++;
while (i < s.Length)
{
pResult[i] = ToUpperAsciiInvariant(pSource[i]);
i++;
}
}
return result;
}
}
internal void ToUpperAsciiInvariant(ReadOnlySpan<char> source, Span<char> destination)
{
Debug.Assert(destination.Length >= source.Length);
for (int i = 0; i < source.Length; i++)
{
destination[i] = ToUpperAsciiInvariant(source[i]);
}
}
private static char ToLowerAsciiInvariant(char c)
{
if ((uint)(c - 'A') <= (uint)('Z' - 'A'))
{
c = (char)(c | 0x20);
}
return c;
}
////////////////////////////////////////////////////////////////////////
//
// ToUpper
//
// Converts the character or string to upper case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToUpper(char c)
{
if (_invariantMode || (IsAscii(c) && IsAsciiCasingSameAsInvariant))
{
return ToUpperAsciiInvariant(c);
}
return ChangeCase(c, toUpper: true);
}
public unsafe virtual string ToUpper(string str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
if (_invariantMode)
{
return ToUpperAsciiInvariant(str);
}
return ChangeCase(str, toUpper: true);
}
internal static char ToUpperAsciiInvariant(char c)
{
if ((uint)(c - 'a') <= (uint)('z' - 'a'))
{
c = (char)(c & ~0x20);
}
return c;
}
private static bool IsAscii(char c)
{
return c < 0x80;
}
private bool IsAsciiCasingSameAsInvariant
{
get
{
if (_isAsciiCasingSameAsInvariant == Tristate.NotInitialized)
{
_isAsciiCasingSameAsInvariant = CultureInfo.GetCultureInfo(_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
CompareOptions.IgnoreCase) == 0 ? Tristate.True : Tristate.False;
}
return _isAsciiCasingSameAsInvariant == Tristate.True;
}
}
// IsRightToLeft
//
// Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
//
public bool IsRightToLeft => _cultureData.IsRightToLeft;
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CultureInfo as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object obj)
{
TextInfo that = obj as TextInfo;
if (that != null)
{
return CultureName.Equals(that.CultureName);
}
return false;
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for CultureInfo A
// and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return CultureName.GetHashCode();
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// TextInfo.
//
////////////////////////////////////////////////////////////////////////
public override string ToString()
{
return "TextInfo - " + _cultureData.CultureName;
}
//
// Titlecasing:
// -----------
// Titlecasing refers to a casing practice wherein the first letter of a word is an uppercase letter
// and the rest of the letters are lowercase. The choice of which words to titlecase in headings
// and titles is dependent on language and local conventions. For example, "The Merry Wives of Windor"
// is the appropriate titlecasing of that play's name in English, with the word "of" not titlecased.
// In German, however, the title is "Die lustigen Weiber von Windsor," and both "lustigen" and "von"
// are not titlecased. In French even fewer words are titlecased: "Les joyeuses commeres de Windsor."
//
// Moreover, the determination of what actually constitutes a word is language dependent, and this can
// influence which letter or letters of a "word" are uppercased when titlecasing strings. For example
// "l'arbre" is considered two words in French, whereas "can't" is considered one word in English.
//
public unsafe string ToTitleCase(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
if (str.Length == 0)
{
return str;
}
StringBuilder result = new StringBuilder();
string lowercaseData = null;
// Store if the current culture is Dutch (special case)
bool isDutchCulture = CultureName.StartsWith("nl-", StringComparison.OrdinalIgnoreCase);
for (int i = 0; i < str.Length; i++)
{
UnicodeCategory charType;
int charLen;
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (char.CheckLetter(charType))
{
// Special case to check for Dutch specific titlecasing with "IJ" characters
// at the beginning of a word
if (isDutchCulture && i < str.Length - 1 && (str[i] == 'i' || str[i] == 'I') && (str[i+1] == 'j' || str[i+1] == 'J'))
{
result.Append("IJ");
i += 2;
}
else
{
// Do the titlecasing for the first character of the word.
i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1;
}
//
// Convert the characters until the end of the this word
// to lowercase.
//
int lowercaseStart = i;
//
// Use hasLowerCase flag to prevent from lowercasing acronyms (like "URT", "USA", etc)
// This is in line with Word 2000 behavior of titlecasing.
//
bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter);
// Use a loop to find all of the other letters following this letter.
while (i < str.Length)
{
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
if (IsLetterCategory(charType))
{
if (charType == UnicodeCategory.LowercaseLetter)
{
hasLowerCase = true;
}
i += charLen;
}
else if (str[i] == '\'')
{
i++;
if (hasLowerCase)
{
if (lowercaseData == null)
{
lowercaseData = ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, i - lowercaseStart);
}
else
{
result.Append(str, lowercaseStart, i - lowercaseStart);
}
lowercaseStart = i;
hasLowerCase = true;
}
else if (!IsWordSeparator(charType))
{
// This category is considered to be part of the word.
// This is any category that is marked as false in wordSeprator array.
i+= charLen;
}
else
{
// A word separator. Break out of the loop.
break;
}
}
int count = i - lowercaseStart;
if (count > 0)
{
if (hasLowerCase)
{
if (lowercaseData == null)
{
lowercaseData = ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, count);
}
else
{
result.Append(str, lowercaseStart, count);
}
}
if (i < str.Length)
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
else
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
return result.ToString();
}
private static int AddNonLetter(ref StringBuilder result, ref string input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
if (charLen == 2)
{
// Surrogate pair
result.Append(input[inputIndex++]);
result.Append(input[inputIndex]);
}
else
{
result.Append(input[inputIndex]);
}
return inputIndex;
}
private int AddTitlecaseLetter(ref StringBuilder result, ref string input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
// for surrogate pairs do a simple ToUpper operation on the substring
if (charLen == 2)
{
// Surrogate pair
result.Append(ToUpper(input.Substring(inputIndex, charLen)));
inputIndex++;
}
else
{
switch (input[inputIndex])
{
//
// For AppCompat, the Titlecase Case Mapping data from NDP 2.0 is used below.
case (char) 0x01C4: // DZ with Caron -> Dz with Caron
case (char) 0x01C5: // Dz with Caron -> Dz with Caron
case (char) 0x01C6: // dz with Caron -> Dz with Caron
result.Append((char) 0x01C5);
break;
case (char) 0x01C7: // LJ -> Lj
case (char) 0x01C8: // Lj -> Lj
case (char) 0x01C9: // lj -> Lj
result.Append((char) 0x01C8);
break;
case (char) 0x01CA: // NJ -> Nj
case (char) 0x01CB: // Nj -> Nj
case (char) 0x01CC: // nj -> Nj
result.Append((char) 0x01CB);
break;
case (char) 0x01F1: // DZ -> Dz
case (char) 0x01F2: // Dz -> Dz
case (char) 0x01F3: // dz -> Dz
result.Append((char) 0x01F2);
break;
default:
result.Append(ToUpper(input[inputIndex]));
break;
}
}
return inputIndex;
}
//
// Used in ToTitleCase():
// When we find a starting letter, the following array decides if a category should be
// considered as word seprator or not.
//
private const int c_wordSeparatorMask =
/* false */ (0 << 0) | // UppercaseLetter = 0,
/* false */ (0 << 1) | // LowercaseLetter = 1,
/* false */ (0 << 2) | // TitlecaseLetter = 2,
/* false */ (0 << 3) | // ModifierLetter = 3,
/* false */ (0 << 4) | // OtherLetter = 4,
/* false */ (0 << 5) | // NonSpacingMark = 5,
/* false */ (0 << 6) | // SpacingCombiningMark = 6,
/* false */ (0 << 7) | // EnclosingMark = 7,
/* false */ (0 << 8) | // DecimalDigitNumber = 8,
/* false */ (0 << 9) | // LetterNumber = 9,
/* false */ (0 << 10) | // OtherNumber = 10,
/* true */ (1 << 11) | // SpaceSeparator = 11,
/* true */ (1 << 12) | // LineSeparator = 12,
/* true */ (1 << 13) | // ParagraphSeparator = 13,
/* true */ (1 << 14) | // Control = 14,
/* true */ (1 << 15) | // Format = 15,
/* false */ (0 << 16) | // Surrogate = 16,
/* false */ (0 << 17) | // PrivateUse = 17,
/* true */ (1 << 18) | // ConnectorPunctuation = 18,
/* true */ (1 << 19) | // DashPunctuation = 19,
/* true */ (1 << 20) | // OpenPunctuation = 20,
/* true */ (1 << 21) | // ClosePunctuation = 21,
/* true */ (1 << 22) | // InitialQuotePunctuation = 22,
/* true */ (1 << 23) | // FinalQuotePunctuation = 23,
/* true */ (1 << 24) | // OtherPunctuation = 24,
/* true */ (1 << 25) | // MathSymbol = 25,
/* true */ (1 << 26) | // CurrencySymbol = 26,
/* true */ (1 << 27) | // ModifierSymbol = 27,
/* true */ (1 << 28) | // OtherSymbol = 28,
/* false */ (0 << 29); // OtherNotAssigned = 29;
private static bool IsWordSeparator(UnicodeCategory category)
{
return (c_wordSeparatorMask & (1 << (int) category)) != 0;
}
private static bool IsLetterCategory(UnicodeCategory uc)
{
return (uc == UnicodeCategory.UppercaseLetter
|| uc == UnicodeCategory.LowercaseLetter
|| uc == UnicodeCategory.TitlecaseLetter
|| uc == UnicodeCategory.ModifierLetter
|| uc == UnicodeCategory.OtherLetter);
}
}
}
| |
#region Copyright
//
// This framework is based on log4j see http://jakarta.apache.org/log4j
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.IO;
using System.Text;
using log4net.helpers;
using log4net.Layout;
using log4net.spi;
namespace log4net.Appender
{
/// <summary>
/// Appends logging events to a file.
/// </summary>
/// <remarks>
/// <para>
/// Logging events are sent to the specified file.
/// </para>
/// <para>
/// The file can be opened in either append or
/// overwrite mode.
/// </para>
/// </remarks>
public class FileAppender : TextWriterAppender
{
#region Public Instance Constructors
/// <summary>
/// Default constructor
/// </summary>
public FileAppender()
{
}
/// <summary>
/// Construct a new appender using the layout, file and append mode.
/// </summary>
/// <param name="layout">the layout to use with this appender</param>
/// <param name="filename">the full path to the file to write to</param>
/// <param name="append">flag to indicate if the file should be appended to</param>
public FileAppender(ILayout layout, string filename, bool append)
{
Layout = layout;
OpenFile(filename, append);
}
/// <summary>
/// Construct a new appender using the layout and file specified.
/// The file will be appended to.
/// </summary>
/// <param name="layout">the layout to use with this appender</param>
/// <param name="filename">the full path to the file to write to</param>
public FileAppender(ILayout layout, string filename) : this(layout, filename, true)
{
}
#endregion Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets the path to the file that logging will be written to.
/// </summary>
/// <value>
/// The path to the file that logging will be written to.
/// </value>
/// <remarks>
/// <para>
/// If the path is relative it is taken as relative from
/// the application base directory.
/// </para>
/// </remarks>
virtual public string File
{
get { return m_fileName; }
set { m_fileName = ConvertToFullPath(value.Trim()); }
}
/// <summary>
/// Gets or sets a flag that indicates weather the file should be
/// appended to or overwritten.
/// </summary>
/// <value>
/// Indicates whether the file should be appended to or overwritten.
/// </value>
/// <remarks>
/// <para>
/// If the value is set to false then the file will be overwritten, if
/// it is set to true then the file will be appended to.
/// </para>
/// The default value is true.
/// </remarks>
public bool AppendToFile
{
get { return m_appendToFile; }
set { m_appendToFile = value; }
}
/// <summary>
/// Gets or sets <see cref="Encoding"/> used to write to the file.
/// </summary>
/// <value>
/// The <see cref="Encoding"/> used to write to the file.
/// </value>
public Encoding Encoding
{
get { return m_encoding; }
set { m_encoding = value; }
}
#endregion Public Instance Properties
#region Override implementation of AppenderSkeleton
/// <summary>
/// Activate the options on the file appender. This will
/// case the file to be opened.
/// </summary>
override public void ActivateOptions()
{
base.ActivateOptions();
if (m_fileName != null)
{
// We must cache the params locally because OpenFile will call
// Reset which will clear the class fields. We need to remember the
// values in case of an error.
string fileName = m_fileName;
bool appendToFile = m_appendToFile;
try
{
OpenFile(fileName, appendToFile);
}
catch(Exception e)
{
ErrorHandler.Error("OpenFile("+fileName+","+appendToFile+") call failed.", e, ErrorCodes.FileOpenFailure);
}
}
else
{
LogLog.Warn("FileAppender: File option not set for appender ["+Name+"].");
LogLog.Warn("FileAppender: Are you using FileAppender instead of ConsoleAppender?");
}
}
#endregion Override implementation of AppenderSkeleton
#region Override implementation of TextWriterAppender
/// <summary>
/// Closes any previously opened file and calls the parent's <see cref="TextWriterAppender.Reset"/>.
/// </summary>
override protected void Reset()
{
base.Reset();
m_fileName = null;
}
#endregion Override implementation of TextWriterAppender
#region Public Instance Methods
/// <summary>
/// Closes the previously opened file.
/// </summary>
protected void CloseFile()
{
WriteFooterAndCloseWriter();
}
#endregion Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Sets and <i>opens</i> the file where the log output will
/// go. The specified file must be writable.
/// </summary>
/// <param name="fileName">The path to the log file</param>
/// <param name="append">If true will append to fileName. Otherwise will truncate fileName</param>
/// <remarks>
/// <para>If there was already an opened file, then the previous file
/// is closed first.</para>
///
/// <para>This method will ensure that the directory structure
/// for the <paramref name="fileName"/> specified exists.</para>
/// </remarks>
virtual protected void OpenFile(string fileName, bool append)
{
lock(this)
{
Reset();
LogLog.Debug("FileAppender: Opening file for writing ["+fileName+"] append ["+append+"]");
// Ensure that the directory structure exists
Directory.CreateDirectory((new FileInfo(fileName)).DirectoryName);
SetQWForFiles(new StreamWriter(fileName, append, m_encoding));
m_fileName = fileName;
m_appendToFile = append;
WriteHeader();
}
}
/// <summary>
/// Sets the quiet writer being used.
/// </summary>
/// <remarks>
/// This method can be overridden by sub classes.
/// </remarks>
/// <param name="writer">the writer to set</param>
virtual protected void SetQWForFiles(TextWriter writer)
{
m_qtw = new QuietTextWriter(writer, ErrorHandler);
}
#endregion Protected Instance Methods
#region Protected Static Methods
/// <summary>
/// Convert a path into a fully qualified path.
/// </summary>
/// <param name="path">The path to convert.</param>
/// <remarks>
/// <para>
/// Converts the path specified to a fully
/// qualified path. If the path is relative it is
/// taken as relative from the application base
/// directory.
/// </para>
/// </remarks>
/// <returns>The fully qualified path.</returns>
protected static string ConvertToFullPath(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (SystemInfo.ApplicationBaseDirectory != null)
{
// Note that Path.Combine will return the second path if it is rooted
return Path.GetFullPath(Path.Combine(SystemInfo.ApplicationBaseDirectory, path));
}
return Path.GetFullPath(path);
}
#endregion Protected Static Methods
#region Private Instance Fields
/// <summary>
/// Flag to indicate if we should append to the file
/// or overwrite the file. The default is to append.
/// </summary>
private bool m_appendToFile = true;
/// <summary>
/// The name of the log file.
/// </summary>
private string m_fileName = null;
/// <summary>
/// The encoding to use for the file stream.
/// </summary>
private Encoding m_encoding = Encoding.Default;
#endregion Private Instance Fields
}
}
| |
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 ApiPractice.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Schema
{
using System;
using System.Xml;
using System.Diagnostics;
using System.Text;
/// <summary>
/// This enum specifies what format should be used when converting string to XsdDateTime
/// </summary>
[Flags]
internal enum XsdDateTimeFlags
{
DateTime = 0x01,
Time = 0x02,
Date = 0x04,
GYearMonth = 0x08,
GYear = 0x10,
GMonthDay = 0x20,
GDay = 0x40,
GMonth = 0x80,
XdrDateTimeNoTz = 0x100,
XdrDateTime = 0x200,
XdrTimeNoTz = 0x400, //XDRTime with tz is the same as xsd:time
AllXsd = 0xFF //All still does not include the XDR formats
}
/// <summary>
/// This structure extends System.DateTime to support timeInTicks zone and Gregorian types components of an Xsd Duration. It is used internally to support Xsd durations without loss
/// of fidelity. XsdDuration structures are immutable once they've been created.
/// </summary>
internal struct XsdDateTime
{
// DateTime is being used as an internal representation only
// Casting XsdDateTime to DateTime might return a different value
private DateTime _dt;
// Additional information that DateTime is not preserving
// Information is stored in the following format:
// Bits Info
// 31-24 DateTimeTypeCode
// 23-16 XsdDateTimeKind
// 15-8 Zone Hours
// 7-0 Zone Minutes
private uint _extra;
// Subset of XML Schema types XsdDateTime represents
private enum DateTimeTypeCode
{
DateTime,
Time,
Date,
GYearMonth,
GYear,
GMonthDay,
GDay,
GMonth,
XdrDateTime,
}
// Internal representation of DateTimeKind
private enum XsdDateTimeKind
{
Unspecified,
Zulu,
LocalWestOfZulu, // GMT-1..14, N..Y
LocalEastOfZulu // GMT+1..14, A..M
}
// Masks and shifts used for packing and unpacking extra
private const uint TypeMask = 0xFF000000;
private const uint KindMask = 0x00FF0000;
private const uint ZoneHourMask = 0x0000FF00;
private const uint ZoneMinuteMask = 0x000000FF;
private const int TypeShift = 24;
private const int KindShift = 16;
private const int ZoneHourShift = 8;
// Maximum number of fraction digits;
private const short maxFractionDigits = 7;
private static readonly int s_lzyyyy = "yyyy".Length;
private static readonly int s_lzyyyy_ = "yyyy-".Length;
private static readonly int s_lzyyyy_MM = "yyyy-MM".Length;
private static readonly int s_lzyyyy_MM_ = "yyyy-MM-".Length;
private static readonly int s_lzyyyy_MM_dd = "yyyy-MM-dd".Length;
private static readonly int s_lzyyyy_MM_ddT = "yyyy-MM-ddT".Length;
private static readonly int s_lzHH = "HH".Length;
private static readonly int s_lzHH_ = "HH:".Length;
private static readonly int s_lzHH_mm = "HH:mm".Length;
private static readonly int s_lzHH_mm_ = "HH:mm:".Length;
private static readonly int s_lzHH_mm_ss = "HH:mm:ss".Length;
private static readonly int s_Lz_ = "-".Length;
private static readonly int s_lz_zz = "-zz".Length;
private static readonly int s_lz_zz_ = "-zz:".Length;
private static readonly int s_lz_zz_zz = "-zz:zz".Length;
private static readonly int s_Lz__ = "--".Length;
private static readonly int s_lz__mm = "--MM".Length;
private static readonly int s_lz__mm_ = "--MM-".Length;
private static readonly int s_lz__mm__ = "--MM--".Length;
private static readonly int s_lz__mm_dd = "--MM-dd".Length;
private static readonly int s_Lz___ = "---".Length;
private static readonly int s_lz___dd = "---dd".Length;
/// <summary>
/// Constructs an XsdDateTime from a string using specific format.
/// </summary>
public XsdDateTime(string text, XsdDateTimeFlags kinds) : this()
{
Parser parser = new Parser();
if (!parser.Parse(text, kinds))
{
throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, text, kinds));
}
InitiateXsdDateTime(parser);
}
private XsdDateTime(Parser parser) : this()
{
InitiateXsdDateTime(parser);
}
private void InitiateXsdDateTime(Parser parser)
{
_dt = new DateTime(parser.year, parser.month, parser.day, parser.hour, parser.minute, parser.second);
if (parser.fraction != 0)
{
_dt = _dt.AddTicks(parser.fraction);
}
_extra = (uint)(((int)parser.typeCode << TypeShift) | ((int)parser.kind << KindShift) | (parser.zoneHour << ZoneHourShift) | parser.zoneMinute);
}
internal static bool TryParse(string text, XsdDateTimeFlags kinds, out XsdDateTime result)
{
Parser parser = new Parser();
if (!parser.Parse(text, kinds))
{
result = new XsdDateTime();
return false;
}
result = new XsdDateTime(parser);
return true;
}
/// <summary>
/// Constructs an XsdDateTime from a DateTime.
/// </summary>
public XsdDateTime(DateTime dateTime, XsdDateTimeFlags kinds)
{
Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set.");
_dt = dateTime;
DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1);
int zoneHour = 0;
int zoneMinute = 0;
XsdDateTimeKind kind;
switch (dateTime.Kind)
{
case DateTimeKind.Unspecified: kind = XsdDateTimeKind.Unspecified; break;
case DateTimeKind.Utc: kind = XsdDateTimeKind.Zulu; break;
default:
{
Debug.Assert(dateTime.Kind == DateTimeKind.Local, "Unknown DateTimeKind: " + dateTime.Kind);
TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(dateTime);
if (utcOffset.Ticks < 0)
{
kind = XsdDateTimeKind.LocalWestOfZulu;
zoneHour = -utcOffset.Hours;
zoneMinute = -utcOffset.Minutes;
}
else
{
kind = XsdDateTimeKind.LocalEastOfZulu;
zoneHour = utcOffset.Hours;
zoneMinute = utcOffset.Minutes;
}
break;
}
}
_extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneHour << ZoneHourShift) | zoneMinute);
}
// Constructs an XsdDateTime from a DateTimeOffset
public XsdDateTime(DateTimeOffset dateTimeOffset) : this(dateTimeOffset, XsdDateTimeFlags.DateTime)
{
}
public XsdDateTime(DateTimeOffset dateTimeOffset, XsdDateTimeFlags kinds)
{
Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set.");
_dt = dateTimeOffset.DateTime;
TimeSpan zoneOffset = dateTimeOffset.Offset;
DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1);
XsdDateTimeKind kind;
if (zoneOffset.TotalMinutes < 0)
{
zoneOffset = zoneOffset.Negate();
kind = XsdDateTimeKind.LocalWestOfZulu;
}
else if (zoneOffset.TotalMinutes > 0)
{
kind = XsdDateTimeKind.LocalEastOfZulu;
}
else
{
kind = XsdDateTimeKind.Zulu;
}
_extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneOffset.Hours << ZoneHourShift) | zoneOffset.Minutes);
}
/// <summary>
/// Returns auxiliary enumeration of XSD date type
/// </summary>
private DateTimeTypeCode InternalTypeCode
{
get { return (DateTimeTypeCode)((_extra & TypeMask) >> TypeShift); }
}
/// <summary>
/// Returns geographical "position" of the value
/// </summary>
private XsdDateTimeKind InternalKind
{
get { return (XsdDateTimeKind)((_extra & KindMask) >> KindShift); }
}
/// <summary>
/// Returns XmlTypeCode of the value being stored
/// </summary>
public XmlTypeCode TypeCode
{
get { return s_typeCodes[(int)InternalTypeCode]; }
}
/// <summary>
/// Returns the year part of XsdDateTime
/// The returned value is integer between 1 and 9999
/// </summary>
public int Year
{
get { return _dt.Year; }
}
/// <summary>
/// Returns the month part of XsdDateTime
/// The returned value is integer between 1 and 12
/// </summary>
public int Month
{
get { return _dt.Month; }
}
/// <summary>
/// Returns the day of the month part of XsdDateTime
/// The returned value is integer between 1 and 31
/// </summary>
public int Day
{
get { return _dt.Day; }
}
/// <summary>
/// Returns the hour part of XsdDateTime
/// The returned value is integer between 0 and 23
/// </summary>
public int Hour
{
get { return _dt.Hour; }
}
/// <summary>
/// Returns the minute part of XsdDateTime
/// The returned value is integer between 0 and 60
/// </summary>
public int Minute
{
get { return _dt.Minute; }
}
/// <summary>
/// Returns the second part of XsdDateTime
/// The returned value is integer between 0 and 60
/// </summary>
public int Second
{
get { return _dt.Second; }
}
/// <summary>
/// Returns number of ticks in the fraction of the second
/// The returned value is integer between 0 and 9999999
/// </summary>
public int Fraction
{
get { return (int)(_dt.Ticks - new DateTime(_dt.Year, _dt.Month, _dt.Day, _dt.Hour, _dt.Minute, _dt.Second).Ticks); }
}
/// <summary>
/// Returns the hour part of the time zone
/// The returned value is integer between -13 and 13
/// </summary>
public int ZoneHour
{
get
{
uint result = (_extra & ZoneHourMask) >> ZoneHourShift;
return (int)result;
}
}
/// <summary>
/// Returns the minute part of the time zone
/// The returned value is integer between 0 and 60
/// </summary>
public int ZoneMinute
{
get
{
uint result = (_extra & ZoneMinuteMask);
return (int)result;
}
}
public DateTime ToZulu()
{
switch (InternalKind)
{
case XsdDateTimeKind.Zulu:
// set it to UTC
return new DateTime(_dt.Ticks, DateTimeKind.Utc);
case XsdDateTimeKind.LocalEastOfZulu:
// Adjust to UTC and then convert to local in the current time zone
return new DateTime(_dt.Subtract(new TimeSpan(ZoneHour, ZoneMinute, 0)).Ticks, DateTimeKind.Utc);
case XsdDateTimeKind.LocalWestOfZulu:
// Adjust to UTC and then convert to local in the current time zone
return new DateTime(_dt.Add(new TimeSpan(ZoneHour, ZoneMinute, 0)).Ticks, DateTimeKind.Utc);
default:
return _dt;
}
}
/// <summary>
/// Cast to DateTime
/// The following table describes the behaviors of getting the default value
/// when a certain year/month/day values are missing.
///
/// An "X" means that the value exists. And "--" means that value is missing.
///
/// Year Month Day => ResultYear ResultMonth ResultDay Note
///
/// X X X Parsed year Parsed month Parsed day
/// X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month.
/// X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year.
/// X -- -- Parsed year First month First day If we have only the year, assume the first day of that year.
///
/// -- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year.
/// -- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day.
/// -- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month.
/// -- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date.
/// </summary>
public static implicit operator DateTime(XsdDateTime xdt)
{
DateTime result;
switch (xdt.InternalTypeCode)
{
case DateTimeTypeCode.GMonth:
case DateTimeTypeCode.GDay:
result = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day);
break;
case DateTimeTypeCode.Time:
//back to DateTime.Now
DateTime currentDateTime = DateTime.Now;
TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day);
result = xdt._dt.Add(addDiff);
break;
default:
result = xdt._dt;
break;
}
long ticks;
switch (xdt.InternalKind)
{
case XsdDateTimeKind.Zulu:
// set it to UTC
result = new DateTime(result.Ticks, DateTimeKind.Utc);
break;
case XsdDateTimeKind.LocalEastOfZulu:
// Adjust to UTC and then convert to local in the current time zone
ticks = result.Ticks - new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks;
if (ticks < DateTime.MinValue.Ticks)
{
// Underflow. Return the DateTime as local time directly
ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks;
if (ticks < DateTime.MinValue.Ticks)
ticks = DateTime.MinValue.Ticks;
return new DateTime(ticks, DateTimeKind.Local);
}
result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
break;
case XsdDateTimeKind.LocalWestOfZulu:
// Adjust to UTC and then convert to local in the current time zone
ticks = result.Ticks + new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks;
if (ticks > DateTime.MaxValue.Ticks)
{
// Overflow. Return the DateTime as local time directly
ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks;
if (ticks > DateTime.MaxValue.Ticks)
ticks = DateTime.MaxValue.Ticks;
return new DateTime(ticks, DateTimeKind.Local);
}
result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
break;
default:
break;
}
return result;
}
public static implicit operator DateTimeOffset(XsdDateTime xdt)
{
DateTime dt;
switch (xdt.InternalTypeCode)
{
case DateTimeTypeCode.GMonth:
case DateTimeTypeCode.GDay:
dt = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day);
break;
case DateTimeTypeCode.Time:
//back to DateTime.Now
DateTime currentDateTime = DateTime.Now;
TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day);
dt = xdt._dt.Add(addDiff);
break;
default:
dt = xdt._dt;
break;
}
DateTimeOffset result;
switch (xdt.InternalKind)
{
case XsdDateTimeKind.LocalEastOfZulu:
result = new DateTimeOffset(dt, new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0));
break;
case XsdDateTimeKind.LocalWestOfZulu:
result = new DateTimeOffset(dt, new TimeSpan(-xdt.ZoneHour, -xdt.ZoneMinute, 0));
break;
case XsdDateTimeKind.Zulu:
result = new DateTimeOffset(dt, new TimeSpan(0));
break;
case XsdDateTimeKind.Unspecified:
default:
result = new DateTimeOffset(dt, TimeZoneInfo.Local.GetUtcOffset(dt));
break;
}
return result;
}
/// <summary>
/// Serialization to a string
/// </summary>
public override string ToString()
{
StringBuilder sb = new StringBuilder(64);
char[] text;
switch (InternalTypeCode)
{
case DateTimeTypeCode.DateTime:
PrintDate(sb);
sb.Append('T');
PrintTime(sb);
break;
case DateTimeTypeCode.Time:
PrintTime(sb);
break;
case DateTimeTypeCode.Date:
PrintDate(sb);
break;
case DateTimeTypeCode.GYearMonth:
text = new char[s_lzyyyy_MM];
IntToCharArray(text, 0, Year, 4);
text[s_lzyyyy] = '-';
ShortToCharArray(text, s_lzyyyy_, Month);
sb.Append(text);
break;
case DateTimeTypeCode.GYear:
text = new char[s_lzyyyy];
IntToCharArray(text, 0, Year, 4);
sb.Append(text);
break;
case DateTimeTypeCode.GMonthDay:
text = new char[s_lz__mm_dd];
text[0] = '-';
text[s_Lz_] = '-';
ShortToCharArray(text, s_Lz__, Month);
text[s_lz__mm] = '-';
ShortToCharArray(text, s_lz__mm_, Day);
sb.Append(text);
break;
case DateTimeTypeCode.GDay:
text = new char[s_lz___dd];
text[0] = '-';
text[s_Lz_] = '-';
text[s_Lz__] = '-';
ShortToCharArray(text, s_Lz___, Day);
sb.Append(text);
break;
case DateTimeTypeCode.GMonth:
text = new char[s_lz__mm__];
text[0] = '-';
text[s_Lz_] = '-';
ShortToCharArray(text, s_Lz__, Month);
text[s_lz__mm] = '-';
text[s_lz__mm_] = '-';
sb.Append(text);
break;
}
PrintZone(sb);
return sb.ToString();
}
// Serialize year, month and day
private void PrintDate(StringBuilder sb)
{
char[] text = new char[s_lzyyyy_MM_dd];
IntToCharArray(text, 0, Year, 4);
text[s_lzyyyy] = '-';
ShortToCharArray(text, s_lzyyyy_, Month);
text[s_lzyyyy_MM] = '-';
ShortToCharArray(text, s_lzyyyy_MM_, Day);
sb.Append(text);
}
// Serialize hour, minute, second and fraction
private void PrintTime(StringBuilder sb)
{
char[] text = new char[s_lzHH_mm_ss];
ShortToCharArray(text, 0, Hour);
text[s_lzHH] = ':';
ShortToCharArray(text, s_lzHH_, Minute);
text[s_lzHH_mm] = ':';
ShortToCharArray(text, s_lzHH_mm_, Second);
sb.Append(text);
int fraction = Fraction;
if (fraction != 0)
{
int fractionDigits = maxFractionDigits;
while (fraction % 10 == 0)
{
fractionDigits--;
fraction /= 10;
}
text = new char[fractionDigits + 1];
text[0] = '.';
IntToCharArray(text, 1, fraction, fractionDigits);
sb.Append(text);
}
}
// Serialize time zone
private void PrintZone(StringBuilder sb)
{
char[] text;
switch (InternalKind)
{
case XsdDateTimeKind.Zulu:
sb.Append('Z');
break;
case XsdDateTimeKind.LocalWestOfZulu:
text = new char[s_lz_zz_zz];
text[0] = '-';
ShortToCharArray(text, s_Lz_, ZoneHour);
text[s_lz_zz] = ':';
ShortToCharArray(text, s_lz_zz_, ZoneMinute);
sb.Append(text);
break;
case XsdDateTimeKind.LocalEastOfZulu:
text = new char[s_lz_zz_zz];
text[0] = '+';
ShortToCharArray(text, s_Lz_, ZoneHour);
text[s_lz_zz] = ':';
ShortToCharArray(text, s_lz_zz_, ZoneMinute);
sb.Append(text);
break;
default:
// do nothing
break;
}
}
// Serialize integer into character array starting with index [start].
// Number of digits is set by [digits]
private void IntToCharArray(char[] text, int start, int value, int digits)
{
while (digits-- != 0)
{
text[start + digits] = (char)(value % 10 + '0');
value /= 10;
}
}
// Serialize two digit integer into character array starting with index [start].
private void ShortToCharArray(char[] text, int start, int value)
{
text[start] = (char)(value / 10 + '0');
text[start + 1] = (char)(value % 10 + '0');
}
private static readonly XmlTypeCode[] s_typeCodes = {
XmlTypeCode.DateTime,
XmlTypeCode.Time,
XmlTypeCode.Date,
XmlTypeCode.GYearMonth,
XmlTypeCode.GYear,
XmlTypeCode.GMonthDay,
XmlTypeCode.GDay,
XmlTypeCode.GMonth
};
// Parsing string according to XML schema spec
private struct Parser
{
private const int leapYear = 1904;
private const int firstMonth = 1;
private const int firstDay = 1;
public DateTimeTypeCode typeCode;
public int year;
public int month;
public int day;
public int hour;
public int minute;
public int second;
public int fraction;
public XsdDateTimeKind kind;
public int zoneHour;
public int zoneMinute;
private string _text;
private int _length;
public bool Parse(string text, XsdDateTimeFlags kinds)
{
_text = text;
_length = text.Length;
// Skip leading whitespace
int start = 0;
while (start < _length && char.IsWhiteSpace(text[start]))
{
start++;
}
// Choose format starting from the most common and trying not to reparse the same thing too many times
if (Test(kinds, XsdDateTimeFlags.DateTime | XsdDateTimeFlags.Date | XsdDateTimeFlags.XdrDateTime | XsdDateTimeFlags.XdrDateTimeNoTz))
{
if (ParseDate(start))
{
if (Test(kinds, XsdDateTimeFlags.DateTime))
{
if (ParseChar(start + s_lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(start + s_lzyyyy_MM_ddT))
{
typeCode = DateTimeTypeCode.DateTime;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.Date))
{
if (ParseZoneAndWhitespace(start + s_lzyyyy_MM_dd))
{
typeCode = DateTimeTypeCode.Date;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.XdrDateTime))
{
if (ParseZoneAndWhitespace(start + s_lzyyyy_MM_dd) || (ParseChar(start + s_lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(start + s_lzyyyy_MM_ddT)))
{
typeCode = DateTimeTypeCode.XdrDateTime;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.XdrDateTimeNoTz))
{
if (ParseChar(start + s_lzyyyy_MM_dd, 'T'))
{
if (ParseTimeAndWhitespace(start + s_lzyyyy_MM_ddT))
{
typeCode = DateTimeTypeCode.XdrDateTime;
return true;
}
}
else
{
typeCode = DateTimeTypeCode.XdrDateTime;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.Time))
{
if (ParseTimeAndZoneAndWhitespace(start))
{ //Equivalent to NoCurrentDateDefault on DateTimeStyles while parsing xs:time
year = leapYear;
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.Time;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.XdrTimeNoTz))
{
if (ParseTimeAndWhitespace(start))
{ //Equivalent to NoCurrentDateDefault on DateTimeStyles while parsing xs:time
year = leapYear;
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.Time;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GYearMonth | XsdDateTimeFlags.GYear))
{
if (Parse4Dig(start, ref year) && 1 <= year)
{
if (Test(kinds, XsdDateTimeFlags.GYearMonth))
{
if (
ParseChar(start + s_lzyyyy, '-') &&
Parse2Dig(start + s_lzyyyy_, ref month) && 1 <= month && month <= 12 &&
ParseZoneAndWhitespace(start + s_lzyyyy_MM)
)
{
day = firstDay;
typeCode = DateTimeTypeCode.GYearMonth;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GYear))
{
if (ParseZoneAndWhitespace(start + s_lzyyyy))
{
month = firstMonth;
day = firstDay;
typeCode = DateTimeTypeCode.GYear;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.GMonthDay | XsdDateTimeFlags.GMonth))
{
if (
ParseChar(start, '-') &&
ParseChar(start + s_Lz_, '-') &&
Parse2Dig(start + s_Lz__, ref month) && 1 <= month && month <= 12
)
{
if (Test(kinds, XsdDateTimeFlags.GMonthDay) && ParseChar(start + s_lz__mm, '-'))
{
if (
Parse2Dig(start + s_lz__mm_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, month) &&
ParseZoneAndWhitespace(start + s_lz__mm_dd)
)
{
year = leapYear;
typeCode = DateTimeTypeCode.GMonthDay;
return true;
}
}
if (Test(kinds, XsdDateTimeFlags.GMonth))
{
if (ParseZoneAndWhitespace(start + s_lz__mm) || (ParseChar(start + s_lz__mm, '-') && ParseChar(start + s_lz__mm_, '-') && ParseZoneAndWhitespace(start + s_lz__mm__)))
{
year = leapYear;
day = firstDay;
typeCode = DateTimeTypeCode.GMonth;
return true;
}
}
}
}
if (Test(kinds, XsdDateTimeFlags.GDay))
{
if (
ParseChar(start, '-') &&
ParseChar(start + s_Lz_, '-') &&
ParseChar(start + s_Lz__, '-') &&
Parse2Dig(start + s_Lz___, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, firstMonth) &&
ParseZoneAndWhitespace(start + s_lz___dd)
)
{
year = leapYear;
month = firstMonth;
typeCode = DateTimeTypeCode.GDay;
return true;
}
}
return false;
}
private bool ParseDate(int start)
{
return
Parse4Dig(start, ref year) && 1 <= year &&
ParseChar(start + s_lzyyyy, '-') &&
Parse2Dig(start + s_lzyyyy_, ref month) && 1 <= month && month <= 12 &&
ParseChar(start + s_lzyyyy_MM, '-') &&
Parse2Dig(start + s_lzyyyy_MM_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(year, month);
}
private bool ParseTimeAndZoneAndWhitespace(int start)
{
if (ParseTime(ref start))
{
if (ParseZoneAndWhitespace(start))
{
return true;
}
}
return false;
}
private bool ParseTimeAndWhitespace(int start)
{
if (ParseTime(ref start))
{
while (start < _length)
{//&& char.IsWhiteSpace(text[start])) {
start++;
}
return start == _length;
}
return false;
}
private static int[] s_power10 = new int[maxFractionDigits] { -1, 10, 100, 1000, 10000, 100000, 1000000 };
private bool ParseTime(ref int start)
{
if (
Parse2Dig(start, ref hour) && hour < 24 &&
ParseChar(start + s_lzHH, ':') &&
Parse2Dig(start + s_lzHH_, ref minute) && minute < 60 &&
ParseChar(start + s_lzHH_mm, ':') &&
Parse2Dig(start + s_lzHH_mm_, ref second) && second < 60
)
{
start += s_lzHH_mm_ss;
if (ParseChar(start, '.'))
{
// Parse factional part of seconds
// We allow any number of digits, but keep only first 7
this.fraction = 0;
int fractionDigits = 0;
int round = 0;
while (++start < _length)
{
int d = _text[start] - '0';
if (9u < unchecked((uint)d))
{ // d < 0 || 9 < d
break;
}
if (fractionDigits < maxFractionDigits)
{
this.fraction = (this.fraction * 10) + d;
}
else if (fractionDigits == maxFractionDigits)
{
if (5 < d)
{
round = 1;
}
else if (d == 5)
{
round = -1;
}
}
else if (round < 0 && d != 0)
{
round = 1;
}
fractionDigits++;
}
if (fractionDigits < maxFractionDigits)
{
if (fractionDigits == 0)
{
return false; // cannot end with .
}
fraction *= s_power10[maxFractionDigits - fractionDigits];
}
else
{
if (round < 0)
{
round = fraction & 1;
}
fraction += round;
}
}
return true;
}
// cleanup - conflict with gYear
hour = 0;
return false;
}
private bool ParseZoneAndWhitespace(int start)
{
if (start < _length)
{
char ch = _text[start];
if (ch == 'Z' || ch == 'z')
{
kind = XsdDateTimeKind.Zulu;
start++;
}
else if (start + 5 < _length)
{
if (
Parse2Dig(start + s_Lz_, ref zoneHour) && zoneHour <= 99 &&
ParseChar(start + s_lz_zz, ':') &&
Parse2Dig(start + s_lz_zz_, ref zoneMinute) && zoneMinute <= 99
)
{
if (ch == '-')
{
kind = XsdDateTimeKind.LocalWestOfZulu;
start += s_lz_zz_zz;
}
else if (ch == '+')
{
kind = XsdDateTimeKind.LocalEastOfZulu;
start += s_lz_zz_zz;
}
}
}
}
while (start < _length && char.IsWhiteSpace(_text[start]))
{
start++;
}
return start == _length;
}
private bool Parse4Dig(int start, ref int num)
{
if (start + 3 < _length)
{
int d4 = _text[start] - '0';
int d3 = _text[start + 1] - '0';
int d2 = _text[start + 2] - '0';
int d1 = _text[start + 3] - '0';
if (0 <= d4 && d4 < 10 &&
0 <= d3 && d3 < 10 &&
0 <= d2 && d2 < 10 &&
0 <= d1 && d1 < 10
)
{
num = ((d4 * 10 + d3) * 10 + d2) * 10 + d1;
return true;
}
}
return false;
}
private bool Parse2Dig(int start, ref int num)
{
if (start + 1 < _length)
{
int d2 = _text[start] - '0';
int d1 = _text[start + 1] - '0';
if (0 <= d2 && d2 < 10 &&
0 <= d1 && d1 < 10
)
{
num = d2 * 10 + d1;
return true;
}
}
return false;
}
private bool ParseChar(int start, char ch)
{
return start < _length && _text[start] == ch;
}
private static bool Test(XsdDateTimeFlags left, XsdDateTimeFlags right)
{
return (left & right) != 0;
}
}
}
}
| |
namespace dotless.Core.Parser
{
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Exceptions;
using Infrastructure.Nodes;
using Utils;
public class Tokenizer
{
public int Optimization { get; set; }
private string _input; // LeSS input string
private List<Chunk> _chunks; // chunkified input
private int _i; // current index in `input`
private int _j; // current chunk
private int _current; // index of current chunk, in `input`
private int _lastCommentStart = -1; // the start of the last collection of comments
private int _lastCommentEnd = -1; // the end of the last collection of comments
private int _inputLength;
private readonly string _commentRegEx = @"(//[^\n]*|(/\*(.|[\r\n])*?\*/))";
private readonly string _quotedRegEx = @"(""((?:[^""\\\r\n]|\\.)*)""|'((?:[^'\\\r\n]|\\.)*)')";
private string _fileName;
//Increasing throughput through tracing of Regex
private IDictionary<string, Regex> regexCache = new Dictionary<string, Regex>();
public Tokenizer(int optimization)
{
Optimization = optimization;
}
public void SetupInput(string input, string fileName)
{
_fileName = fileName;
_i = _j = _current = 0;
_chunks = new List<Chunk>();
_input = input.Replace("\r\n", "\n");
_inputLength = _input.Length;
// Split the input into chunks,
// Either delimited by /\n\n/ or
// delmited by '\n}' (see rationale above),
// depending on the level of optimization.
if(Optimization == 0)
_chunks.Add(new Chunk(_input));
else
{
var skip = new Regex(@"\G(@\{[a-zA-Z0-9_-]+\}|[^\""'{}/\\\(\)]+)");
var comment = GetRegex(this._commentRegEx, RegexOptions.None);
var quotedstring = GetRegex(this._quotedRegEx, RegexOptions.None);
var level = 0;
var lastBlock = 0;
var inParam = false;
int i = 0;
while(i < _inputLength)
{
var match = skip.Match(_input, i);
if(match.Success)
{
Chunk.Append(match.Value, _chunks);
i += match.Length;
continue;
}
var c = _input[i];
if(i < _inputLength - 1 && c == '/')
{
var cc = _input[i + 1];
if ((!inParam && cc == '/') || cc == '*')
{
match = comment.Match(_input, i);
if(match.Success)
{
i += match.Length;
_chunks.Add(new Chunk(match.Value, ChunkType.Comment));
continue;
} else
{
throw new ParsingException("Missing closing comment", GetNodeLocation(i));
}
}
}
if(c == '"' || c == '\'')
{
match = quotedstring.Match(_input, i);
if(match.Success)
{
i += match.Length;
_chunks.Add(new Chunk(match.Value, ChunkType.QuotedString));
continue;
} else
{
throw new ParsingException(string.Format("Missing closing quote ({0})", c), GetNodeLocation(i));
}
}
// we are not in a quoted string or comment - process '{' level
if(!inParam && c == '{')
{
level++;
lastBlock = i;
}
else if (!inParam && c == '}')
{
level--;
if(level < 0)
throw new ParsingException("Unexpected '}'", GetNodeLocation(i));
Chunk.Append(c, _chunks, true);
i++;
continue;
} if (c == '(')
{
inParam = true;
}
else if (c == ')')
{
inParam = false;
}
Chunk.Append(c, _chunks);
i++;
}
if(level > 0)
throw new ParsingException("Missing closing '}'", GetNodeLocation(lastBlock));
_input = Chunk.CommitAll(_chunks);
_inputLength = _input.Length;
}
Advance(0); // skip any whitespace characters at the start.
}
public string GetComment()
{
// if we've hit the end we might still be looking at a valid chunk, so return early
if (_i == _inputLength) {
return null;
}
string val;
int startI = _i;
int endI = 0;
if (Optimization == 0)
{
if (this.CurrentChar != '/')
return null;
var comment = this.Match(this._commentRegEx);
if (comment == null)
{
return null;
}
val = comment.Value;
endI = startI + comment.Value.Length;
}
else
{
if (_chunks[_j].Type == ChunkType.Comment)
{
val = _chunks[_j].Value;
endI = _i + _chunks[_j].Value.Length;
Advance(_chunks[_j].Value.Length);
}
else
{
return null;
}
}
if (_lastCommentEnd != startI)
{
_lastCommentStart = startI;
}
_lastCommentEnd = endI;
return val;
}
public string GetQuotedString()
{
// if we've hit the end we might still be looking at a valid chunk, so return early
if (_i == _inputLength) {
return null;
}
if (Optimization == 0) {
if (this.CurrentChar != '"' && this.CurrentChar != '\'')
return null;
var quotedstring = this.Match(this._quotedRegEx);
return quotedstring.Value;
} else {
if (_chunks[_j].Type == ChunkType.QuotedString) {
string val = _chunks[_j].Value;
Advance(_chunks[_j].Value.Length);
return val;
}
}
return null;
}
public string MatchString(char tok)
{
var c = Match(tok);
return c == null ? null : c.Value;
}
public string MatchString(string tok)
{
var match = Match(tok);
return match == null ? null : match.Value;
}
//
// Parse from a token, regexp or string, and move forward if match
//
public CharMatchResult Match(char tok)
{
if (_i == _inputLength || _chunks[_j].Type != ChunkType.Text) {
return null;
}
if (_input[_i] == tok)
{
var index = _i;
Advance(1);
return new CharMatchResult(tok) { Location = GetNodeLocation(index) };
}
return null;
}
public RegexMatchResult Match(string tok)
{
return Match(tok, false);
}
public RegexMatchResult Match(string tok, bool caseInsensitive)
{
if (_i == _inputLength || _chunks[_j].Type != ChunkType.Text) {
return null;
}
var options = RegexOptions.None;
if (caseInsensitive)
options |= RegexOptions.IgnoreCase;
var regex = GetRegex(tok, options);
var match = regex.Match(_chunks[_j].Value, _i - _current);
if (!match.Success)
return null;
var index = _i;
Advance(match.Length);
return new RegexMatchResult(match) {Location = GetNodeLocation(index)};
}
// Match a string, but include the possibility of matching quoted and comments
public RegexMatchResult MatchAny(string tok)
{
if (_i == _inputLength) {
return null;
}
var regex = GetRegex(tok, RegexOptions.None);
var match = regex.Match(_input, _i);
if (!match.Success)
return null;
Advance(match.Length);
if (_i > _current && _i < _current + _chunks[_j].Value.Length)
{
//If we absorbed the start of an inline comment then turn it into text so the rest can be absorbed
if (_chunks[_j].Type == ChunkType.Comment && _chunks[_j].Value.StartsWith("//"))
{
_chunks[_j].Type = ChunkType.Text;
}
}
return new RegexMatchResult(match);
}
public void Advance(int length)
{
if (_i == _inputLength) //only for empty cases as there may not be any chunks
return;
// The match is confirmed, add the match length to `i`,
// and consume any extra white-space characters (' ' || '\n')
// which come after that. The reason for this is that LeSS's
// grammar is mostly white-space insensitive.
_i += length;
var endIndex = _current + _chunks[_j].Value.Length;
while (true)
{
if(_i == _inputLength)
break;
if (_i >= endIndex)
{
if (_j < _chunks.Count - 1)
{
_current = endIndex;
endIndex += _chunks[++_j].Value.Length;
continue; // allow skipping multiple chunks
}
else
break;
}
if (!char.IsWhiteSpace(_input[_i]))
break;
_i++;
}
}
// Same as Match, but don't change the state of the parser,
// just return the match.
public bool Peek(char tok)
{
if (_i == _inputLength)
return false;
return _input[_i] == tok;
}
public bool Peek(string tok)
{
var regex = GetRegex(tok, RegexOptions.None);
var match = regex.Match(_input, _i);
return match.Success;
}
public bool PeekAfterComments(char tok)
{
var memo = this.Location;
while(GetComment() != null);
var peekSuccess = Peek(tok);
this.Location = memo;
return peekSuccess;
}
private Regex GetRegex(string pattern, RegexOptions options)
{
if (!regexCache.ContainsKey(pattern))
regexCache.Add(pattern, new Regex(@"\G" + pattern, options));
return regexCache[pattern];
}
public char GetPreviousCharIgnoringComments()
{
if (_i == 0) {
return '\0';
}
if (_i != _lastCommentEnd) {
return PreviousChar;
}
int i = _lastCommentStart - 1;
if (i < 0) {
return '\0';
}
return _input[i];
}
public char PreviousChar
{
get { return _i == 0 ? '\0' : _input[_i - 1]; }
}
public char CurrentChar
{
get { return _i == _inputLength ? '\0' : _input[_i]; }
}
public char NextChar
{
get { return _i + 1 == _inputLength ? '\0' : _input[_i + 1]; }
}
public bool HasCompletedParsing()
{
return _i == _inputLength;
}
public Location Location
{
get
{
return new Location
{
Index = _i,
CurrentChunk = _j,
CurrentChunkIndex = _current
};
}
set
{
_i = value.Index;
_j = value.CurrentChunk;
_current = value.CurrentChunkIndex;
}
}
public NodeLocation GetNodeLocation(int index)
{
return new NodeLocation(index, this._input, this._fileName);
}
public NodeLocation GetNodeLocation()
{
return GetNodeLocation(this.Location.Index);
}
private enum ChunkType
{
Text,
Comment,
QuotedString
}
private class Chunk
{
private StringBuilder _builder;
public Chunk(string val)
{
Value = val;
Type = ChunkType.Text;
}
public Chunk(string val, ChunkType type)
{
Value = val;
Type = type;
}
public Chunk()
{
_builder = new StringBuilder();
Type = ChunkType.Text;
}
public ChunkType Type { get; set; }
public string Value { get; set; }
private bool _final;
public void Append(string str)
{
_builder.Append(str);
}
public void Append(char c)
{
_builder.Append(c);
}
private static Chunk ReadyForText(List<Chunk> chunks)
{
Chunk last = chunks.LastOrDefault();
if (last == null || last.Type != ChunkType.Text || last._final == true)
{
last = new Chunk();
chunks.Add(last);
}
return last;
}
public static void Append(char c, List<Chunk> chunks, bool final)
{
Chunk chunk = ReadyForText(chunks);
chunk.Append(c);
chunk._final = final;
}
public static void Append(char c, List<Chunk> chunks)
{
Chunk chunk = ReadyForText(chunks);
chunk.Append(c);
}
public static void Append(string s, List<Chunk> chunks)
{
Chunk chunk = ReadyForText(chunks);
chunk.Append(s);
}
public static string CommitAll(List<Chunk> chunks)
{
StringBuilder all = new StringBuilder();
foreach(Chunk chunk in chunks)
{
if (chunk._builder != null)
{
string val = chunk._builder.ToString();
chunk._builder = null;
chunk.Value = val;
}
all.Append(chunk.Value);
}
return all.ToString();
}
}
}
public class Location
{
public int Index { get; set; }
public int CurrentChunk { get; set; }
public int CurrentChunkIndex { get; set; }
}
}
| |
using UnityEngine;
using System.Collections.Generic;
namespace Pathfinding.RVO {
/** Base class for simple RVO colliders.
*
* This is a helper base class for RVO colliders. It provides automatic gizmos
* and helps with the winding order of the vertices as well as automatically updating the obstacle when moved.
*
* Extend this class to create custom RVO obstacles.
*
* \see writing-rvo-colliders
* \see RVOSquareObstacle
*
* \astarpro
*/
public abstract class RVOObstacle : VersionedMonoBehaviour {
/** Mode of the obstacle.
* Determines winding order of the vertices */
public ObstacleVertexWinding obstacleMode;
public RVOLayer layer = RVOLayer.DefaultObstacle;
/** RVO Obstacle Modes.
* Determines winding order of obstacle vertices */
public enum ObstacleVertexWinding {
/** Keeps agents from entering the obstacle */
KeepOut,
/** Keeps agents inside the obstacle */
KeepIn,
}
/** Reference to simulator */
protected Pathfinding.RVO.Simulator sim;
/** All obstacles added */
private List<ObstacleVertex> addedObstacles;
/** Original vertices for the obstacles */
private List<Vector3[]> sourceObstacles;
/** Create Obstacles.
* Override this and add logic for creating obstacles.
* You should not use the simulator's function calls directly.
*
* \see AddObstacle
*/
protected abstract void CreateObstacles ();
/** Enable executing in editor to draw gizmos.
* If enabled, the CreateObstacles function will be executed in the editor as well
* in order to draw gizmos.
*/
protected abstract bool ExecuteInEditor { get; }
/** If enabled, all coordinates are handled as local.
*/
protected abstract bool LocalCoordinates { get; }
/** Static or dynamic.
* This determines if the obstacle can be updated by e.g moving the transform
* around in the scene.
*/
protected abstract bool StaticObstacle { get; }
protected abstract float Height { get; }
/** Called in the editor.
* This function should return true if any variables which can change the shape or position of the obstacle
* has changed since the last call to this function. Take a look at the RVOSquareObstacle for an example.
*/
protected abstract bool AreGizmosDirty ();
/** Enabled if currently in OnDrawGizmos */
private bool gizmoDrawing = false;
/** Vertices for gizmos */
private List<Vector3[]> gizmoVerts;
/** Last obstacle mode.
* Used to check if the gizmos should be updated
*/
private ObstacleVertexWinding _obstacleMode;
/** Last matrix the obstacle was updated with.
* Used to check if the obstacle should be updated */
private Matrix4x4 prevUpdateMatrix;
/** Draws Gizmos */
public void OnDrawGizmos () {
OnDrawGizmos(false);
}
/** Draws Gizmos */
public void OnDrawGizmosSelected () {
OnDrawGizmos(true);
}
/** Draws Gizmos */
public void OnDrawGizmos (bool selected) {
gizmoDrawing = true;
Gizmos.color = new Color(0.615f, 1, 0.06f, selected ? 1.0f : 0.7f);
var movementPlane = RVOSimulator.active != null ? RVOSimulator.active.movementPlane : MovementPlane.XZ;
var up = movementPlane == MovementPlane.XZ ? Vector3.up : -Vector3.forward;
if (gizmoVerts == null || AreGizmosDirty() || _obstacleMode != obstacleMode) {
_obstacleMode = obstacleMode;
if (gizmoVerts == null) gizmoVerts = new List<Vector3[]>();
else gizmoVerts.Clear();
CreateObstacles();
}
Matrix4x4 m = GetMatrix();
for (int i = 0; i < gizmoVerts.Count; i++) {
Vector3[] verts = gizmoVerts[i];
for (int j = 0, q = verts.Length-1; j < verts.Length; q = j++) {
Gizmos.DrawLine(m.MultiplyPoint3x4(verts[j]), m.MultiplyPoint3x4(verts[q]));
}
if (selected) {
for (int j = 0, q = verts.Length-1; j < verts.Length; q = j++) {
Vector3 a = m.MultiplyPoint3x4(verts[q]);
Vector3 b = m.MultiplyPoint3x4(verts[j]);
if (movementPlane != MovementPlane.XY) {
Gizmos.DrawLine(a + up*Height, b + up*Height);
Gizmos.DrawLine(a, a + up*Height);
}
Vector3 avg = (a + b) * 0.5f;
Vector3 tang = (b - a).normalized;
if (tang == Vector3.zero) continue;
Vector3 normal = Vector3.Cross(up, tang);
Gizmos.DrawLine(avg, avg+normal);
Gizmos.DrawLine(avg+normal, avg+normal*0.5f+tang*0.5f);
Gizmos.DrawLine(avg+normal, avg+normal*0.5f-tang*0.5f);
}
}
}
gizmoDrawing = false;
}
/** Get's the matrix to use for vertices.
* Can be overriden for custom matrices.
* \returns transform.localToWorldMatrix if LocalCoordinates is true, otherwise Matrix4x4.identity
*/
protected virtual Matrix4x4 GetMatrix () {
return LocalCoordinates ? transform.localToWorldMatrix : Matrix4x4.identity;
}
/** Disables the obstacle.
* Do not override this function
*/
public void OnDisable () {
if (addedObstacles != null) {
if (sim == null) throw new System.Exception("This should not happen! Make sure you are not overriding the OnEnable function");
for (int i = 0; i < addedObstacles.Count; i++) {
sim.RemoveObstacle(addedObstacles[i]);
}
}
}
/** Enabled the obstacle.
* Do not override this function
*/
public void OnEnable () {
if (addedObstacles != null) {
if (sim == null) throw new System.Exception("This should not happen! Make sure you are not overriding the OnDisable function");
for (int i = 0; i < addedObstacles.Count; i++) {
// Update height and layer
var vertex = addedObstacles[i];
var start = vertex;
do {
vertex.layer = layer;
vertex = vertex.next;
} while (vertex != start);
sim.AddObstacle(addedObstacles[i]);
}
}
}
/** Creates obstacles */
public void Start () {
addedObstacles = new List<ObstacleVertex>();
sourceObstacles = new List<Vector3[]>();
prevUpdateMatrix = GetMatrix();
CreateObstacles();
}
/** Updates obstacle if required.
* Checks for if the obstacle should be updated (e.g if it has moved) */
public void Update () {
Matrix4x4 m = GetMatrix();
if (m != prevUpdateMatrix) {
for (int i = 0; i < addedObstacles.Count; i++) {
sim.UpdateObstacle(addedObstacles[i], sourceObstacles[i], m);
}
prevUpdateMatrix = m;
}
}
/** Finds a simulator in the scene.
*
* Saves found simulator in #sim.
*
* \throws System.InvalidOperationException When no RVOSimulator could be found.
*/
protected void FindSimulator () {
if (RVOSimulator.active == null) throw new System.InvalidOperationException("No RVOSimulator could be found in the scene. Please add one to any GameObject");
sim = RVOSimulator.active.GetSimulator();
}
/** Adds an obstacle with the specified vertices.
* The vertices array might be changed by this function. */
protected void AddObstacle (Vector3[] vertices, float height) {
if (vertices == null) throw new System.ArgumentNullException("Vertices Must Not Be Null");
if (height < 0) throw new System.ArgumentOutOfRangeException("Height must be non-negative");
if (vertices.Length < 2) throw new System.ArgumentException("An obstacle must have at least two vertices");
if (sim == null) FindSimulator();
if (gizmoDrawing) {
var v = new Vector3[vertices.Length];
WindCorrectly(vertices);
System.Array.Copy(vertices, v, vertices.Length);
gizmoVerts.Add(v);
return;
}
if (vertices.Length == 2) {
AddObstacleInternal(vertices, height);
return;
}
WindCorrectly(vertices);
AddObstacleInternal(vertices, height);
}
/** Adds an obstacle.
* Winding is assumed to be correct and very little error checking is done.
*/
private void AddObstacleInternal (Vector3[] vertices, float height) {
addedObstacles.Add(sim.AddObstacle(vertices, height, GetMatrix(), layer));
sourceObstacles.Add(vertices);
}
/** Winds the vertices correctly.
* Winding order is determined from #obstacleMode.
*/
private void WindCorrectly (Vector3[] vertices) {
int leftmost = 0;
float leftmostX = float.PositiveInfinity;
var matrix = GetMatrix();
for (int i = 0; i < vertices.Length; i++) {
var x = matrix.MultiplyPoint3x4(vertices[i]).x;
if (x < leftmostX) {
leftmost = i;
leftmostX = x;
}
}
var p1 = matrix.MultiplyPoint3x4(vertices[(leftmost-1 + vertices.Length) % vertices.Length]);
var p2 = matrix.MultiplyPoint3x4(vertices[leftmost]);
var p3 = matrix.MultiplyPoint3x4(vertices[(leftmost+1) % vertices.Length]);
MovementPlane movementPlane;
if (sim != null) movementPlane = sim.movementPlane;
else if (RVOSimulator.active) movementPlane = RVOSimulator.active.movementPlane;
else movementPlane = MovementPlane.XZ;
if (movementPlane == MovementPlane.XY) {
p1.z = p1.y;
p2.z = p2.y;
p3.z = p3.y;
}
if (VectorMath.IsClockwiseXZ(p1, p2, p3) != (obstacleMode == ObstacleVertexWinding.KeepIn)) {
System.Array.Reverse(vertices);
}
}
}
}
| |
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 BoardGameWindmill.Areas.HelpPage.ModelDescriptions;
using BoardGameWindmill.Areas.HelpPage.Models;
namespace BoardGameWindmill.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);
}
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ASDOC
{
using System;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Response = Microsoft.Protocols.TestSuites.Common.Response;
/// <summary>
/// This scenario is designed to retrieve Document class items that match the criteria specified by the client through the Search command messages.
/// </summary>
[TestClass]
public class S01_SearchCommand : TestSuiteBase
{
#region Class initialize and cleanup
/// <summary>
/// Initialize the class.
/// </summary>
/// <param name="testContext">VSTS test context.</param>
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
/// <summary>
/// Clear the class.
/// </summary>
[ClassCleanup]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
/// <summary>
/// This test case is designed to verify server behavior when using Search command to search a visible folder with LinkId.
/// </summary>
[TestCategory("MSASDOC"), TestMethod()]
public void MSASDOC_S01_TC01_SearchCommand_VisibleFolderWithLinkId()
{
#region Client calls Search command to get document class value of a shared visible folder.
// Get search command response.
SearchResponse searchResponse = this.SearchCommand(Common.GetConfigurationPropertyValue("SharedVisibleFolder", Site));
Site.Assert.AreEqual<string>("1", searchResponse.ResponseData.Response.Store.Status, "The folder should be found.");
Site.Assert.AreEqual<int>(1, searchResponse.ResponseData.Response.Store.Result.Length, "Only one folder information should be returned.");
#endregion
for (int i = 0; i < searchResponse.ResponseData.Response.Store.Result[0].Properties.ItemsElementName.Length; i++)
{
if (searchResponse.ResponseData.Response.Store.Result[0].Properties.ItemsElementName[i] == Response.ItemsChoiceType6.IsFolder)
{
byte isFolder = (byte)searchResponse.ResponseData.Response.Store.Result[0].Properties.Items[i];
// Add the debug information.
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDOC_R47");
// Verify MS-ASDOC requirement: MS-ASDOC_R47
Site.CaptureRequirementIfAreEqual<byte>(
1,
isFolder,
47,
@"[In IsFolder] The value 1 means the item is a folder.");
}
if (searchResponse.ResponseData.Response.Store.Result[0].Properties.ItemsElementName[i] == Response.ItemsChoiceType6.IsHidden)
{
byte isHidden = (byte)searchResponse.ResponseData.Response.Store.Result[0].Properties.Items[i];
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDOC_R118");
// Verify MS-ASDOC requirement: MS-ASDOC_R118
Site.CaptureRequirementIfAreEqual<byte>(
0,
isHidden,
118,
@"[In IsHidden]The value 0 means the folder is not hidden.");
}
}
}
/// <summary>
/// This test case is designed to verify server behavior when using Search command to search a hidden folder with LinkId.
/// </summary>
[TestCategory("MSASDOC"), TestMethod()]
public void MSASDOC_S01_TC02_SearchCommand_HiddenFolderWithLinkId()
{
#region Client calls Search command to get document class value of a shared hidden folder.
// Get Search command response.
SearchResponse searchResponse = this.SearchCommand(Common.GetConfigurationPropertyValue("SharedHiddenFolder", Site));
Site.Assert.AreEqual<string>("1", searchResponse.ResponseData.Response.Store.Status, "The folder should be found.");
Site.Assert.AreEqual<int>(1, searchResponse.ResponseData.Response.Store.Result.Length, "Only one folder information should be returned.");
#endregion
for (int i = 0; i < searchResponse.ResponseData.Response.Store.Result[0].Properties.ItemsElementName.Length; i++)
{
if (searchResponse.ResponseData.Response.Store.Result[0].Properties.ItemsElementName[i] == Response.ItemsChoiceType6.IsHidden)
{
byte isHidden = (byte)searchResponse.ResponseData.Response.Store.Result[0].Properties.Items[i];
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDOC_R119");
// Verify MS-ASDOC requirement: MS-ASDOC_R119
Site.CaptureRequirementIfAreEqual<byte>(
1,
isHidden,
119,
@"[In IsHidden]The value 1 means the folder is hidden.");
}
}
}
/// <summary>
/// This test case is designed to verify server behavior when using Search command to retrieve data of a document without LinkId.
/// </summary>
[TestCategory("MSASDOC"), TestMethod()]
public void MSASDOC_S01_TC03_SearchCommand_WithoutLinkId()
{
#region Client calls Search command without LinkId.
// Get Search command response.
SearchResponse searchResponse = this.SearchCommand(null);
#endregion
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDOC_R85");
// Verify MS-ASDOC requirement: MS-ASDOC_R85
Site.CaptureRequirementIfAreEqual<string>(
"2",
searchResponse.ResponseData.Response.Store.Status,
85,
@"[In Search Command Request] If the LinkId element is not included in a Search command request, then the server MUST respond with protocol error 2.");
}
/// <summary>
/// This test case is designed to verify server behavior when using Search command to retrieve data of zero or more documents.
/// </summary>
[TestCategory("MSASDOC"), TestMethod()]
public void MSASDOC_S01_TC04_SearchCommand_GetZeroOrMoreDocumentClass()
{
#region Client calls Search command to get document class value of a folder that doesn't exist.
// Get Search command response.
SearchResponse searchGetZeroDocResponse = this.SearchCommand(Common.GetConfigurationPropertyValue("SharedFolder", Site) + Guid.NewGuid().ToString());
Site.Assert.IsNull(searchGetZeroDocResponse.ResponseData.Response.Store.Result, "Document class value should not be returned.");
#endregion
#region Client calls Search command to get document class value of a shared folder which is the root folder.
// Get Search command response.
SearchResponse searchGetMultipleDocResponse = this.SearchCommand(Common.GetConfigurationPropertyValue("SharedFolder", Site));
Site.Assert.AreEqual<string>("1", searchGetMultipleDocResponse.ResponseData.Response.Store.Status, "The folder should be found.");
// According to MS-ASCMD section 2.2.3.142.2 :If the documentlibrary:LinkId element value in the request points to a folder, the metadata properties of the folder are returned as the first item, and the contents of the folder are returned as subsequent results.
Site.Assert.IsTrue(searchGetMultipleDocResponse.ResponseData.Response.Store.Result.Length == 5, "Root folder and the contents of the folder should be returned.");
#endregion
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDOC_R112");
// Server can return zero or more documents class blocks which can be seen from two steps above.
Site.CaptureRequirement(
112,
@"[In Search Command Response] The server can return zero or more Document class blocks in its response, depending on how many document items match the criteria specified in the client command request.");
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDOC_R111");
// Items that match the criteria are returned.
Site.CaptureRequirement(
111,
@"[In Search Command Response] The server MUST return a Document class XML block for every item that matches the criteria specified in the client command request.");
}
/// <summary>
/// This test case is designed to verify server behavior when using Search command to search a visible document.
/// </summary>
[TestCategory("MSASDOC"), TestMethod()]
public void MSASDOC_S01_TC05_SearchCommand_VisibleDocument()
{
#region Client calls Search command to get document class value of a shared visible document.
// Get Search command response.
SearchResponse searchResponse = this.SearchCommand(Common.GetConfigurationPropertyValue("SharedVisibleDocument", Site));
Site.Assert.AreEqual<string>("1", searchResponse.ResponseData.Response.Store.Status, "Document class value should be returned.");
Site.Assert.AreEqual<int>(1, searchResponse.ResponseData.Response.Store.Result.Length, "Only one document information should be returned.");
#endregion
for (int i = 0; i < searchResponse.ResponseData.Response.Store.Result[0].Properties.ItemsElementName.Length; i++)
{
if (searchResponse.ResponseData.Response.Store.Result[0].Properties.ItemsElementName[i] == Response.ItemsChoiceType6.IsFolder)
{
byte isFolder = (byte)searchResponse.ResponseData.Response.Store.Result[0].Properties.Items[i];
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDOC_46");
// Verify MS-ASDOC requirement: MS-ASDOC_R46
Site.CaptureRequirementIfAreEqual<byte>(
0,
isFolder,
46,
@"[In IsFolder] The value 0 means the item is not a folder.");
}
if (searchResponse.ResponseData.Response.Store.Result[0].Properties.ItemsElementName[i] == Response.ItemsChoiceType6.IsHidden)
{
byte isHidden = (byte)searchResponse.ResponseData.Response.Store.Result[0].Properties.Items[i];
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDOC_R52");
// Verify MS-ASDOC requirement: MS-ASDOC_R52
Site.CaptureRequirementIfAreEqual<byte>(
0,
isHidden,
52,
@"[In IsHidden]The value 0 means the document is not hidden.");
}
}
}
/// <summary>
/// This test case is designed to verify server behavior when using Search command to search a Hidden document.
/// </summary>
[TestCategory("MSASDOC"), TestMethod()]
public void MSASDOC_S01_TC06_SearchCommand_HiddenDocument()
{
#region Client calls Search command to get document class value of a shared hidden document.
// Get Search command response.
SearchResponse searchResponse = this.SearchCommand(Common.GetConfigurationPropertyValue("SharedHiddenDocument", Site));
Site.Assert.AreEqual<string>("1", searchResponse.ResponseData.Response.Store.Status, "Document class value should be returned.");
Site.Assert.AreEqual<int>(1, searchResponse.ResponseData.Response.Store.Result.Length, "Only one document information should be returned.");
#endregion
for (int i = 0; i < searchResponse.ResponseData.Response.Store.Result[0].Properties.ItemsElementName.Length; i++)
{
if (searchResponse.ResponseData.Response.Store.Result[0].Properties.ItemsElementName[i] == Response.ItemsChoiceType6.IsHidden)
{
byte isHidden = (byte)searchResponse.ResponseData.Response.Store.Result[0].Properties.Items[i];
// Add the debug information
Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASDOC_R53");
// Verify MS-ASDOC requirement: MS-ASDOC_R53
Site.CaptureRequirementIfAreEqual<byte>(
1,
isHidden,
53,
@"[In IsHidden]The value 1 means the document is hidden.");
}
}
}
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// AccountOperations operations.
/// </summary>
internal partial class AccountOperations : IServiceOperations<BatchServiceClient>, IAccountOperations
{
/// <summary>
/// Initializes a new instance of the AccountOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal AccountOperations(BatchServiceClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the BatchServiceClient
/// </summary>
public BatchServiceClient Client { get; private set; }
/// <summary>
/// Lists all node agent SKUs supported by the Azure Batch service.
/// </summary>
/// <param name='accountListNodeAgentSkusOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>> ListNodeAgentSkusWithHttpMessagesAsync(AccountListNodeAgentSkusOptions accountListNodeAgentSkusOptions = default(AccountListNodeAgentSkusOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
string filter = default(string);
if (accountListNodeAgentSkusOptions != null)
{
filter = accountListNodeAgentSkusOptions.Filter;
}
int? maxResults = default(int?);
if (accountListNodeAgentSkusOptions != null)
{
maxResults = accountListNodeAgentSkusOptions.MaxResults;
}
int? timeout = default(int?);
if (accountListNodeAgentSkusOptions != null)
{
timeout = accountListNodeAgentSkusOptions.Timeout;
}
string clientRequestId = default(string);
if (accountListNodeAgentSkusOptions != null)
{
clientRequestId = accountListNodeAgentSkusOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (accountListNodeAgentSkusOptions != null)
{
returnClientRequestId = accountListNodeAgentSkusOptions.ReturnClientRequestId;
}
DateTime? ocpDate = default(DateTime?);
if (accountListNodeAgentSkusOptions != null)
{
ocpDate = accountListNodeAgentSkusOptions.OcpDate;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("filter", filter);
tracingParameters.Add("maxResults", maxResults);
tracingParameters.Add("timeout", timeout);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNodeAgentSkus", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "nodeagentskus").ToString();
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", Uri.EscapeDataString(filter)));
}
if (maxResults != null)
{
_queryParameters.Add(string.Format("maxresults={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(maxResults, this.Client.SerializationSettings).Trim('"'))));
}
if (timeout != null)
{
_queryParameters.Add(string.Format("timeout={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeout, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<NodeAgentSku>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<AccountListNodeAgentSkusHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all node agent SKUs supported by the Azure Batch service.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='accountListNodeAgentSkusNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>> ListNodeAgentSkusNextWithHttpMessagesAsync(string nextPageLink, AccountListNodeAgentSkusNextOptions accountListNodeAgentSkusNextOptions = default(AccountListNodeAgentSkusNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
string clientRequestId = default(string);
if (accountListNodeAgentSkusNextOptions != null)
{
clientRequestId = accountListNodeAgentSkusNextOptions.ClientRequestId;
}
bool? returnClientRequestId = default(bool?);
if (accountListNodeAgentSkusNextOptions != null)
{
returnClientRequestId = accountListNodeAgentSkusNextOptions.ReturnClientRequestId;
}
DateTime? ocpDate = default(DateTime?);
if (accountListNodeAgentSkusNextOptions != null)
{
ocpDate = accountListNodeAgentSkusNextOptions.OcpDate;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("clientRequestId", clientRequestId);
tracingParameters.Add("returnClientRequestId", returnClientRequestId);
tracingParameters.Add("ocpDate", ocpDate);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNodeAgentSkusNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (clientRequestId != null)
{
if (_httpRequest.Headers.Contains("client-request-id"))
{
_httpRequest.Headers.Remove("client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("client-request-id", clientRequestId);
}
if (returnClientRequestId != null)
{
if (_httpRequest.Headers.Contains("return-client-request-id"))
{
_httpRequest.Headers.Remove("return-client-request-id");
}
_httpRequest.Headers.TryAddWithoutValidation("return-client-request-id", SafeJsonConvert.SerializeObject(returnClientRequestId, this.Client.SerializationSettings).Trim('"'));
}
if (ocpDate != null)
{
if (_httpRequest.Headers.Contains("ocp-date"))
{
_httpRequest.Headers.Remove("ocp-date");
}
_httpRequest.Headers.TryAddWithoutValidation("ocp-date", SafeJsonConvert.SerializeObject(ocpDate, new DateTimeRfc1123JsonConverter()).Trim('"'));
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new BatchErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
BatchError _errorBody = SafeJsonConvert.DeserializeObject<BatchError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<NodeAgentSku>,AccountListNodeAgentSkusHeaders>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<NodeAgentSku>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<AccountListNodeAgentSkusHeaders>(JsonSerializer.Create(this.Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace Nwc.XmlRpc
{
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Xml;
/// <summary>A restricted HTTP server for use with XML-RPC.</summary>
/// <remarks>It only handles POST requests, and only POSTs representing XML-RPC calls.
/// In addition to dispatching requests it also provides a registry for request handlers.
/// </remarks>
public class XmlRpcServer : IEnumerable
{
#pragma warning disable 0414 // disable "private field assigned but not used"
const int RESPONDER_COUNT = 10;
private TcpListener _myListener;
private int _port;
private IPAddress _address;
private IDictionary _handlers;
private XmlRpcSystemObject _system;
private WaitCallback _wc;
#pragma warning restore 0414
///<summary>Constructor with port and address.</summary>
///<remarks>This constructor sets up a TcpListener listening on the
///given port and address. It also calls a Thread on the method StartListen().</remarks>
///<param name="address"><c>IPAddress</c> value of the address to listen on.</param>
///<param name="port"><c>Int</c> value of the port to listen on.</param>
public XmlRpcServer(IPAddress address, int port)
{
_port = port;
_address = address;
_handlers = new Hashtable();
_system = new XmlRpcSystemObject(this);
_wc = new WaitCallback(WaitCallback);
}
///<summary>Basic constructor.</summary>
///<remarks>This constructor sets up a TcpListener listening on the
///given port. It also calls a Thread on the method StartListen(). IPAddress.Any
///is assumed as the address here.</remarks>
///<param name="port"><c>Int</c> value of the port to listen on.</param>
public XmlRpcServer(int port) : this(IPAddress.Any, port) { }
/// <summary>Start the server.</summary>
public void Start()
{
try
{
Stop();
//start listing on the given port
// IPAddress addr = IPAddress.Parse("127.0.0.1");
lock (this)
{
_myListener = new TcpListener(IPAddress.Any, _port);
_myListener.Start();
//start the thread which calls the method 'StartListen'
Thread th = new Thread(new ThreadStart(StartListen));
th.Start();
}
}
catch (Exception e)
{
Logger.WriteEntry("An Exception Occurred while Listening :" + e.ToString(), LogLevel.Error);
}
}
/// <summary>Stop the server.</summary>
public void Stop()
{
try
{
if (_myListener != null)
{
lock (this)
{
_myListener.Stop();
_myListener = null;
}
}
}
catch (Exception e)
{
Logger.WriteEntry("An Exception Occurred while stopping :" +
e.ToString(), LogLevel.Error);
}
}
/// <summary>Get an enumeration of my XML-RPC handlers.</summary>
/// <returns><c>IEnumerable</c> the handler enumeration.</returns>
public IEnumerator GetEnumerator()
{
return _handlers.GetEnumerator();
}
/// <summary>Retrieve a handler by name.</summary>
/// <param name="name"><c>String</c> naming a handler</param>
/// <returns><c>Object</c> that is the handler.</returns>
public Object this[String name]
{
get { return _handlers[name]; }
}
///<summary>
///This method Accepts new connections and dispatches them when appropriate.
///</summary>
public void StartListen()
{
while (true && _myListener != null)
{
//Accept a new connection
XmlRpcResponder responder = new XmlRpcResponder(this, _myListener.AcceptTcpClient());
ThreadPool.QueueUserWorkItem(_wc, responder);
}
}
///<summary>
///Add an XML-RPC handler object by name.
///</summary>
///<param name="name"><c>String</c> XML-RPC dispatch name of this object.</param>
///<param name="obj"><c>Object</c> The object that is the XML-RPC handler.</param>
public void Add(String name, Object obj)
{
_handlers.Add(name, obj);
}
///<summary>Return a C# object.method name for and XML-RPC object.method name pair.</summary>
///<param name="methodName">The XML-RPC object.method.</param>
///<returns><c>String</c> of form object.method for the underlying C# method.</returns>
public String MethodName(String methodName)
{
int dotAt = methodName.LastIndexOf('.');
if (dotAt == -1)
{
throw new XmlRpcException(XmlRpcErrorCodes.SERVER_ERROR_METHOD,
XmlRpcErrorCodes.SERVER_ERROR_METHOD_MSG + ": Bad method name " + methodName);
}
String objectName = methodName.Substring(0, dotAt);
Object target = _handlers[objectName];
if (target == null)
{
throw new XmlRpcException(XmlRpcErrorCodes.SERVER_ERROR_METHOD,
XmlRpcErrorCodes.SERVER_ERROR_METHOD_MSG + ": Object " + objectName + " not found");
}
return target.GetType().FullName + "." + methodName.Substring(dotAt + 1);
}
///<summary>Invoke a method described in a request.</summary>
///<param name="req"><c>XmlRpcRequest</c> containing a method descriptions.</param>
/// <seealso cref="XmlRpcSystemObject.Invoke"/>
/// <seealso cref="XmlRpcServer.Invoke(String,String,IList)"/>
public Object Invoke(XmlRpcRequest req)
{
return Invoke(req.MethodNameObject, req.MethodNameMethod, req.Params);
}
///<summary>Invoke a method on a named handler.</summary>
///<param name="objectName"><c>String</c> The name of the handler.</param>
///<param name="methodName"><c>String</c> The name of the method to invoke on the handler.</param>
///<param name="parameters"><c>IList</c> The parameters to invoke the method with.</param>
/// <seealso cref="XmlRpcSystemObject.Invoke"/>
public Object Invoke(String objectName, String methodName, IList parameters)
{
Object target = _handlers[objectName];
if (target == null)
{
throw new XmlRpcException(XmlRpcErrorCodes.SERVER_ERROR_METHOD,
XmlRpcErrorCodes.SERVER_ERROR_METHOD_MSG + ": Object " + objectName + " not found");
}
return XmlRpcSystemObject.Invoke(target, methodName, parameters);
}
/// <summary>The method the thread pool invokes when a thread is available to handle an HTTP request.</summary>
/// <param name="responder">TcpClient from the socket accept.</param>
public void WaitCallback(object responder)
{
XmlRpcResponder resp = (XmlRpcResponder)responder;
if (resp.HttpReq.HttpMethod == "POST")
{
try
{
resp.Respond();
}
catch (Exception e)
{
Logger.WriteEntry("Failed on post: " + e, LogLevel.Error);
}
}
else
{
Logger.WriteEntry("Only POST methods are supported: " + resp.HttpReq.HttpMethod +
" ignored", LogLevel.Error);
}
resp.Close();
}
/// <summary>
/// This function send the Header Information to the client (Browser)
/// </summary>
/// <param name="sHttpVersion">HTTP Version</param>
/// <param name="sMIMEHeader">Mime Type</param>
/// <param name="iTotBytes">Total Bytes to be sent in the body</param>
/// <param name="sStatusCode"></param>
/// <param name="output">Socket reference</param>
static public void HttpHeader(string sHttpVersion, string sMIMEHeader, long iTotBytes, string sStatusCode, TextWriter output)
{
String sBuffer = "";
// if Mime type is not provided set default to text/html
if (sMIMEHeader.Length == 0)
{
sMIMEHeader = "text/html"; // Default Mime Type is text/html
}
sBuffer += sHttpVersion + sStatusCode + "\r\n";
sBuffer += "Connection: close\r\n";
if (iTotBytes > 0)
sBuffer += "Content-Length: " + iTotBytes + "\r\n";
sBuffer += "Server: XmlRpcServer \r\n";
sBuffer += "Content-Type: " + sMIMEHeader + "\r\n";
sBuffer += "\r\n";
output.Write(sBuffer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class TakesScreenshotTest : DriverTestFixture
{
[TearDown]
public void SwitchToTop()
{
driver.SwitchTo().DefaultContent();
}
[Test]
public void GetScreenshotAsFile()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = simpleTestPage;
string filename = Path.Combine(Path.GetTempPath(), "snapshot" + new Random().Next().ToString() + ".png");
Screenshot screenImage = screenshotCapableDriver.GetScreenshot();
screenImage.SaveAsFile(filename, ScreenshotImageFormat.Png);
Assert.That(File.Exists(filename), Is.True);
Assert.That(new FileInfo(filename).Length, Is.GreaterThan(0));
File.Delete(filename);
}
[Test]
public void GetScreenshotAsBase64()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = simpleTestPage;
Screenshot screenImage = screenshotCapableDriver.GetScreenshot();
string base64 = screenImage.AsBase64EncodedString;
Assert.That(base64.Length, Is.GreaterThan(0));
}
[Test]
public void GetScreenshotAsBinary()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = simpleTestPage;
Screenshot screenImage = screenshotCapableDriver.GetScreenshot();
byte[] bytes = screenImage.AsByteArray;
Assert.That(bytes.Length, Is.GreaterThan(0));
}
[Test]
public void ShouldCaptureScreenshotOfCurrentViewport()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step */ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
public void ShouldTakeScreenshotsOfAnElement()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html");
IWebElement element = driver.FindElement(By.Id("cell11"));
ITakesScreenshot screenshotCapableElement = element as ITakesScreenshot;
if (screenshotCapableElement == null)
{
return;
}
Screenshot screenImage = screenshotCapableElement.GetScreenshot();
byte[] imageData = screenImage.AsByteArray;
Assert.That(imageData, Is.Not.Null);
Assert.That(imageData.Length, Is.GreaterThan(0));
Color pixelColor = GetPixelColor(screenImage, 1, 1);
string pixelColorString = FormatColorToHex(pixelColor.ToArgb());
Assert.AreEqual("#0f12f7", pixelColorString);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")]
[IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")]
[IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")]
public void ShouldCaptureScreenshotOfPageWithLongX()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_long.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 50,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")]
[IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")]
[IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")]
public void ShouldCaptureScreenshotOfPageWithLongY()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_long.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 50);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")]
[IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")]
[IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")]
public void ShouldCaptureScreenshotOfPageWithTooLongX()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_too_long.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 100,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")]
[IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")]
[IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")]
public void ShouldCaptureScreenshotOfPageWithTooLongY()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_too_long.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 100);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")]
[IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")]
[IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")]
[IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")]
public void ShouldCaptureScreenshotOfPageWithTooLongXandY()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_too_long.html");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 100,
/* stepY in pixels */ 100);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
CompareColors(expectedColors, actualColors);
}
[Test]
public void ShouldCaptureScreenshotAtFramePage()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html");
WaitFor(FrameToBeAvailableAndSwitchedTo("frame1"), "Did not switch to frame1");
WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content");
driver.SwitchTo().DefaultContent();
WaitFor(FrameToBeAvailableAndSwitchedTo("frame2"), "Did not switch to frame2");
WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content");
driver.SwitchTo().DefaultContent();
WaitFor(TitleToBe("screen test"), "Title was not expected value");
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with frames will be taken for full page
CompareColors(expectedColors, actualColors);
}
[Test]
public void ShouldCaptureScreenshotAtIFramePage()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html");
// Resize the window to avoid scrollbars in screenshot
Size originalSize = driver.Manage().Window.Size;
driver.Manage().Window.Size = new Size(1040, 700);
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
driver.Manage().Window.Size = originalSize;
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with Iframes will be taken for full page
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")]
public void ShouldCaptureScreenshotAtFramePageAfterSwitching()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html");
driver.SwitchTo().Frame(driver.FindElement(By.Id("frame2")));
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with frames after switching to a frame
// will be taken for full page
CompareColors(expectedColors, actualColors);
}
[Test]
[IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")]
public void ShouldCaptureScreenshotAtIFramePageAfterSwitching()
{
ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot;
if (screenshotCapableDriver == null)
{
return;
}
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html");
// Resize the window to avoid scrollbars in screenshot
Size originalSize = driver.Manage().Window.Size;
driver.Manage().Window.Size = new Size(1040, 700);
driver.SwitchTo().Frame(driver.FindElement(By.Id("iframe2")));
Screenshot screenshot = screenshotCapableDriver.GetScreenshot();
driver.Manage().Window.Size = originalSize;
HashSet<string> actualColors = ScanActualColors(screenshot,
/* stepX in pixels */ 5,
/* stepY in pixels */ 5);
HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6);
expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF,
/* color step*/ 1000,
/* grid X size */ 6,
/* grid Y size */ 6));
// expectation is that screenshot at page with Iframes after switching to a Iframe
// will be taken for full page
CompareColors(expectedColors, actualColors);
}
private string FormatColorToHex(int colorValue)
{
string pixelColorString = string.Format("#{0:x2}{1:x2}{2:x2}", (colorValue & 0xFF0000) >> 16, (colorValue & 0x00FF00) >> 8, (colorValue & 0x0000FF));
return pixelColorString;
}
private void CompareColors(HashSet<string> expectedColors, HashSet<string> actualColors)
{
// Ignore black and white for further comparison
actualColors.Remove("#000000");
actualColors.Remove("#ffffff");
Assert.That(actualColors, Is.EquivalentTo(expectedColors));
}
private HashSet<string> GenerateExpectedColors(int initialColor, int stepColor, int numberOfSamplesX, int numberOfSamplesY)
{
HashSet<string> colors = new HashSet<string>();
int count = 1;
for (int i = 1; i < numberOfSamplesX; i++)
{
for (int j = 1; j < numberOfSamplesY; j++)
{
int color = initialColor + (count * stepColor);
string hex = FormatColorToHex(color);
colors.Add(hex);
count++;
}
}
return colors;
}
private HashSet<string> ScanActualColors(Screenshot screenshot, int stepX, int stepY)
{
HashSet<string> colors = new HashSet<string>();
#if !NETCOREAPP3_1 && !NETSTANDARD2_1 && !NET5_0
try
{
Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray));
Bitmap bitmap = new Bitmap(image);
int height = bitmap.Height;
int width = bitmap.Width;
Assert.That(width, Is.GreaterThan(0));
Assert.That(height, Is.GreaterThan(0));
for (int i = 0; i < width; i = i + stepX)
{
for (int j = 0; j < height; j = j + stepY)
{
string hex = FormatColorToHex(bitmap.GetPixel(i, j).ToArgb());
colors.Add(hex);
}
}
}
catch (Exception e)
{
Assert.Fail("Unable to get actual colors from screenshot: " + e.Message);
}
Assert.That(colors.Count, Is.GreaterThan(0));
#endif
return colors;
}
private Color GetPixelColor(Screenshot screenshot, int x, int y)
{
Color pixelColor = Color.Black;
#if !NETCOREAPP3_1 && !NETSTANDARD2_1 && !NET5_0
Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray));
Bitmap bitmap = new Bitmap(image);
pixelColor = bitmap.GetPixel(1, 1);
#endif
return pixelColor;
}
private Func<bool> FrameToBeAvailableAndSwitchedTo(string frameId)
{
return () =>
{
try
{
IWebElement frameElement = driver.FindElement(By.Id(frameId));
driver.SwitchTo().Frame(frameElement);
}
catch(Exception)
{
return false;
}
return true;
};
}
private Func<bool> ElementToBeVisibleWithId(string elementId)
{
return () =>
{
try
{
IWebElement element = driver.FindElement(By.Id(elementId));
return element.Displayed;
}
catch(Exception)
{
return false;
}
};
}
private Func<bool> TitleToBe(string desiredTitle)
{
return () => driver.Title == desiredTitle;
}
}
}
| |
using System;
using System.Net;
using System.Text;
using System.IO;
using System.Xml;
namespace GoogleReaderNotifier.ReaderAPI
{
/// <summary>
/// Summary description for GoogleReader.
/// </summary>
public class GoogleReader
{
#region Private variables
private CookieCollection _Cookies = new CookieCollection();
private CookieContainer _cookiesContainer = new CookieContainer();
private bool _loggedIn = false;
private int _totalCount = 0;
private string _tagCount = "";
#endregion
public int TotalCount
{
get{return _totalCount;}
set{_totalCount = value;}
}
public string TagCount
{
get{return _tagCount;}
set{_tagCount = value;}
}
#region Application Code
// https://www.google.com/reader/atom/user/-/state/com.google/reading-list // get full feed of items
public string GetDetailedCount(string username, string password, string filters)
{
//verify login
if(!_loggedIn)
{
string loginResult = this.Login(username, password);
if(loginResult != string.Empty)
return loginResult;
}
//get the counts from google
XmlDocument xdoc = this.GetUnreadCounts();
string detailedcount = "";
// if filters are set, then don't check the regular unread items
if(filters.Trim().Length == 0)
{
this._totalCount = this.CountAllFeeds(xdoc);
}
else
{
this._totalCount = this.CountFilteredFeeds(xdoc, filters, ref detailedcount);
}
detailedcount = this._totalCount.ToString() + " unread items" + Environment.NewLine + detailedcount;
this.TagCount = detailedcount;
return detailedcount;
}
string auth_head_string; // authorization string, got from Login() "Auth=" field.
public string Login(string username, string password)
{
auth_head_string = null;
HttpWebRequest req = CreateRequest("https://www.google.com/accounts/ClientLogin");
PostLoginForm(req, String.Format(
"accountType=HOSTED_OR_GOOGLE&Email={0}&Passwd={1}&service=reader&source=GRN_mod&continue=https://www.google.com/reader",
Uri.EscapeDataString(username),
Uri.EscapeDataString(password)));
var resString = GetResponseString(req);
if(resString.IndexOf("SID=") != -1)
{
foreach(var line in resString.Split('\n'))
{
if(line.StartsWith("SID="))
_Cookies.Add(new Cookie("SID", line.Substring(4)));
if (line.StartsWith("LSID="))
_Cookies.Add(new Cookie("LSID", line.Substring(5)));
if (line.StartsWith("Auth="))
auth_head_string = line.Substring(5);
if (line.StartsWith("HSID="))
_Cookies.Add(new Cookie("HSID", line.Substring(5)));
}
_loggedIn = true;
return string.Empty;
}
else
{
return "AUTH_ERROR";
}
}
private XmlDocument GetUnreadCounts()
{
string url = "https://www.google.com/reader/api/0/unread-count?all=true";
string theXml = GetResponseString(CreateRequest(url));
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(theXml);
return xdoc;
}
private int CountAllFeeds(XmlDocument xdoc)
{
int totalFeeds = 0;
foreach(XmlNode node in xdoc.SelectNodes("//object/string[contains(.,'feed/http')]"))
{
int thenumber = Convert.ToInt32(node.ParentNode.SelectSingleNode("number").InnerText);
totalFeeds += thenumber;
}
return totalFeeds;
}
private int CountFilteredFeeds(XmlDocument xdoc, string filters, ref string filterBreakdown)
{
// filters have been set, check here for just the tagged items.
string[] filterlist = filters.Split(" ".ToCharArray());
int totalFeeds = 0;
foreach(XmlNode node in xdoc.SelectNodes("//object/string[contains(.,'/label/') and contains(.,'user/')]"))
{
string thelabel = node.InnerText.Substring(node.InnerText.LastIndexOf("/")+1); //user/10477630455154158284/label/food
foreach(string thefilter in filterlist)
{
if(thefilter == thelabel)
{
int thenumber = Convert.ToInt32(node.ParentNode.SelectSingleNode("number").InnerText);
totalFeeds += thenumber;
if(thenumber > 0)
{
filterBreakdown += thenumber.ToString() + " in " + thelabel + Environment.NewLine;
}
}
}
}
return totalFeeds;
}
#endregion
#region HTTP Functions
private string GetResponseString(HttpWebRequest req)
{
string responseString = null;
try
{
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
res.Cookies = req.CookieContainer.GetCookies(req.RequestUri);
_Cookies.Add(res.Cookies);
using (StreamReader read = new StreamReader(res.GetResponseStream()))
{
responseString = read.ReadToEnd();
}
res.Close();
//_currentHTML = responseString;
}
catch (Exception ex)
{
string exc = ex.ToString();
}
return responseString;
}
private void PostLoginForm(HttpWebRequest req, string p)
{
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//req.Referer = _currentURL;
byte[] b = Encoding.UTF8.GetBytes(p);
req.ContentLength = b.Length;
using (Stream s = req.GetRequestStream())
{
s.Write(b, 0, b.Length);
s.Close();
}
}
private HttpWebRequest CreateRequest(string url)
{
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
WebProxy defaultProxy = WebProxy.GetDefaultProxy();
_cookiesContainer.Add(new Uri(url, UriKind.Absolute), _Cookies);
// add request header: Authorization field, GoogleLogin auth=[login auth string]...
if(!string.IsNullOrEmpty(auth_head_string))
req.Headers.Add("Authorization", "GoogleLogin auth=" + auth_head_string);
req.Proxy = defaultProxy;
//req.UserAgent = _user.UserAgent;
req.CookieContainer = _cookiesContainer;
//req.Referer = _currentURL; // set the referring url properly to appear as a regular browser
//_currentURL = url; // set the current url so the next request will have the right referring url ( might not work for sub pages )
return req;
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Collections;
using SmartFile.Errors;
namespace SmartFile
{
namespace Errors
{
public class APIError : Exception
{
public APIError(string message)
{
}
}
public class RequestError : APIError
{
public RequestError(string message)
: base(message)
{
}
}
public class ResponseError : APIError
{
private WebException error;
public ResponseError(WebException e)
: base("Server responded with error")
{
this.error = e;
}
public int StatusCode
{
get
{
return (int)this.error.Status;
}
}
public WebResponse Response
{
get
{
return this.error.Response;
}
}
}
}
internal class Util
{
internal class PostItem
{
public string Name;
public string Data;
public string Boundary;
protected byte[] _header = null;
protected PostItem(string name, string boundary)
{
this.Name = name;
this.Boundary = boundary;
}
public PostItem(string name, string data, string boundary)
: this(name, boundary)
{
this.Data = data;
}
public virtual byte[] Header
{
get
{
if (this._header == null)
{
this._header = UTF8Encoding.UTF8.GetBytes(
string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n",
this.Boundary, this.Name));
}
return this._header;
}
}
public virtual long Length
{
get
{
long length = 0;
length += this.Header.LongLength;
length += UTF8Encoding.UTF8.GetBytes(this.Data).Length;
return length;
}
}
}
internal class PostFile : PostItem
{
public new FileInfo Data;
public string ContentType = "application/octet-stream";
public PostFile(string name, FileInfo data, string boundary)
: base(name, boundary)
{
this.Data = data;
}
public PostFile(string name, FileInfo data, string boundary, string contentType)
: this(name, data, boundary)
{
this.ContentType = contentType;
}
public override byte[] Header
{
get
{
if (this._header == null)
{
this._header = UTF8Encoding.UTF8.GetBytes(
string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n",
this.Boundary, this.Name, this.Data.Name, this.ContentType));
}
return this._header;
}
}
public override long Length
{
get
{
long length = 0;
length += this.Header.LongLength;
length += this.Data.Length;
return length;
}
}
public FileStream OpenRead()
{
return this.Data.OpenRead();
}
}
public static string CleanToken(string token)
{
if (string.IsNullOrEmpty(token))
{
throw new APIError("null or empty");
}
token = token.Trim();
if (token.Length < 30)
{
throw new APIError("too short");
}
return token;
}
public static string UrlEncode(Hashtable data)
{
string pre = "";
StringBuilder enc = new StringBuilder();
foreach (string key in data.Keys)
{
enc.AppendFormat("{0}{1}={2}", pre, key,
HttpUtility.UrlEncode(data[key].ToString()));
pre = "&";
}
return enc.ToString();
}
public static void HttpForm(HttpWebRequest request, Hashtable data)
{
// No files, use simple form encoding.
byte[] postBytes = UTF8Encoding.UTF8.GetBytes(Util.UrlEncode(data));
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postBytes, 0, postBytes.Length);
}
}
public static void HttpMultipart(HttpWebRequest request, Hashtable data, Hashtable files)
{
// We have files, so use the more complex multipart encoding.
string boundary = string.Format("{0}",
DateTime.Now.Ticks.ToString("x"));
request.ContentType = string.Format("multipart/form-data; boundary={0}",
boundary);
ArrayList items = new ArrayList();
// Determine the amount of data we will be sending
long length = 0;
foreach (string key in data.Keys)
{
PostItem item = new PostItem(key, data[key].ToString(), boundary);
items.Add(item);
length += item.Length;
}
foreach (string key in files.Keys)
{
PostFile file = new PostFile(key, (FileInfo)files[key], boundary);
items.Add(file);
length += file.Length;
}
length += boundary.Length + 8;
request.ContentLength = length;
// Now stream the data.
//using (Stream requestStream = File.Create("c:\\Users\\bneely\\documents\\debug.txt"))
using (Stream requestStream = request.GetRequestStream())
{
foreach (PostItem item in items)
{
requestStream.Write(item.Header, 0, item.Header.Length);
if (item.GetType() == typeof(PostFile))
{
FileStream fileData = ((PostFile)item).OpenRead();
byte[] buffer = new byte[32768];
int read = 0;
while ((read = fileData.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, read);
}
}
else
{
byte[] itemData = UTF8Encoding.UTF8.GetBytes(item.Data);
requestStream.Write(itemData, 0, itemData.Length);
}
}
byte[] end = UTF8Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", boundary));
requestStream.Write(end, 0, end.Length);
}
}
public static void HttpSendData(HttpWebRequest request, Hashtable data)
{
// Find files, and move them to a separate handler.
Hashtable files = new Hashtable();
string[] keys = new string[data.Keys.Count];
data.Keys.CopyTo(keys, 0);
foreach (string key in keys)
{
object obj = data[key];
if (obj.GetType() == typeof(FileInfo))
{
files[key] = obj;
data.Remove(key);
if (data.Keys.Count <= 0)
break;
}
}
if (files.Count == 0)
{
Util.HttpForm(request, data);
}
else
{
Util.HttpMultipart(request, data, files);
}
}
}
public abstract class Client
{
protected const string API_URL = "https://app.smartfile.com/";
protected const string API_VER = "2"; //2.1 -- for latest version, do not use subversion
protected const string HTTP_USER_AGENT = "SmartFile C# API client v{0}";
protected const string THROTTLE_PATTERN = "^.*; next=([\\d\\.]+) sec$";
public string url;
public string version;
public bool throttleWait;
public Regex throttleRegex;
public Client(string url = null, string version = API_VER, bool throttleWait = true)
{
if (url == null)
{
url = API_URL;
}
this.url = url;
this.version = version;
this.throttleWait = throttleWait;
this.throttleRegex = new Regex(THROTTLE_PATTERN);
}
protected virtual HttpWebResponse _DoRequest(HttpWebRequest request, Hashtable data)
{
HttpWebResponse response;
try
{
if (data != null)
{
Util.HttpSendData(request, data);
}
response = request.GetResponse() as HttpWebResponse;
}
catch (WebException e)
{
throw new ResponseError(e);
}
// figure out the return type we want...
return response;
}
protected HttpWebResponse _Request(string method, string endpoint, object id = null, Hashtable data = null, Hashtable query = null)
{
ArrayList parts = new ArrayList();
parts.Add("api");
parts.Add(this.version);
parts.Add(endpoint);
if (id != null)
parts.Add(id.ToString());
string path = string.Join("/", (string[])parts.ToArray(typeof(string)));
if (!path.EndsWith("/"))
path += "/";
while (path.Contains("//"))
path = path.Replace("//", "/");
StringBuilder url = new StringBuilder();
url.Append(this.url);
url.Append(path);
if (query != null)
{
url.Append(Util.UrlEncode(query));
}
HttpWebRequest request = HttpWebRequest.Create(url.ToString()) as HttpWebRequest;
request.Method = method;
request.UserAgent = string.Format(HTTP_USER_AGENT, this.version);
int trys = 0;
for (; trys < 3; trys++)
{
try
{
return this._DoRequest(request, data);
}
catch (ResponseError e)
{
if (this.throttleWait && e.StatusCode == 503)
{
string throttleHeader = e.Response.Headers.Get("x-throttle");
if (!string.IsNullOrEmpty(throttleHeader))
{
float wait;
Match m = this.throttleRegex.Match(throttleHeader);
if (float.TryParse(m.Groups[1].Value, out wait))
{
Thread.Sleep((int)(wait * 1000));
continue;
}
}
}
throw e;
}
}
throw new RequestError(string.Format("Could not complete request after {0} trys.", trys));
}
public HttpWebResponse Get(string endpoint, object id = null, Hashtable data = null)
{
return this._Request("GET", endpoint, id, query: data);
}
public HttpWebResponse Put(string endpoint, object id = null, Hashtable data = null)
{
return this._Request("PUT", endpoint, id, data: data);
}
public HttpWebResponse Post(string endpoint, object id = null, Hashtable data = null)
{
return this._Request("POST", endpoint, id, data: data);
}
public HttpWebResponse Delete(string endpoint, object id = null, Hashtable data = null)
{
return this._Request("DELETE", endpoint, id, data: data);
}
}
public class BasicClient : Client
{
private string key;
private string password;
public BasicClient(string key = null, string password = null, string url = null, string version = Client.API_VER, bool throttleWait = true)
{
if (key == null)
{
key = Environment.GetEnvironmentVariable("SMARTFILE_API_KEY");
}
if (password == null)
{
password = Environment.GetEnvironmentVariable("SMARTFILE_API_PASSWORD");
}
try
{
this.key = Util.CleanToken(key);
this.password = Util.CleanToken(password);
}
catch (APIError)
{
throw new APIError("Please provide an API key and password. Use arguments or environment variables.");
}
}
protected override HttpWebResponse _DoRequest(HttpWebRequest request, Hashtable data)
{
string authInfo = this.key + ":" + this.password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
return base._DoRequest(request, data);
}
}
}
| |
//
// linq.cs: support for query expressions
//
// Authors: Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2007-2008 Novell, Inc
// Copyright 2011 Xamarin Inc
//
using System;
using System.Collections.Generic;
namespace Mono.CSharp.Linq
{
public class QueryExpression : AQueryClause
{
public QueryExpression (AQueryClause start)
: base (null, null, start.Location)
{
this.next = start;
}
public override Expression BuildQueryClause (ResolveContext ec, Expression lSide, Parameter parentParameter)
{
return next.BuildQueryClause (ec, lSide, parentParameter);
}
protected override Expression DoResolve (ResolveContext ec)
{
int counter = QueryBlock.TransparentParameter.Counter;
Expression e = BuildQueryClause (ec, null, null);
if (e != null)
e = e.Resolve (ec);
//
// Reset counter in probing mode to ensure that all transparent
// identifier anonymous types are created only once
//
if (ec.IsInProbingMode)
QueryBlock.TransparentParameter.Counter = counter;
return e;
}
protected override string MethodName {
get { throw new NotSupportedException (); }
}
}
public abstract class AQueryClause : ShimExpression
{
protected class QueryExpressionAccess : MemberAccess
{
public QueryExpressionAccess (Expression expr, string methodName, Location loc)
: base (expr, methodName, loc)
{
}
public QueryExpressionAccess (Expression expr, string methodName, TypeArguments typeArguments, Location loc)
: base (expr, methodName, typeArguments, loc)
{
}
public override void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
{
ec.Report.Error (1935, loc, "An implementation of `{0}' query expression pattern could not be found. " +
"Are you missing `System.Linq' using directive or `System.Core.dll' assembly reference?",
name);
}
}
protected class QueryExpressionInvocation : Invocation, OverloadResolver.IErrorHandler
{
public QueryExpressionInvocation (QueryExpressionAccess expr, Arguments arguments)
: base (expr, arguments)
{
}
protected override MethodGroupExpr DoResolveOverload (ResolveContext rc)
{
using (rc.Set (ResolveContext.Options.QueryClauseScope)) {
return mg.OverloadResolve (rc, ref arguments, this, OverloadResolver.Restrictions.None);
}
}
protected override Expression DoResolveDynamic (ResolveContext ec, Expression memberExpr)
{
ec.Report.Error (1979, loc,
"Query expressions with a source or join sequence of type `dynamic' are not allowed");
return null;
}
#region IErrorHandler Members
bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
{
var emg = mg as ExtensionMethodGroupExpr;
var type = emg == null ? mg.InstanceExpression : emg.ExtensionExpression;
ec.Report.SymbolRelatedToPreviousError (best);
ec.Report.SymbolRelatedToPreviousError (ambiguous);
ec.Report.Error (1940, loc, "Ambiguous implementation of the query pattern `{0}' for source type `{1}'",
best.Name, type.Type.GetSignatureForError ());
return true;
}
bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
{
return false;
}
bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
{
return false;
}
bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
{
var ms = (MethodSpec) best;
TypeSpec source_type = ms.Parameters.ExtensionMethodType;
if (source_type != null) {
Argument a = arguments[0];
if (TypeManager.IsGenericType (source_type) && InflatedTypeSpec.ContainsTypeParameter (source_type)) {
TypeInferenceContext tic = new TypeInferenceContext (source_type.TypeArguments);
tic.OutputTypeInference (rc, a.Expr, source_type);
if (tic.FixAllTypes (rc)) {
source_type = source_type.GetDefinition ().MakeGenericType (rc, tic.InferredTypeArguments);
}
}
if (!Convert.ImplicitConversionExists (rc, a.Expr, source_type)) {
rc.Report.Error (1936, loc, "An implementation of `{0}' query expression pattern for source type `{1}' could not be found",
best.Name, a.Type.GetSignatureForError ());
return true;
}
}
if (best.Name == "SelectMany") {
rc.Report.Error (1943, loc,
"An expression type is incorrect in a subsequent `from' clause in a query expression with source type `{0}'",
arguments[0].GetSignatureForError ());
} else {
rc.Report.Error (1942, loc,
"An expression type in `{0}' clause is incorrect. Type inference failed in the call to `{1}'",
best.Name.ToLowerInvariant (), best.Name);
}
return true;
}
#endregion
}
public AQueryClause next;
public QueryBlock block;
protected AQueryClause (QueryBlock block, Expression expr, Location loc)
: base (expr)
{
this.block = block;
this.loc = loc;
}
protected override void CloneTo (CloneContext clonectx, Expression target)
{
base.CloneTo (clonectx, target);
AQueryClause t = (AQueryClause) target;
if (block != null)
t.block = (QueryBlock) clonectx.LookupBlock (block);
if (next != null)
t.next = (AQueryClause) next.Clone (clonectx);
}
protected override Expression DoResolve (ResolveContext ec)
{
return expr.Resolve (ec);
}
public virtual Expression BuildQueryClause (ResolveContext ec, Expression lSide, Parameter parameter)
{
Arguments args = null;
CreateArguments (ec, parameter, ref args);
lSide = CreateQueryExpression (lSide, args);
if (next != null) {
parameter = CreateChildrenParameters (parameter);
Select s = next as Select;
if (s == null || s.IsRequired (parameter))
return next.BuildQueryClause (ec, lSide, parameter);
// Skip transparent select clause if any clause follows
if (next.next != null)
return next.next.BuildQueryClause (ec, lSide, parameter);
}
return lSide;
}
protected virtual Parameter CreateChildrenParameters (Parameter parameter)
{
// Have to clone the parameter for any children use, it carries block sensitive data
return parameter.Clone ();
}
protected virtual void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args)
{
args = new Arguments (2);
LambdaExpression selector = new LambdaExpression (loc);
block.SetParameter (parameter);
selector.Block = block;
selector.Block.AddStatement (new ContextualReturn (expr));
args.Add (new Argument (selector));
}
protected Invocation CreateQueryExpression (Expression lSide, Arguments arguments)
{
return new QueryExpressionInvocation (
new QueryExpressionAccess (lSide, MethodName, loc), arguments);
}
protected abstract string MethodName { get; }
public AQueryClause Next {
set {
next = value;
}
}
public AQueryClause Tail {
get {
return next == null ? this : next.Tail;
}
}
}
//
// A query clause with an identifier (range variable)
//
public abstract class ARangeVariableQueryClause : AQueryClause
{
sealed class RangeAnonymousTypeParameter : AnonymousTypeParameter
{
public RangeAnonymousTypeParameter (Expression initializer, RangeVariable parameter)
: base (initializer, parameter.Name, parameter.Location)
{
}
protected override void Error_InvalidInitializer (ResolveContext ec, string initializer)
{
ec.Report.Error (1932, loc, "A range variable `{0}' cannot be initialized with `{1}'",
Name, initializer);
}
}
class RangeParameterReference : ParameterReference
{
Parameter parameter;
public RangeParameterReference (Parameter p)
: base (null, p.Location)
{
this.parameter = p;
}
protected override Expression DoResolve (ResolveContext ec)
{
pi = ec.CurrentBlock.ParametersBlock.GetParameterInfo (parameter);
return base.DoResolve (ec);
}
}
protected RangeVariable identifier;
protected ARangeVariableQueryClause (QueryBlock block, RangeVariable identifier, Expression expr, Location loc)
: base (block, expr, loc)
{
this.identifier = identifier;
}
public RangeVariable Identifier {
get {
return identifier;
}
}
public FullNamedExpression IdentifierType { get; set; }
protected Invocation CreateCastExpression (Expression lSide)
{
return new QueryExpressionInvocation (
new QueryExpressionAccess (lSide, "Cast", new TypeArguments (IdentifierType), loc), null);
}
protected override Parameter CreateChildrenParameters (Parameter parameter)
{
return new QueryBlock.TransparentParameter (parameter.Clone (), GetIntoVariable ());
}
protected static Expression CreateRangeVariableType (ResolveContext rc, Parameter parameter, RangeVariable name, Expression init)
{
var args = new List<AnonymousTypeParameter> (2);
//
// The first argument is the reference to the parameter
//
args.Add (new AnonymousTypeParameter (new RangeParameterReference (parameter), parameter.Name, parameter.Location));
//
// The second argument is the linq expression
//
args.Add (new RangeAnonymousTypeParameter (init, name));
//
// Create unique anonymous type
//
return new NewAnonymousType (args, rc.MemberContext.CurrentMemberDefinition.Parent, name.Location);
}
protected virtual RangeVariable GetIntoVariable ()
{
return identifier;
}
}
public sealed class RangeVariable : INamedBlockVariable
{
Block block;
public RangeVariable (string name, Location loc)
{
Name = name;
Location = loc;
}
#region Properties
public Block Block {
get {
return block;
}
set {
block = value;
}
}
public bool IsDeclared {
get {
return true;
}
}
public bool IsParameter {
get {
return false;
}
}
public Location Location { get; private set; }
public string Name { get; private set; }
#endregion
public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
{
//
// We know the variable name is somewhere in the scope. This generates
// an access expression from current block
//
var pb = rc.CurrentBlock.ParametersBlock;
while (true) {
if (pb is QueryBlock) {
for (int i = pb.Parameters.Count - 1; i >= 0; --i) {
var p = pb.Parameters[i];
if (p.Name == Name)
return pb.GetParameterReference (i, loc);
Expression expr = null;
var tp = p as QueryBlock.TransparentParameter;
while (tp != null) {
if (expr == null)
expr = pb.GetParameterReference (i, loc);
else
expr = new TransparentMemberAccess (expr, tp.Name);
if (tp.Identifier == Name)
return new TransparentMemberAccess (expr, Name);
if (tp.Parent.Name == Name)
return new TransparentMemberAccess (expr, Name);
tp = tp.Parent as QueryBlock.TransparentParameter;
}
}
}
if (pb == block)
return null;
pb = pb.Parent.ParametersBlock;
}
}
}
public class QueryStartClause : ARangeVariableQueryClause
{
public QueryStartClause (QueryBlock block, Expression expr, RangeVariable identifier, Location loc)
: base (block, identifier, expr, loc)
{
block.AddRangeVariable (identifier);
}
public override Expression BuildQueryClause (ResolveContext ec, Expression lSide, Parameter parameter)
{
if (IdentifierType != null)
expr = CreateCastExpression (expr);
if (parameter == null)
lSide = expr;
return next.BuildQueryClause (ec, lSide, new ImplicitLambdaParameter (identifier.Name, identifier.Location));
}
protected override Expression DoResolve (ResolveContext ec)
{
Expression e = BuildQueryClause (ec, null, null);
return e.Resolve (ec);
}
protected override string MethodName {
get { throw new NotSupportedException (); }
}
}
public class GroupBy : AQueryClause
{
Expression element_selector;
QueryBlock element_block;
public GroupBy (QueryBlock block, Expression elementSelector, QueryBlock elementBlock, Expression keySelector, Location loc)
: base (block, keySelector, loc)
{
//
// Optimizes clauses like `group A by A'
//
if (!elementSelector.Equals (keySelector)) {
this.element_selector = elementSelector;
this.element_block = elementBlock;
}
}
public Expression SelectorExpression {
get {
return element_selector;
}
}
protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args)
{
base.CreateArguments (ec, parameter, ref args);
if (element_selector != null) {
LambdaExpression lambda = new LambdaExpression (element_selector.Location);
element_block.SetParameter (parameter.Clone ());
lambda.Block = element_block;
lambda.Block.AddStatement (new ContextualReturn (element_selector));
args.Add (new Argument (lambda));
}
}
protected override void CloneTo (CloneContext clonectx, Expression target)
{
GroupBy t = (GroupBy) target;
if (element_selector != null) {
t.element_selector = element_selector.Clone (clonectx);
t.element_block = (QueryBlock) element_block.Clone (clonectx);
}
base.CloneTo (clonectx, t);
}
protected override string MethodName {
get { return "GroupBy"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Join : SelectMany
{
QueryBlock inner_selector, outer_selector;
public Join (QueryBlock block, RangeVariable lt, Expression inner, QueryBlock outerSelector, QueryBlock innerSelector, Location loc)
: base (block, lt, inner, loc)
{
this.outer_selector = outerSelector;
this.inner_selector = innerSelector;
}
public QueryBlock InnerSelector {
get {
return inner_selector;
}
}
public QueryBlock OuterSelector {
get {
return outer_selector;
}
}
protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args)
{
args = new Arguments (4);
if (IdentifierType != null)
expr = CreateCastExpression (expr);
args.Add (new Argument (expr));
outer_selector.SetParameter (parameter.Clone ());
var lambda = new LambdaExpression (outer_selector.StartLocation);
lambda.Block = outer_selector;
args.Add (new Argument (lambda));
inner_selector.SetParameter (new ImplicitLambdaParameter (identifier.Name, identifier.Location));
lambda = new LambdaExpression (inner_selector.StartLocation);
lambda.Block = inner_selector;
args.Add (new Argument (lambda));
base.CreateArguments (ec, parameter, ref args);
}
protected override void CloneTo (CloneContext clonectx, Expression target)
{
Join t = (Join) target;
t.inner_selector = (QueryBlock) inner_selector.Clone (clonectx);
t.outer_selector = (QueryBlock) outer_selector.Clone (clonectx);
base.CloneTo (clonectx, t);
}
protected override string MethodName {
get { return "Join"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class GroupJoin : Join
{
readonly RangeVariable into;
public GroupJoin (QueryBlock block, RangeVariable lt, Expression inner,
QueryBlock outerSelector, QueryBlock innerSelector, RangeVariable into, Location loc)
: base (block, lt, inner, outerSelector, innerSelector, loc)
{
this.into = into;
}
protected override RangeVariable GetIntoVariable ()
{
return into;
}
protected override string MethodName {
get { return "GroupJoin"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Let : ARangeVariableQueryClause
{
public Let (QueryBlock block, RangeVariable identifier, Expression expr, Location loc)
: base (block, identifier, expr, loc)
{
}
protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args)
{
expr = CreateRangeVariableType (ec, parameter, identifier, expr);
base.CreateArguments (ec, parameter, ref args);
}
protected override string MethodName {
get { return "Select"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Select : AQueryClause
{
public Select (QueryBlock block, Expression expr, Location loc)
: base (block, expr, loc)
{
}
//
// For queries like `from a orderby a select a'
// the projection is transparent and select clause can be safely removed
//
public bool IsRequired (Parameter parameter)
{
SimpleName sn = expr as SimpleName;
if (sn == null)
return true;
return sn.Name != parameter.Name;
}
protected override string MethodName {
get { return "Select"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class SelectMany : ARangeVariableQueryClause
{
public SelectMany (QueryBlock block, RangeVariable identifier, Expression expr, Location loc)
: base (block, identifier, expr, loc)
{
}
protected override void CreateArguments (ResolveContext ec, Parameter parameter, ref Arguments args)
{
if (args == null) {
if (IdentifierType != null)
expr = CreateCastExpression (expr);
base.CreateArguments (ec, parameter.Clone (), ref args);
}
Expression result_selector_expr;
QueryBlock result_block;
var target = GetIntoVariable ();
var target_param = new ImplicitLambdaParameter (target.Name, target.Location);
//
// When select follows use it as a result selector
//
if (next is Select) {
result_selector_expr = next.Expr;
result_block = next.block;
result_block.SetParameters (parameter, target_param);
next = next.next;
} else {
result_selector_expr = CreateRangeVariableType (ec, parameter, target, new SimpleName (target.Name, target.Location));
result_block = new QueryBlock (block.Parent, block.StartLocation);
result_block.SetParameters (parameter, target_param);
}
LambdaExpression result_selector = new LambdaExpression (Location);
result_selector.Block = result_block;
result_selector.Block.AddStatement (new ContextualReturn (result_selector_expr));
args.Add (new Argument (result_selector));
}
protected override string MethodName {
get { return "SelectMany"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Where : AQueryClause
{
public Where (QueryBlock block, Expression expr, Location loc)
: base (block, expr, loc)
{
}
protected override string MethodName {
get { return "Where"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class OrderByAscending : AQueryClause
{
public OrderByAscending (QueryBlock block, Expression expr)
: base (block, expr, expr.Location)
{
}
protected override string MethodName {
get { return "OrderBy"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class OrderByDescending : AQueryClause
{
public OrderByDescending (QueryBlock block, Expression expr)
: base (block, expr, expr.Location)
{
}
protected override string MethodName {
get { return "OrderByDescending"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class ThenByAscending : OrderByAscending
{
public ThenByAscending (QueryBlock block, Expression expr)
: base (block, expr)
{
}
protected override string MethodName {
get { return "ThenBy"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class ThenByDescending : OrderByDescending
{
public ThenByDescending (QueryBlock block, Expression expr)
: base (block, expr)
{
}
protected override string MethodName {
get { return "ThenByDescending"; }
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
//
// Implicit query block
//
public class QueryBlock : ParametersBlock
{
//
// Transparent parameters are used to package up the intermediate results
// and pass them onto next clause
//
public sealed class TransparentParameter : ImplicitLambdaParameter
{
public static int Counter;
const string ParameterNamePrefix = "<>__TranspIdent";
public readonly Parameter Parent;
public readonly string Identifier;
public TransparentParameter (Parameter parent, RangeVariable identifier)
: base (ParameterNamePrefix + Counter++, identifier.Location)
{
Parent = parent;
Identifier = identifier.Name;
}
public static void Reset ()
{
Counter = 0;
}
}
public QueryBlock (Block parent, Location start)
: base (parent, ParametersCompiled.EmptyReadOnlyParameters, start, Flags.CompilerGenerated)
{
}
public void AddRangeVariable (RangeVariable variable)
{
variable.Block = this;
TopBlock.AddLocalName (variable.Name, variable, true);
}
public override void Error_AlreadyDeclared (string name, INamedBlockVariable variable, string reason)
{
TopBlock.Report.Error (1931, variable.Location,
"A range variable `{0}' conflicts with a previous declaration of `{0}'",
name);
}
public override void Error_AlreadyDeclared (string name, INamedBlockVariable variable)
{
TopBlock.Report.Error (1930, variable.Location,
"A range variable `{0}' has already been declared in this scope",
name);
}
public override void Error_AlreadyDeclaredTypeParameter (string name, Location loc)
{
TopBlock.Report.Error (1948, loc,
"A range variable `{0}' conflicts with a method type parameter",
name);
}
public void SetParameter (Parameter parameter)
{
base.parameters = new ParametersCompiled (parameter);
base.parameter_info = new ParameterInfo[] {
new ParameterInfo (this, 0)
};
}
public void SetParameters (Parameter first, Parameter second)
{
base.parameters = new ParametersCompiled (first, second);
base.parameter_info = new ParameterInfo[] {
new ParameterInfo (this, 0),
new ParameterInfo (this, 1)
};
}
}
sealed class TransparentMemberAccess : MemberAccess
{
public TransparentMemberAccess (Expression expr, string name)
: base (expr, name)
{
}
public override Expression DoResolveLValue (ResolveContext rc, Expression right_side)
{
rc.Report.Error (1947, loc,
"A range variable `{0}' cannot be assigned to. Consider using `let' clause to store the value",
Name);
return null;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Countries
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KGT : EduHubEntity
{
#region Foreign Navigation Properties
private IReadOnlyList<DF> Cache_COUNTRY_DF_BIRTH_COUNTRY_A;
private IReadOnlyList<DF> Cache_COUNTRY_DF_BIRTH_COUNTRY_B;
private IReadOnlyList<OSCS> Cache_COUNTRY_OSCS_ADULT_A_COUNTRY;
private IReadOnlyList<OSCS> Cache_COUNTRY_OSCS_ADULT_B_COUNTRY;
private IReadOnlyList<OSCS> Cache_COUNTRY_OSCS_BIRTH_COUNTRY;
private IReadOnlyList<PE> Cache_COUNTRY_PE_COUNTRY;
private IReadOnlyList<PPD> Cache_COUNTRY_PPD_COUNTRY;
private IReadOnlyList<PPS> Cache_COUNTRY_PPS_COUNTRY;
private IReadOnlyList<PPS> Cache_COUNTRY_PPS_POSTAL_COUNTRY;
private IReadOnlyList<SF> Cache_COUNTRY_SF_BIRTH_COUNTRY;
private IReadOnlyList<ST> Cache_COUNTRY_ST_BIRTH_COUNTRY;
private IReadOnlyList<UM> Cache_COUNTRY_UM_COUNTRY;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Country code
/// [Uppercase Alphanumeric (6)]
/// </summary>
public string COUNTRY { get; internal set; }
/// <summary>
/// Country description
/// [Alphanumeric (40)]
/// </summary>
public string DESCRIPTION { get; internal set; }
/// <summary>
/// Indicates whether English is the country's first language (Y/N)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string ENGLISH_SPEAKING { get; internal set; }
/// <summary>
/// Numeric "Standard Australian Classification of Countries" code as defined by Australian Bureau of Statistics
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string SACC { get; internal set; }
/// <summary>
/// Is this code obsolete (no longer in use)? (Y/blank)
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string OBSOLETE { get; internal set; }
/// <summary>
/// Identifies if Country is a refugee type for EAL (refer Aegis 7210).
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string REFUGEE { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last write operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Foreign Navigation Properties
/// <summary>
/// DF (Families) related entities by [KGT.COUNTRY]->[DF.BIRTH_COUNTRY_A]
/// Country code
/// </summary>
public IReadOnlyList<DF> COUNTRY_DF_BIRTH_COUNTRY_A
{
get
{
if (Cache_COUNTRY_DF_BIRTH_COUNTRY_A == null &&
!Context.DF.TryFindByBIRTH_COUNTRY_A(COUNTRY, out Cache_COUNTRY_DF_BIRTH_COUNTRY_A))
{
Cache_COUNTRY_DF_BIRTH_COUNTRY_A = new List<DF>().AsReadOnly();
}
return Cache_COUNTRY_DF_BIRTH_COUNTRY_A;
}
}
/// <summary>
/// DF (Families) related entities by [KGT.COUNTRY]->[DF.BIRTH_COUNTRY_B]
/// Country code
/// </summary>
public IReadOnlyList<DF> COUNTRY_DF_BIRTH_COUNTRY_B
{
get
{
if (Cache_COUNTRY_DF_BIRTH_COUNTRY_B == null &&
!Context.DF.TryFindByBIRTH_COUNTRY_B(COUNTRY, out Cache_COUNTRY_DF_BIRTH_COUNTRY_B))
{
Cache_COUNTRY_DF_BIRTH_COUNTRY_B = new List<DF>().AsReadOnly();
}
return Cache_COUNTRY_DF_BIRTH_COUNTRY_B;
}
}
/// <summary>
/// OSCS (CASES Past Students) related entities by [KGT.COUNTRY]->[OSCS.ADULT_A_COUNTRY]
/// Country code
/// </summary>
public IReadOnlyList<OSCS> COUNTRY_OSCS_ADULT_A_COUNTRY
{
get
{
if (Cache_COUNTRY_OSCS_ADULT_A_COUNTRY == null &&
!Context.OSCS.TryFindByADULT_A_COUNTRY(COUNTRY, out Cache_COUNTRY_OSCS_ADULT_A_COUNTRY))
{
Cache_COUNTRY_OSCS_ADULT_A_COUNTRY = new List<OSCS>().AsReadOnly();
}
return Cache_COUNTRY_OSCS_ADULT_A_COUNTRY;
}
}
/// <summary>
/// OSCS (CASES Past Students) related entities by [KGT.COUNTRY]->[OSCS.ADULT_B_COUNTRY]
/// Country code
/// </summary>
public IReadOnlyList<OSCS> COUNTRY_OSCS_ADULT_B_COUNTRY
{
get
{
if (Cache_COUNTRY_OSCS_ADULT_B_COUNTRY == null &&
!Context.OSCS.TryFindByADULT_B_COUNTRY(COUNTRY, out Cache_COUNTRY_OSCS_ADULT_B_COUNTRY))
{
Cache_COUNTRY_OSCS_ADULT_B_COUNTRY = new List<OSCS>().AsReadOnly();
}
return Cache_COUNTRY_OSCS_ADULT_B_COUNTRY;
}
}
/// <summary>
/// OSCS (CASES Past Students) related entities by [KGT.COUNTRY]->[OSCS.BIRTH_COUNTRY]
/// Country code
/// </summary>
public IReadOnlyList<OSCS> COUNTRY_OSCS_BIRTH_COUNTRY
{
get
{
if (Cache_COUNTRY_OSCS_BIRTH_COUNTRY == null &&
!Context.OSCS.TryFindByBIRTH_COUNTRY(COUNTRY, out Cache_COUNTRY_OSCS_BIRTH_COUNTRY))
{
Cache_COUNTRY_OSCS_BIRTH_COUNTRY = new List<OSCS>().AsReadOnly();
}
return Cache_COUNTRY_OSCS_BIRTH_COUNTRY;
}
}
/// <summary>
/// PE (Employees) related entities by [KGT.COUNTRY]->[PE.COUNTRY]
/// Country code
/// </summary>
public IReadOnlyList<PE> COUNTRY_PE_COUNTRY
{
get
{
if (Cache_COUNTRY_PE_COUNTRY == null &&
!Context.PE.TryFindByCOUNTRY(COUNTRY, out Cache_COUNTRY_PE_COUNTRY))
{
Cache_COUNTRY_PE_COUNTRY = new List<PE>().AsReadOnly();
}
return Cache_COUNTRY_PE_COUNTRY;
}
}
/// <summary>
/// PPD (PAYG Payer Details) related entities by [KGT.COUNTRY]->[PPD.COUNTRY]
/// Country code
/// </summary>
public IReadOnlyList<PPD> COUNTRY_PPD_COUNTRY
{
get
{
if (Cache_COUNTRY_PPD_COUNTRY == null &&
!Context.PPD.TryFindByCOUNTRY(COUNTRY, out Cache_COUNTRY_PPD_COUNTRY))
{
Cache_COUNTRY_PPD_COUNTRY = new List<PPD>().AsReadOnly();
}
return Cache_COUNTRY_PPD_COUNTRY;
}
}
/// <summary>
/// PPS (PAYG Supplier Details) related entities by [KGT.COUNTRY]->[PPS.COUNTRY]
/// Country code
/// </summary>
public IReadOnlyList<PPS> COUNTRY_PPS_COUNTRY
{
get
{
if (Cache_COUNTRY_PPS_COUNTRY == null &&
!Context.PPS.TryFindByCOUNTRY(COUNTRY, out Cache_COUNTRY_PPS_COUNTRY))
{
Cache_COUNTRY_PPS_COUNTRY = new List<PPS>().AsReadOnly();
}
return Cache_COUNTRY_PPS_COUNTRY;
}
}
/// <summary>
/// PPS (PAYG Supplier Details) related entities by [KGT.COUNTRY]->[PPS.POSTAL_COUNTRY]
/// Country code
/// </summary>
public IReadOnlyList<PPS> COUNTRY_PPS_POSTAL_COUNTRY
{
get
{
if (Cache_COUNTRY_PPS_POSTAL_COUNTRY == null &&
!Context.PPS.TryFindByPOSTAL_COUNTRY(COUNTRY, out Cache_COUNTRY_PPS_POSTAL_COUNTRY))
{
Cache_COUNTRY_PPS_POSTAL_COUNTRY = new List<PPS>().AsReadOnly();
}
return Cache_COUNTRY_PPS_POSTAL_COUNTRY;
}
}
/// <summary>
/// SF (Staff) related entities by [KGT.COUNTRY]->[SF.BIRTH_COUNTRY]
/// Country code
/// </summary>
public IReadOnlyList<SF> COUNTRY_SF_BIRTH_COUNTRY
{
get
{
if (Cache_COUNTRY_SF_BIRTH_COUNTRY == null &&
!Context.SF.TryFindByBIRTH_COUNTRY(COUNTRY, out Cache_COUNTRY_SF_BIRTH_COUNTRY))
{
Cache_COUNTRY_SF_BIRTH_COUNTRY = new List<SF>().AsReadOnly();
}
return Cache_COUNTRY_SF_BIRTH_COUNTRY;
}
}
/// <summary>
/// ST (Students) related entities by [KGT.COUNTRY]->[ST.BIRTH_COUNTRY]
/// Country code
/// </summary>
public IReadOnlyList<ST> COUNTRY_ST_BIRTH_COUNTRY
{
get
{
if (Cache_COUNTRY_ST_BIRTH_COUNTRY == null &&
!Context.ST.TryFindByBIRTH_COUNTRY(COUNTRY, out Cache_COUNTRY_ST_BIRTH_COUNTRY))
{
Cache_COUNTRY_ST_BIRTH_COUNTRY = new List<ST>().AsReadOnly();
}
return Cache_COUNTRY_ST_BIRTH_COUNTRY;
}
}
/// <summary>
/// UM (Addresses) related entities by [KGT.COUNTRY]->[UM.COUNTRY]
/// Country code
/// </summary>
public IReadOnlyList<UM> COUNTRY_UM_COUNTRY
{
get
{
if (Cache_COUNTRY_UM_COUNTRY == null &&
!Context.UM.TryFindByCOUNTRY(COUNTRY, out Cache_COUNTRY_UM_COUNTRY))
{
Cache_COUNTRY_UM_COUNTRY = new List<UM>().AsReadOnly();
}
return Cache_COUNTRY_UM_COUNTRY;
}
}
#endregion
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2014-2018 FUJIWARA, Yusuke and contributors
//
// 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.
//
// Contributors:
// Takeshi KIRIYA
// Odyth
// Roman-Blinkov
// Samuel Cragg
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
#if FEATURE_MPCONTRACT
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // FEATURE_MPCONTRACT
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using MsgPack.Serialization.DefaultSerializers;
namespace MsgPack.Serialization
{
/// <summary>
/// Implements serialization target member extraction logics.
/// </summary>
#if UNITY && DEBUG
public
#else
internal
#endif
class SerializationTarget
{
// Type names to avoid user who doesn't embed "message pack assembly's attributes" in their code directly.
private static readonly string MessagePackMemberAttributeTypeName = typeof( MessagePackMemberAttribute ).FullName;
private static readonly string MessagePackIgnoreAttributeTypeName = typeof( MessagePackIgnoreAttribute ).FullName;
private static readonly string MessagePackDeserializationConstructorAttributeTypeName = typeof( MessagePackDeserializationConstructorAttribute ).FullName;
private static readonly string[] EmptyStrings = new string[ 0 ];
private static readonly SerializingMember[] EmptyMembers = new SerializingMember[ 0 ];
private static readonly Assembly ThisAssembly = typeof( SerializationTarget ).GetAssembly();
public IList<SerializingMember> Members { get; private set; }
public ConstructorInfo DeserializationConstructor { get; private set; }
private readonly string[] _correspondingMemberNames;
public bool IsConstructorDeserialization { get; private set; }
public bool CanDeserialize { get; private set; }
private SerializationTarget( IList<SerializingMember> members, ConstructorInfo constructor, string[] correspondingMemberNames, bool canDeserialize )
{
Trace( "SerializationTarget::ctor(canDeserialize: {0})", canDeserialize );
this.Members = members;
this.DeserializationConstructor = constructor;
this.IsConstructorDeserialization = constructor != null && constructor.GetParameters().Any();
this.CanDeserialize = canDeserialize;
this._correspondingMemberNames = correspondingMemberNames ?? EmptyStrings;
}
public SerializerCapabilities GetCapabilitiesForObject()
{
return this.CanDeserialize ? ( SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom ) : SerializerCapabilities.PackTo;
}
public SerializerCapabilities GetCapabilitiesForCollection( CollectionTraits traits )
{
return
!this.CanDeserialize
? SerializerCapabilities.PackTo
: traits.AddMethod == null
? ( SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom )
: ( SerializerCapabilities.PackTo | SerializerCapabilities.UnpackFrom | SerializerCapabilities.UnpackTo );
}
private static string[] FindCorrespondingMemberNames( IList<SerializingMember> members, ConstructorInfo constructor )
{
if ( constructor == null )
{
return null;
}
var constructorParameters = constructor.GetParameters();
return
constructorParameters.GroupJoin(
members,
p => new KeyValuePair<string, Type>( p.Name, p.ParameterType ),
m => new KeyValuePair<string, Type>( m.Contract.Name, m.Member == null ? null : m.Member.GetMemberValueType() ),
( p, ms ) => DetermineCorrespondingMemberName( p, ms ),
MemberConstructorParameterEqualityComparer.Instance
).ToArray();
}
private static string DetermineCorrespondingMemberName( ParameterInfo parameterInfo, IEnumerable<SerializingMember> members )
{
var membersArray = members.ToArray();
switch ( membersArray.Length )
{
case 0:
{
return null;
}
case 1:
{
return membersArray[ 0 ].MemberName;
}
default:
{
ThrowAmbigiousMatchException( parameterInfo, membersArray );
return null;
}
}
}
private static void ThrowAmbigiousMatchException( ParameterInfo parameterInfo, ICollection<SerializingMember> members )
{
throw new AmbiguousMatchException(
String.Format(
CultureInfo.CurrentCulture,
"There are multiple candiates for corresponding member for parameter '{0}' of constructor. [{1}]",
parameterInfo,
String.Join( ", ", members.Select( x => x.ToString() ).ToArray() )
)
);
}
public string GetCorrespondingMemberName( int constructorParameterIndex )
{
return this._correspondingMemberNames[ constructorParameterIndex ];
}
public static void VerifyType( Type targetType )
{
if ( targetType.GetIsInterface() || targetType.GetIsAbstract() )
{
throw SerializationExceptions.NewNotSupportedBecauseCannotInstanciateAbstractType( targetType );
}
}
public static void VerifyCanSerializeTargetType( SerializationContext context, Type targetType )
{
if ( context.SerializerOptions.DisablePrivilegedAccess && !targetType.GetIsPublic() && !targetType.GetIsNestedPublic() && !ThisAssembly.Equals( targetType.GetAssembly() ) )
{
throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot serialize type '{0}' because it is not public to the serializer.", targetType ) );
}
}
public static SerializationTarget Prepare( SerializationContext context, Type targetType )
{
VerifyCanSerializeTargetType( context, targetType );
IEnumerable<string> memberIgnoreList = context.BindingOptions.GetIgnoringMembers( targetType );
var getters = GetTargetMembers( targetType )
.Where( getter => !memberIgnoreList.Contains( getter.MemberName, StringComparer.Ordinal ) )
.OrderBy( entry => entry.Contract.Id )
.ToArray();
if ( getters.Length == 0
&& !typeof( IPackable ).IsAssignableFrom( targetType )
&& !typeof( IUnpackable ).IsAssignableFrom( targetType )
#if FEATURE_TAP
&& ( context.SerializerOptions.WithAsync
&& ( !typeof( IAsyncPackable ).IsAssignableFrom( targetType )
&& !typeof( IAsyncUnpackable ).IsAssignableFrom( targetType )
)
)
#endif // FEATURE_TAP
)
{
throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Cannot serialize type '{0}' because it does not have any serializable fields nor properties.", targetType ) );
}
var memberCandidates = getters.Where( entry => CheckTargetEligibility( context, entry.Member ) ).ToArray();
if ( memberCandidates.Length == 0 && !context.CompatibilityOptions.AllowAsymmetricSerializer )
{
ConstructorKind constructorKind;
var deserializationConstructor = FindDeserializationConstructor( context, targetType, out constructorKind );
var complementedMembers = ComplementMembers( getters, context, targetType );
var correspondingMemberNames = FindCorrespondingMemberNames( complementedMembers, deserializationConstructor );
return
new SerializationTarget(
complementedMembers,
deserializationConstructor,
correspondingMemberNames,
DetermineCanDeserialize( constructorKind, context, targetType, correspondingMemberNames, allowDefault: false )
);
}
else
{
bool? canDeserialize;
ConstructorKind constructorKind;
// Try to get default constructor.
var constructor = targetType.GetConstructor( ReflectionAbstractions.EmptyTypes );
if ( constructor == null && !targetType.GetIsValueType() )
{
// Try to get deserialization constructor.
var deserializationConstructor = FindDeserializationConstructor( context, targetType, out constructorKind );
if ( deserializationConstructor == null && !context.CompatibilityOptions.AllowAsymmetricSerializer )
{
throw SerializationExceptions.NewTargetDoesNotHavePublicDefaultConstructor( targetType );
}
constructor = deserializationConstructor;
canDeserialize = null;
}
else if ( memberCandidates.Length == 0 )
{
#if DEBUG
Contract.Assert( context.CompatibilityOptions.AllowAsymmetricSerializer );
#endif // DEBUG
// Absolutely cannot deserialize in this case.
canDeserialize = false;
constructorKind = ConstructorKind.Ambiguous;
}
else
{
constructorKind = ConstructorKind.Default;
// Let's prefer annotated constructor here.
var markedConstructors = FindExplicitDeserializationConstructors( targetType.GetConstructors() );
if ( markedConstructors.Count == 1 )
{
// For backward compatibility, no exceptions are thrown here even if mulitiple deserialization constructor attributes in the type
// just use default constructor for it.
constructor = markedConstructors[ 0 ];
constructorKind = ConstructorKind.Marked;
}
// OK, appropriate constructor and setters are found.
canDeserialize = true;
}
if ( constructor != null && constructor.GetParameters().Any() || context.CompatibilityOptions.AllowAsymmetricSerializer )
{
// Recalculate members because getter-only/readonly members should be included for constructor deserialization.
memberCandidates = getters;
}
// Because members' order is equal to declared order is NOT guaranteed, so explicit ordering is required.
IList<SerializingMember> members;
if ( memberCandidates.All( item => item.Contract.Id == DataMemberContract.UnspecifiedId ) )
{
// Alphabetical order.
members = memberCandidates.OrderBy( item => item.Contract.Name ).ToArray();
}
else
{
// ID order.
members = ComplementMembers( memberCandidates, context, targetType );
}
var correspondingMemberNames = FindCorrespondingMemberNames( members, constructor );
return
new SerializationTarget(
members,
constructor,
correspondingMemberNames,
canDeserialize ?? DetermineCanDeserialize( constructorKind, context, targetType, correspondingMemberNames, allowDefault: true )
);
}
}
private static bool HasAnyCorrespondingMembers( IEnumerable<string> correspondingMemberNames )
{
return correspondingMemberNames.Count( x => !String.IsNullOrEmpty( x ) ) > 0;
}
private static bool HasUnpackableInterface( Type targetType, SerializationContext context )
{
return
typeof( IUnpackable ).IsAssignableFrom( targetType )
#if FEATURE_TAP
&& ( !context.SerializerOptions.WithAsync || typeof( IAsyncUnpackable ).IsAssignableFrom( targetType ) )
#endif // FEATURE_TAP
;
}
private static bool DetermineCanDeserialize( ConstructorKind kind, SerializationContext context, Type targetType, IEnumerable<string> correspondingMemberNames, bool allowDefault )
{
if ( HasUnpackableInterface( targetType, context ) )
{
Trace( "SerializationTarget::DetermineCanDeserialize({0}, {1}) -> true: HasUnpackableInterface", targetType, kind );
return true;
}
switch ( kind )
{
case ConstructorKind.Marked:
{
Trace( "SerializationTarget::DetermineCanDeserialize({0}, {1}) -> true: Marked", targetType, kind );
return true;
}
case ConstructorKind.Parameterful:
{
var result = HasAnyCorrespondingMembers( correspondingMemberNames );
Trace( "SerializationTarget::DetermineCanDeserialize({0}, {1}) -> {2}: HasAnyCorrespondingMembers", targetType, kind, result );
return result;
}
case ConstructorKind.Default:
{
Trace( "SerializationTarget::DetermineCanDeserialize({0}, {1}) -> {2}: Default", targetType, kind, allowDefault );
return allowDefault;
}
default:
{
Contract.Assert( kind == ConstructorKind.None || kind == ConstructorKind.Ambiguous, "kind == ConstructorKind.None || kind == ConstructorKind.Ambiguous : " + kind );
return false;
}
}
}
private static MemberInfo[] GetDistinctMembers( Type type )
{
var distinctMembers = new List<MemberInfo>();
var returningMemberNamesSet = new HashSet<string>();
while ( type != typeof( object ) && type != null )
{
var members =
#if !NETSTANDARD1_1 && !NETSTANDARD1_3
type.FindMembers(
MemberTypes.Field | MemberTypes.Property,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
null,
null
);
#else
type.GetTypeInfo().DeclaredFields.Where( f => !f.IsStatic ).OfType<MemberInfo>()
.Concat( type.GetTypeInfo().DeclaredProperties.Where( p => p.GetMethod != null && !p.GetMethod.IsStatic ) );
#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3
foreach ( var memberInfo in members )
{
if ( returningMemberNamesSet.Add( memberInfo.Name ) ) //HashSet returns true is new key was added
{
distinctMembers.Add( memberInfo );
}
}
type = type.GetBaseType();
}
return distinctMembers.ToArray();
}
private static IEnumerable<SerializingMember> GetTargetMembers( Type type )
{
Contract.Assert( type != null, "type != null" );
var members = GetDistinctMembers( type );
var filtered = members.Where( item =>
#if !UNITY
item.GetCustomAttributesData().Any( a => a.GetAttributeType().FullName == MessagePackMemberAttributeTypeName )
#else
item.GetCustomAttributes( typeof( MessagePackMemberAttribute ), true ).Any()
#endif // !UNITY
).ToArray();
if ( filtered.Length > 0 )
{
return GetAnnotatedMembersWithDuplicationDetection( type, filtered );
}
if (
#if !UNITY
type.GetCustomAttributesData().Any( attr =>
attr.GetAttributeType().FullName == "System.Runtime.Serialization.DataContractAttribute" )
#else
type.GetCustomAttributes( true ).Any( attr =>
attr.GetType().FullName == "System.Runtime.Serialization.DataContractAttribute" )
#endif // !UNITY
)
{
return GetSystemRuntimeSerializationCompatibleMembers( members );
}
return GetPublicUnpreventedMembers( members );
}
private static IEnumerable<SerializingMember> GetAnnotatedMembersWithDuplicationDetection( Type type, MemberInfo[] filtered )
{
var duplicated =
filtered.FirstOrDefault(
#if !UNITY
member => member.GetCustomAttributesData().Any( a => a.GetAttributeType().FullName == MessagePackIgnoreAttributeTypeName )
#else
member => member.GetCustomAttributes( typeof( MessagePackIgnoreAttribute ), true ).Any()
#endif // !UNITY
);
if ( duplicated != null )
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"A member '{0}' of type '{1}' is marked with both MessagePackMemberAttribute and MessagePackIgnoreAttribute.",
duplicated.Name,
type
)
);
}
return
filtered.Select(
member =>
{
#if !UNITY
var attribute = member.GetCustomAttributesData().Single( a => a.GetAttributeType().FullName == MessagePackMemberAttributeTypeName );
return
new SerializingMember(
member,
new DataMemberContract(
member,
( string )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "Name" ),
#if !SILVERLIGHT
( NilImplication )( ( int? )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "NilImplication" ) ).GetValueOrDefault(),
( int? )GetAttributeArgument( MessagePackMemberAttributeTypeName, attribute, 0 )
#else
( NilImplication )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "NilImplication" ),
( int? )GetAttributeProperty( MessagePackMemberAttributeTypeName, attribute, "Id" )
#endif // !SILVERLIGHT
)
);
#else
var attribute = member.GetCustomAttributes( typeof( MessagePackMemberAttribute ), true ).Single() as MessagePackMemberAttribute;
return
new SerializingMember(
member,
new DataMemberContract(
member,
attribute.Name,
attribute.NilImplication,
attribute.Id
)
);
#endif // !UNITY
}
);
}
#if !UNITY
#if !SILVERLIGHT
private static object GetAttributeArgument( string attributeName, CustomAttributeData attribute, int index )
{
var arguments = attribute.GetConstructorArguments();
if ( arguments.Count < index )
{
// Use default.
return null;
}
return arguments[ index ].Value;
}
#endif // !SILVERLIGHT
#if !SILVERLIGHT
private static object GetAttributeProperty( string attributeName, CustomAttributeData attribute, string propertyName )
#else
private static object GetAttributeProperty( string attributeName, Attribute attribute, string propertyName )
#endif // !SILVERLIGHT
{
var property = attribute.GetNamedArguments().SingleOrDefault( a => a.GetMemberName() == propertyName );
if ( property.GetMemberName() == null )
{
// Use default.
return null;
}
return property.GetTypedValue().Value;
}
#endif // !UNITY
private static IEnumerable<SerializingMember> GetSystemRuntimeSerializationCompatibleMembers( MemberInfo[] members )
{
return
members.Select(
item =>
new
{
member = item,
data =
#if !UNITY
item.GetCustomAttributesData()
.FirstOrDefault(
data => data.GetAttributeType().FullName == "System.Runtime.Serialization.DataMemberAttribute"
)
#else
item.GetCustomAttributes( true )
.FirstOrDefault(
data => data.GetType().FullName == "System.Runtime.Serialization.DataMemberAttribute"
)
#endif // !UNITY
}
).Where( item => item.data != null )
.Select(
item =>
{
#if !UNITY
var name =
item.data.GetNamedArguments()
.Where( arg => arg.GetMemberName() == "Name" )
.Select( arg => ( string )arg.GetTypedValue().Value )
.FirstOrDefault();
var id =
item.data.GetNamedArguments()
.Where( arg => arg.GetMemberName() == "Order" )
.Select( arg => ( int? )arg.GetTypedValue().Value )
.FirstOrDefault();
if ( id == -1 )
{
id = null;
}
return
new SerializingMember(
item.member,
new DataMemberContract( item.member, name, NilImplication.MemberDefault, id )
);
#else
var nameProperty = item.data.GetType().GetProperty( "Name" );
var orderProperty = item.data.GetType().GetProperty( "Order" );
if ( nameProperty == null || !nameProperty.CanRead || nameProperty.GetGetMethod().GetParameters().Length > 0 )
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"Failed to get Name property from {0} type.",
item.data.GetType().AssemblyQualifiedName
)
);
}
if( orderProperty == null || !orderProperty.CanRead || orderProperty.GetGetMethod().GetParameters().Length > 0 )
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"Failed to get Order property from {0} type.",
item.data.GetType().AssemblyQualifiedName
)
);
}
var name = ( string )nameProperty.GetValue( item.data, null );
var id = ( int? )orderProperty.GetValue( item.data, null );
if ( id == -1 )
{
id = null;
}
return
new SerializingMember(
item.member,
new DataMemberContract( item.member, name, NilImplication.MemberDefault, id )
);
#endif // !UNITY
}
);
}
private static IEnumerable<SerializingMember> GetPublicUnpreventedMembers( MemberInfo[] members )
{
return members.Where(
member =>
member.GetIsPublic()
&& !member
#if !UNITY
.GetCustomAttributesData()
.Select( data => data.GetAttributeType().FullName )
#else
.GetCustomAttributes( true )
.Select( data => data.GetType().FullName )
#endif // !UNITY
.Any( attr =>
attr == "MsgPack.Serialization.MessagePackIgnoreAttribute"
|| attr == "System.Runtime.Serialization.IgnoreDataMemberAttribute"
)
&& !IsNonSerializedField( member )
).Select( member => new SerializingMember( member, new DataMemberContract( member ) ) );
}
private static bool IsNonSerializedField( MemberInfo member )
{
var asField = member as FieldInfo;
if ( asField == null )
{
return false;
}
return ( asField.Attributes & FieldAttributes.NotSerialized ) != 0;
}
private static ConstructorInfo FindDeserializationConstructor( SerializationContext context, Type targetType, out ConstructorKind constructorKind )
{
var constructors = targetType.GetConstructors().ToArray();
if ( constructors.Length == 0 )
{
if ( context.CompatibilityOptions.AllowAsymmetricSerializer )
{
constructorKind = ConstructorKind.None;
return null;
}
else
{
throw NewTypeCannotBeSerializedException( targetType );
}
}
// The marked construtor is always preferred.
var markedConstructors = FindExplicitDeserializationConstructors( constructors );
switch ( markedConstructors.Count )
{
case 0:
{
break;
}
case 1:
{
// OK use it for deserialization.
constructorKind = ConstructorKind.Marked;
return markedConstructors[ 0 ];
}
default:
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"There are multiple constructors marked with MessagePackDeserializationConstrutorAttribute in type '{0}'.",
targetType
)
);
}
}
// A constructor which has most parameters will be used.
var mostRichConstructors =
constructors.GroupBy( ctor => ctor.GetParameters().Length ).OrderByDescending( g => g.Key ).First().ToArray();
#if DEBUG
Trace( "SerializationTarget::FindDeserializationConstructor.MostRich({0}) -> {1}", targetType, String.Join( ";", mostRichConstructors.Select( x => x.ToString() ).ToArray() ) );
#endif // DEBUG
switch ( mostRichConstructors.Length )
{
case 1:
{
if ( mostRichConstructors[ 0 ].GetParameters().Length == 0 )
{
if ( context.CompatibilityOptions.AllowAsymmetricSerializer )
{
constructorKind = ConstructorKind.Default;
return mostRichConstructors[ 0 ];
}
else
{
throw NewTypeCannotBeSerializedException( targetType );
}
}
// OK try use it but it may not handle deserialization correctly.
constructorKind = ConstructorKind.Parameterful;
return mostRichConstructors[ 0 ];
}
default:
{
if ( context.CompatibilityOptions.AllowAsymmetricSerializer )
{
constructorKind = ConstructorKind.Ambiguous;
return null;
}
else
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"Cannot serialize type '{0}' because it does not have any serializable fields nor properties, and serializer generator failed to determine constructor to deserialize among({1}).",
targetType,
String.Join( ", ", mostRichConstructors.Select( ctor => ctor.ToString() ).ToArray() )
)
);
}
}
}
}
private static IList<ConstructorInfo> FindExplicitDeserializationConstructors( IEnumerable<ConstructorInfo> construtors )
{
return
construtors
.Where( ctor =>
#if !UNITY
ctor.GetCustomAttributesData().Any( a =>
a.GetAttributeType().FullName
#else
ctor.GetCustomAttributes( true ).Any( a =>
a.GetType().FullName
#endif // !UNITY
== MessagePackDeserializationConstructorAttributeTypeName
)
).ToArray();
}
private static SerializationException NewTypeCannotBeSerializedException( Type targetType )
{
return
new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"Cannot serialize type '{0}' because it does not have any serializable fields nor properties, and it does not have any public constructors with parameters.",
targetType
)
);
}
private static bool CheckTargetEligibility( SerializationContext context, MemberInfo member )
{
var asProperty = member as PropertyInfo;
var asField = member as FieldInfo;
Type returnType;
if ( asProperty != null )
{
if ( asProperty.GetIndexParameters().Length > 0 )
{
// Indexer cannot be target except the type itself implements IDictionary or IDictionary<TKey,TValue>
return false;
}
#if !NETSTANDARD1_1 && !NETSTANDARD1_3
var setter = asProperty.GetSetMethod( true );
#else
var setter = asProperty.SetMethod;
#endif // !NETSTANDARD1_1 && !NETSTANDARD1_3
if ( setter != null )
{
if ( setter.GetIsPublic() )
{
return true;
}
if ( !context.SerializerOptions.DisablePrivilegedAccess )
{
// Can deserialize non-public setter if privileged.
return true;
}
}
returnType = asProperty.PropertyType;
}
else if ( asField != null )
{
if ( !asField.IsInitOnly )
{
return true;
}
returnType = asField.FieldType;
}
else
{
#if DEBUG
Contract.Assert( false, "Unknown type member " + member );
#endif // DEBUG
// ReSharper disable once HeuristicUnreachableCode
return true;
}
var traits = returnType.GetCollectionTraits( CollectionTraitOptions.WithAddMethod, allowNonCollectionEnumerableTypes: false );
switch ( traits.CollectionType )
{
case CollectionKind.Array:
case CollectionKind.Map:
{
return traits.AddMethod != null;
}
default:
{
return false;
}
}
}
private static IList<SerializingMember> ComplementMembers( IList<SerializingMember> candidates, SerializationContext context, Type targetType )
{
if ( candidates.Count == 0 )
{
return candidates;
}
if ( candidates[ 0 ].Contract.Id < 0 )
{
return candidates;
}
if ( context.CompatibilityOptions.OneBoundDataMemberOrder && candidates[ 0 ].Contract.Id == 0 )
{
throw new NotSupportedException(
"Cannot specify order value 0 on DataMemberAttribute when SerializationContext.CompatibilityOptions.OneBoundDataMemberOrder is set to true."
);
}
#if !UNITY
var maxId = candidates.Max( item => item.Contract.Id );
#else
int maxId = -1;
foreach ( var id in candidates.Select( item => item.Contract.Id ) )
{
maxId = Math.Max( id, maxId );
}
#endif
var result = new List<SerializingMember>( maxId + 1 );
for ( int source = 0, destination = context.CompatibilityOptions.OneBoundDataMemberOrder ? 1 : 0;
source < candidates.Count;
source++, destination++ )
{
#if DEBUG
Contract.Assert( candidates[ source ].Contract.Id >= 0, "candidates[ source ].Contract.Id >= 0" );
#endif // DEBUG
if ( candidates[ source ].Contract.Id < destination )
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
"The member ID '{0}' is duplicated in the '{1}' elementType.",
candidates[ source ].Contract.Id,
targetType
)
);
}
while ( candidates[ source ].Contract.Id > destination )
{
result.Add( new SerializingMember() );
destination++;
}
result.Add( candidates[ source ] );
}
VerifyNilImplication( targetType, result );
VerifyKeyUniqueness( result );
return result;
}
private static void VerifyNilImplication( Type type, IEnumerable<SerializingMember> entries )
{
foreach ( var serializingMember in entries )
{
if ( serializingMember.Contract.NilImplication == NilImplication.Null )
{
var itemType = serializingMember.Member.GetMemberValueType();
if ( itemType != typeof( MessagePackObject )
&& itemType.GetIsValueType()
&& Nullable.GetUnderlyingType( itemType ) == null )
{
SerializationExceptions.ThrowValueTypeCannotBeNull( serializingMember.Member.ToString(), itemType, type );
}
bool isReadOnly;
FieldInfo asField;
PropertyInfo asProperty;
if ( ( asField = serializingMember.Member as FieldInfo ) != null )
{
isReadOnly = asField.IsInitOnly;
}
else
{
asProperty = serializingMember.Member as PropertyInfo;
#if DEBUG
Contract.Assert( asProperty != null, serializingMember.Member.ToString() );
#endif // DEBUG
isReadOnly = asProperty.GetSetMethod() == null;
}
if ( isReadOnly )
{
SerializationExceptions.ThrowNullIsProhibited( serializingMember.Member.ToString() );
}
}
}
}
private static void VerifyKeyUniqueness( IList<SerializingMember> result )
{
var duplicated = new Dictionary<string, List<MemberInfo>>();
var existents = new Dictionary<string, SerializingMember>();
foreach ( var member in result )
{
if ( member.Contract.Name == null )
{
continue;
}
try
{
existents.Add( member.Contract.Name, member );
}
catch ( ArgumentException )
{
List<MemberInfo> list;
if ( duplicated.TryGetValue( member.Contract.Name, out list ) )
{
list.Add( member.Member );
}
else
{
duplicated.Add( member.Contract.Name, new List<MemberInfo> { existents[ member.Contract.Name ].Member, member.Member } );
}
}
}
if ( duplicated.Count > 0 )
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"Some member keys specified with custom attributes are duplicated. Details: {{{0}}}",
String.Join(
",",
duplicated.Select(
kv => String.Format(
CultureInfo.CurrentCulture,
"\"{0}\":[{1}]",
kv.Key,
String.Join( ",", kv.Value.Select( m => String.Format( CultureInfo.InvariantCulture, "{0}.{1}({2})", m.DeclaringType, m.Name, ( m is FieldInfo ) ? "Field" : "Property" ) ).ToArray() )
)
).ToArray()
)
)
);
}
}
public static SerializationTarget CreateForCollection( ConstructorInfo collectionConstructor, bool canDeserialize )
{
return new SerializationTarget( EmptyMembers, collectionConstructor, EmptyStrings, canDeserialize );
}
#if !NET35
public static SerializationTarget CreateForTuple( IList<Type> itemTypes )
{
return new SerializationTarget( itemTypes.Select( ( _, i ) => new SerializingMember( GetTupleItemNameFromIndex( i ) ) ).ToArray(), null, null, true );
}
public static string GetTupleItemNameFromIndex( int i )
{
return "Item" + ( i + 1 ).ToString( "D", CultureInfo.InvariantCulture );
}
#endif // !NET35
#if FEATURE_CODEGEN
public static bool BuiltInSerializerExists( ISerializerGeneratorConfiguration configuration, Type type, CollectionTraits traits )
{
return GenericSerializer.IsSupported( type, traits, configuration.PreferReflectionBasedSerializer ) || SerializerRepository.InternalDefault.ContainsFor( type );
}
#endif // FEATURE_CODEGEN
private sealed class MemberConstructorParameterEqualityComparer : EqualityComparer<KeyValuePair<string, Type>>
{
public static readonly IEqualityComparer<KeyValuePair<string, Type>> Instance = new MemberConstructorParameterEqualityComparer();
private MemberConstructorParameterEqualityComparer() { }
public override bool Equals( KeyValuePair<string, Type> x, KeyValuePair<string, Type> y )
{
return String.Equals( x.Key, y.Key, StringComparison.OrdinalIgnoreCase ) && x.Value == y.Value;
}
public override int GetHashCode( KeyValuePair<string, Type> obj )
{
return ( obj.Key == null ? 0 : StringComparer.OrdinalIgnoreCase.GetHashCode( obj.Key ) ) ^ ( obj.Value == null ? 0 : obj.Value.GetHashCode() );
}
}
[Conditional( "DEBUG" )]
private static void Trace( string format, params object[] args )
{
#if !SILVERLIGHT && !WINDOWS_PHONE && !NETFX_CORE
Tracer.Binding.TraceEvent( Tracer.EventType.Trace, Tracer.EventId.Trace, format, args );
#endif // !SILVERLIGHT && !WINDOWS_PHONE && !NETFX_CORE
}
private enum ConstructorKind
{
None = 0,
Marked,
Default,
Parameterful,
Ambiguous
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/oslogin/v1beta/oslogin.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.OsLogin.V1Beta {
/// <summary>Holder for reflection information generated from google/cloud/oslogin/v1beta/oslogin.proto</summary>
public static partial class OsloginReflection {
#region Descriptor
/// <summary>File descriptor for google/cloud/oslogin/v1beta/oslogin.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static OsloginReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cilnb29nbGUvY2xvdWQvb3Nsb2dpbi92MWJldGEvb3Nsb2dpbi5wcm90bxIb",
"Z29vZ2xlLmNsb3VkLm9zbG9naW4udjFiZXRhGhxnb29nbGUvYXBpL2Fubm90",
"YXRpb25zLnByb3RvGihnb29nbGUvY2xvdWQvb3Nsb2dpbi9jb21tb24vY29t",
"bW9uLnByb3RvGhtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8aIGdvb2ds",
"ZS9wcm90b2J1Zi9maWVsZF9tYXNrLnByb3RvIqoCCgxMb2dpblByb2ZpbGUS",
"DAoEbmFtZRgBIAEoCRJBCg5wb3NpeF9hY2NvdW50cxgCIAMoCzIpLmdvb2ds",
"ZS5jbG91ZC5vc2xvZ2luLmNvbW1vbi5Qb3NpeEFjY291bnQSVQoPc3NoX3B1",
"YmxpY19rZXlzGAMgAygLMjwuZ29vZ2xlLmNsb3VkLm9zbG9naW4udjFiZXRh",
"LkxvZ2luUHJvZmlsZS5Tc2hQdWJsaWNLZXlzRW50cnkSEQoJc3VzcGVuZGVk",
"GAQgASgIGl8KElNzaFB1YmxpY0tleXNFbnRyeRILCgNrZXkYASABKAkSOAoF",
"dmFsdWUYAiABKAsyKS5nb29nbGUuY2xvdWQub3Nsb2dpbi5jb21tb24uU3No",
"UHVibGljS2V5OgI4ASIpChlEZWxldGVQb3NpeEFjY291bnRSZXF1ZXN0EgwK",
"BG5hbWUYASABKAkiKQoZRGVsZXRlU3NoUHVibGljS2V5UmVxdWVzdBIMCgRu",
"YW1lGAEgASgJIiYKFkdldExvZ2luUHJvZmlsZVJlcXVlc3QSDAoEbmFtZRgB",
"IAEoCSImChZHZXRTc2hQdWJsaWNLZXlSZXF1ZXN0EgwKBG5hbWUYASABKAki",
"ggEKGUltcG9ydFNzaFB1YmxpY0tleVJlcXVlc3QSDgoGcGFyZW50GAEgASgJ",
"EkEKDnNzaF9wdWJsaWNfa2V5GAIgASgLMikuZ29vZ2xlLmNsb3VkLm9zbG9n",
"aW4uY29tbW9uLlNzaFB1YmxpY0tleRISCgpwcm9qZWN0X2lkGAMgASgJIl4K",
"GkltcG9ydFNzaFB1YmxpY0tleVJlc3BvbnNlEkAKDWxvZ2luX3Byb2ZpbGUY",
"ASABKAsyKS5nb29nbGUuY2xvdWQub3Nsb2dpbi52MWJldGEuTG9naW5Qcm9m",
"aWxlIp0BChlVcGRhdGVTc2hQdWJsaWNLZXlSZXF1ZXN0EgwKBG5hbWUYASAB",
"KAkSQQoOc3NoX3B1YmxpY19rZXkYAiABKAsyKS5nb29nbGUuY2xvdWQub3Ns",
"b2dpbi5jb21tb24uU3NoUHVibGljS2V5Ei8KC3VwZGF0ZV9tYXNrGAMgASgL",
"MhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFzazKFCAoOT3NMb2dpblNlcnZp",
"Y2USjwEKEkRlbGV0ZVBvc2l4QWNjb3VudBI2Lmdvb2dsZS5jbG91ZC5vc2xv",
"Z2luLnYxYmV0YS5EZWxldGVQb3NpeEFjY291bnRSZXF1ZXN0GhYuZ29vZ2xl",
"LnByb3RvYnVmLkVtcHR5IimC0+STAiMqIS92MWJldGEve25hbWU9dXNlcnMv",
"Ki9wcm9qZWN0cy8qfRKUAQoSRGVsZXRlU3NoUHVibGljS2V5EjYuZ29vZ2xl",
"LmNsb3VkLm9zbG9naW4udjFiZXRhLkRlbGV0ZVNzaFB1YmxpY0tleVJlcXVl",
"c3QaFi5nb29nbGUucHJvdG9idWYuRW1wdHkiLoLT5JMCKComL3YxYmV0YS97",
"bmFtZT11c2Vycy8qL3NzaFB1YmxpY0tleXMvKn0SngEKD0dldExvZ2luUHJv",
"ZmlsZRIzLmdvb2dsZS5jbG91ZC5vc2xvZ2luLnYxYmV0YS5HZXRMb2dpblBy",
"b2ZpbGVSZXF1ZXN0GikuZ29vZ2xlLmNsb3VkLm9zbG9naW4udjFiZXRhLkxv",
"Z2luUHJvZmlsZSIrgtPkkwIlEiMvdjFiZXRhL3tuYW1lPXVzZXJzLyp9L2xv",
"Z2luUHJvZmlsZRKhAQoPR2V0U3NoUHVibGljS2V5EjMuZ29vZ2xlLmNsb3Vk",
"Lm9zbG9naW4udjFiZXRhLkdldFNzaFB1YmxpY0tleVJlcXVlc3QaKS5nb29n",
"bGUuY2xvdWQub3Nsb2dpbi5jb21tb24uU3NoUHVibGljS2V5Ii6C0+STAigS",
"Ji92MWJldGEve25hbWU9dXNlcnMvKi9zc2hQdWJsaWNLZXlzLyp9EsoBChJJ",
"bXBvcnRTc2hQdWJsaWNLZXkSNi5nb29nbGUuY2xvdWQub3Nsb2dpbi52MWJl",
"dGEuSW1wb3J0U3NoUHVibGljS2V5UmVxdWVzdBo3Lmdvb2dsZS5jbG91ZC5v",
"c2xvZ2luLnYxYmV0YS5JbXBvcnRTc2hQdWJsaWNLZXlSZXNwb25zZSJDgtPk",
"kwI9IisvdjFiZXRhL3twYXJlbnQ9dXNlcnMvKn06aW1wb3J0U3NoUHVibGlj",
"S2V5Og5zc2hfcHVibGljX2tleRK3AQoSVXBkYXRlU3NoUHVibGljS2V5EjYu",
"Z29vZ2xlLmNsb3VkLm9zbG9naW4udjFiZXRhLlVwZGF0ZVNzaFB1YmxpY0tl",
"eVJlcXVlc3QaKS5nb29nbGUuY2xvdWQub3Nsb2dpbi5jb21tb24uU3NoUHVi",
"bGljS2V5Ij6C0+STAjgyJi92MWJldGEve25hbWU9dXNlcnMvKi9zc2hQdWJs",
"aWNLZXlzLyp9Og5zc2hfcHVibGljX2tleUKxAQofY29tLmdvb2dsZS5jbG91",
"ZC5vc2xvZ2luLnYxYmV0YUIMT3NMb2dpblByb3RvUAFaQmdvb2dsZS5nb2xh",
"bmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvY2xvdWQvb3Nsb2dpbi92MWJl",
"dGE7b3Nsb2dpbqoCG0dvb2dsZS5DbG91ZC5Pc0xvZ2luLlYxQmV0YcoCG0dv",
"b2dsZVxDbG91ZFxPc0xvZ2luXFYxYmV0YWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Cloud.OsLogin.Common.CommonReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.FieldMaskReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsLogin.V1Beta.LoginProfile), global::Google.Cloud.OsLogin.V1Beta.LoginProfile.Parser, new[]{ "Name", "PosixAccounts", "SshPublicKeys", "Suspended" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsLogin.V1Beta.DeletePosixAccountRequest), global::Google.Cloud.OsLogin.V1Beta.DeletePosixAccountRequest.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsLogin.V1Beta.DeleteSshPublicKeyRequest), global::Google.Cloud.OsLogin.V1Beta.DeleteSshPublicKeyRequest.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsLogin.V1Beta.GetLoginProfileRequest), global::Google.Cloud.OsLogin.V1Beta.GetLoginProfileRequest.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsLogin.V1Beta.GetSshPublicKeyRequest), global::Google.Cloud.OsLogin.V1Beta.GetSshPublicKeyRequest.Parser, new[]{ "Name" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsLogin.V1Beta.ImportSshPublicKeyRequest), global::Google.Cloud.OsLogin.V1Beta.ImportSshPublicKeyRequest.Parser, new[]{ "Parent", "SshPublicKey", "ProjectId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsLogin.V1Beta.ImportSshPublicKeyResponse), global::Google.Cloud.OsLogin.V1Beta.ImportSshPublicKeyResponse.Parser, new[]{ "LoginProfile" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.OsLogin.V1Beta.UpdateSshPublicKeyRequest), global::Google.Cloud.OsLogin.V1Beta.UpdateSshPublicKeyRequest.Parser, new[]{ "Name", "SshPublicKey", "UpdateMask" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// The user profile information used for logging in to a virtual machine on
/// Google Compute Engine.
/// </summary>
public sealed partial class LoginProfile : pb::IMessage<LoginProfile> {
private static readonly pb::MessageParser<LoginProfile> _parser = new pb::MessageParser<LoginProfile>(() => new LoginProfile());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<LoginProfile> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.OsLogin.V1Beta.OsloginReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoginProfile() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoginProfile(LoginProfile other) : this() {
name_ = other.name_;
posixAccounts_ = other.posixAccounts_.Clone();
sshPublicKeys_ = other.sshPublicKeys_.Clone();
suspended_ = other.suspended_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoginProfile Clone() {
return new LoginProfile(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The primary email address that uniquely identifies the user.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "posix_accounts" field.</summary>
public const int PosixAccountsFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Cloud.OsLogin.Common.PosixAccount> _repeated_posixAccounts_codec
= pb::FieldCodec.ForMessage(18, global::Google.Cloud.OsLogin.Common.PosixAccount.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.OsLogin.Common.PosixAccount> posixAccounts_ = new pbc::RepeatedField<global::Google.Cloud.OsLogin.Common.PosixAccount>();
/// <summary>
/// The list of POSIX accounts associated with the user.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.OsLogin.Common.PosixAccount> PosixAccounts {
get { return posixAccounts_; }
}
/// <summary>Field number for the "ssh_public_keys" field.</summary>
public const int SshPublicKeysFieldNumber = 3;
private static readonly pbc::MapField<string, global::Google.Cloud.OsLogin.Common.SshPublicKey>.Codec _map_sshPublicKeys_codec
= new pbc::MapField<string, global::Google.Cloud.OsLogin.Common.SshPublicKey>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Cloud.OsLogin.Common.SshPublicKey.Parser), 26);
private readonly pbc::MapField<string, global::Google.Cloud.OsLogin.Common.SshPublicKey> sshPublicKeys_ = new pbc::MapField<string, global::Google.Cloud.OsLogin.Common.SshPublicKey>();
/// <summary>
/// A map from SSH public key fingerprint to the associated key object.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, global::Google.Cloud.OsLogin.Common.SshPublicKey> SshPublicKeys {
get { return sshPublicKeys_; }
}
/// <summary>Field number for the "suspended" field.</summary>
public const int SuspendedFieldNumber = 4;
private bool suspended_;
/// <summary>
/// Indicates if the user is suspended. A suspended user cannot log in but
/// their profile information is retained.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Suspended {
get { return suspended_; }
set {
suspended_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as LoginProfile);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(LoginProfile other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if(!posixAccounts_.Equals(other.posixAccounts_)) return false;
if (!SshPublicKeys.Equals(other.SshPublicKeys)) return false;
if (Suspended != other.Suspended) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
hash ^= posixAccounts_.GetHashCode();
hash ^= SshPublicKeys.GetHashCode();
if (Suspended != false) hash ^= Suspended.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
posixAccounts_.WriteTo(output, _repeated_posixAccounts_codec);
sshPublicKeys_.WriteTo(output, _map_sshPublicKeys_codec);
if (Suspended != false) {
output.WriteRawTag(32);
output.WriteBool(Suspended);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
size += posixAccounts_.CalculateSize(_repeated_posixAccounts_codec);
size += sshPublicKeys_.CalculateSize(_map_sshPublicKeys_codec);
if (Suspended != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(LoginProfile other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
posixAccounts_.Add(other.posixAccounts_);
sshPublicKeys_.Add(other.sshPublicKeys_);
if (other.Suspended != false) {
Suspended = other.Suspended;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
posixAccounts_.AddEntriesFrom(input, _repeated_posixAccounts_codec);
break;
}
case 26: {
sshPublicKeys_.AddEntriesFrom(input, _map_sshPublicKeys_codec);
break;
}
case 32: {
Suspended = input.ReadBool();
break;
}
}
}
}
}
/// <summary>
/// A request message for deleting a POSIX account entry.
/// </summary>
public sealed partial class DeletePosixAccountRequest : pb::IMessage<DeletePosixAccountRequest> {
private static readonly pb::MessageParser<DeletePosixAccountRequest> _parser = new pb::MessageParser<DeletePosixAccountRequest>(() => new DeletePosixAccountRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DeletePosixAccountRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.OsLogin.V1Beta.OsloginReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeletePosixAccountRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeletePosixAccountRequest(DeletePosixAccountRequest other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeletePosixAccountRequest Clone() {
return new DeletePosixAccountRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// A reference to the POSIX account to update. POSIX accounts are identified
/// by the project ID they are associated with. A reference to the POSIX
/// account is in format `users/{user}/projects/{project}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DeletePosixAccountRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DeletePosixAccountRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DeletePosixAccountRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// A request message for deleting an SSH public key.
/// </summary>
public sealed partial class DeleteSshPublicKeyRequest : pb::IMessage<DeleteSshPublicKeyRequest> {
private static readonly pb::MessageParser<DeleteSshPublicKeyRequest> _parser = new pb::MessageParser<DeleteSshPublicKeyRequest>(() => new DeleteSshPublicKeyRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DeleteSshPublicKeyRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.OsLogin.V1Beta.OsloginReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteSshPublicKeyRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteSshPublicKeyRequest(DeleteSshPublicKeyRequest other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteSshPublicKeyRequest Clone() {
return new DeleteSshPublicKeyRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The fingerprint of the public key to update. Public keys are identified by
/// their SHA-256 fingerprint. The fingerprint of the public key is in format
/// `users/{user}/sshPublicKeys/{fingerprint}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DeleteSshPublicKeyRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DeleteSshPublicKeyRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DeleteSshPublicKeyRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// A request message for retrieving the login profile information for a user.
/// </summary>
public sealed partial class GetLoginProfileRequest : pb::IMessage<GetLoginProfileRequest> {
private static readonly pb::MessageParser<GetLoginProfileRequest> _parser = new pb::MessageParser<GetLoginProfileRequest>(() => new GetLoginProfileRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetLoginProfileRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.OsLogin.V1Beta.OsloginReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetLoginProfileRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetLoginProfileRequest(GetLoginProfileRequest other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetLoginProfileRequest Clone() {
return new GetLoginProfileRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The unique ID for the user in format `users/{user}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetLoginProfileRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetLoginProfileRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetLoginProfileRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// A request message for retrieving an SSH public key.
/// </summary>
public sealed partial class GetSshPublicKeyRequest : pb::IMessage<GetSshPublicKeyRequest> {
private static readonly pb::MessageParser<GetSshPublicKeyRequest> _parser = new pb::MessageParser<GetSshPublicKeyRequest>(() => new GetSshPublicKeyRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetSshPublicKeyRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.OsLogin.V1Beta.OsloginReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetSshPublicKeyRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetSshPublicKeyRequest(GetSshPublicKeyRequest other) : this() {
name_ = other.name_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetSshPublicKeyRequest Clone() {
return new GetSshPublicKeyRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The fingerprint of the public key to retrieve. Public keys are identified
/// by their SHA-256 fingerprint. The fingerprint of the public key is in
/// format `users/{user}/sshPublicKeys/{fingerprint}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetSshPublicKeyRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetSshPublicKeyRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetSshPublicKeyRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// A request message for importing an SSH public key.
/// </summary>
public sealed partial class ImportSshPublicKeyRequest : pb::IMessage<ImportSshPublicKeyRequest> {
private static readonly pb::MessageParser<ImportSshPublicKeyRequest> _parser = new pb::MessageParser<ImportSshPublicKeyRequest>(() => new ImportSshPublicKeyRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ImportSshPublicKeyRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.OsLogin.V1Beta.OsloginReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ImportSshPublicKeyRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ImportSshPublicKeyRequest(ImportSshPublicKeyRequest other) : this() {
parent_ = other.parent_;
SshPublicKey = other.sshPublicKey_ != null ? other.SshPublicKey.Clone() : null;
projectId_ = other.projectId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ImportSshPublicKeyRequest Clone() {
return new ImportSshPublicKeyRequest(this);
}
/// <summary>Field number for the "parent" field.</summary>
public const int ParentFieldNumber = 1;
private string parent_ = "";
/// <summary>
/// The unique ID for the user in format `users/{user}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Parent {
get { return parent_; }
set {
parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "ssh_public_key" field.</summary>
public const int SshPublicKeyFieldNumber = 2;
private global::Google.Cloud.OsLogin.Common.SshPublicKey sshPublicKey_;
/// <summary>
/// The SSH public key and expiration time.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.OsLogin.Common.SshPublicKey SshPublicKey {
get { return sshPublicKey_; }
set {
sshPublicKey_ = value;
}
}
/// <summary>Field number for the "project_id" field.</summary>
public const int ProjectIdFieldNumber = 3;
private string projectId_ = "";
/// <summary>
/// The project ID of the Google Cloud Platform project.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ProjectId {
get { return projectId_; }
set {
projectId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ImportSshPublicKeyRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ImportSshPublicKeyRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Parent != other.Parent) return false;
if (!object.Equals(SshPublicKey, other.SshPublicKey)) return false;
if (ProjectId != other.ProjectId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Parent.Length != 0) hash ^= Parent.GetHashCode();
if (sshPublicKey_ != null) hash ^= SshPublicKey.GetHashCode();
if (ProjectId.Length != 0) hash ^= ProjectId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Parent.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Parent);
}
if (sshPublicKey_ != null) {
output.WriteRawTag(18);
output.WriteMessage(SshPublicKey);
}
if (ProjectId.Length != 0) {
output.WriteRawTag(26);
output.WriteString(ProjectId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Parent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent);
}
if (sshPublicKey_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(SshPublicKey);
}
if (ProjectId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ProjectId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ImportSshPublicKeyRequest other) {
if (other == null) {
return;
}
if (other.Parent.Length != 0) {
Parent = other.Parent;
}
if (other.sshPublicKey_ != null) {
if (sshPublicKey_ == null) {
sshPublicKey_ = new global::Google.Cloud.OsLogin.Common.SshPublicKey();
}
SshPublicKey.MergeFrom(other.SshPublicKey);
}
if (other.ProjectId.Length != 0) {
ProjectId = other.ProjectId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Parent = input.ReadString();
break;
}
case 18: {
if (sshPublicKey_ == null) {
sshPublicKey_ = new global::Google.Cloud.OsLogin.Common.SshPublicKey();
}
input.ReadMessage(sshPublicKey_);
break;
}
case 26: {
ProjectId = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// A response message for importing an SSH public key.
/// </summary>
public sealed partial class ImportSshPublicKeyResponse : pb::IMessage<ImportSshPublicKeyResponse> {
private static readonly pb::MessageParser<ImportSshPublicKeyResponse> _parser = new pb::MessageParser<ImportSshPublicKeyResponse>(() => new ImportSshPublicKeyResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ImportSshPublicKeyResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.OsLogin.V1Beta.OsloginReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ImportSshPublicKeyResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ImportSshPublicKeyResponse(ImportSshPublicKeyResponse other) : this() {
LoginProfile = other.loginProfile_ != null ? other.LoginProfile.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ImportSshPublicKeyResponse Clone() {
return new ImportSshPublicKeyResponse(this);
}
/// <summary>Field number for the "login_profile" field.</summary>
public const int LoginProfileFieldNumber = 1;
private global::Google.Cloud.OsLogin.V1Beta.LoginProfile loginProfile_;
/// <summary>
/// The login profile information for the user.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.OsLogin.V1Beta.LoginProfile LoginProfile {
get { return loginProfile_; }
set {
loginProfile_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ImportSshPublicKeyResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ImportSshPublicKeyResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(LoginProfile, other.LoginProfile)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (loginProfile_ != null) hash ^= LoginProfile.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (loginProfile_ != null) {
output.WriteRawTag(10);
output.WriteMessage(LoginProfile);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (loginProfile_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(LoginProfile);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ImportSshPublicKeyResponse other) {
if (other == null) {
return;
}
if (other.loginProfile_ != null) {
if (loginProfile_ == null) {
loginProfile_ = new global::Google.Cloud.OsLogin.V1Beta.LoginProfile();
}
LoginProfile.MergeFrom(other.LoginProfile);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (loginProfile_ == null) {
loginProfile_ = new global::Google.Cloud.OsLogin.V1Beta.LoginProfile();
}
input.ReadMessage(loginProfile_);
break;
}
}
}
}
}
/// <summary>
/// A request message for updating an SSH public key.
/// </summary>
public sealed partial class UpdateSshPublicKeyRequest : pb::IMessage<UpdateSshPublicKeyRequest> {
private static readonly pb::MessageParser<UpdateSshPublicKeyRequest> _parser = new pb::MessageParser<UpdateSshPublicKeyRequest>(() => new UpdateSshPublicKeyRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UpdateSshPublicKeyRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.OsLogin.V1Beta.OsloginReflection.Descriptor.MessageTypes[7]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateSshPublicKeyRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateSshPublicKeyRequest(UpdateSshPublicKeyRequest other) : this() {
name_ = other.name_;
SshPublicKey = other.sshPublicKey_ != null ? other.SshPublicKey.Clone() : null;
UpdateMask = other.updateMask_ != null ? other.UpdateMask.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateSshPublicKeyRequest Clone() {
return new UpdateSshPublicKeyRequest(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The fingerprint of the public key to update. Public keys are identified by
/// their SHA-256 fingerprint. The fingerprint of the public key is in format
/// `users/{user}/sshPublicKeys/{fingerprint}`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "ssh_public_key" field.</summary>
public const int SshPublicKeyFieldNumber = 2;
private global::Google.Cloud.OsLogin.Common.SshPublicKey sshPublicKey_;
/// <summary>
/// The SSH public key and expiration time.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.OsLogin.Common.SshPublicKey SshPublicKey {
get { return sshPublicKey_; }
set {
sshPublicKey_ = value;
}
}
/// <summary>Field number for the "update_mask" field.</summary>
public const int UpdateMaskFieldNumber = 3;
private global::Google.Protobuf.WellKnownTypes.FieldMask updateMask_;
/// <summary>
/// Mask to control which fields get updated. Updates all if not present.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.FieldMask UpdateMask {
get { return updateMask_; }
set {
updateMask_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UpdateSshPublicKeyRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UpdateSshPublicKeyRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (!object.Equals(SshPublicKey, other.SshPublicKey)) return false;
if (!object.Equals(UpdateMask, other.UpdateMask)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (sshPublicKey_ != null) hash ^= SshPublicKey.GetHashCode();
if (updateMask_ != null) hash ^= UpdateMask.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (sshPublicKey_ != null) {
output.WriteRawTag(18);
output.WriteMessage(SshPublicKey);
}
if (updateMask_ != null) {
output.WriteRawTag(26);
output.WriteMessage(UpdateMask);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (sshPublicKey_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(SshPublicKey);
}
if (updateMask_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateMask);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UpdateSshPublicKeyRequest other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.sshPublicKey_ != null) {
if (sshPublicKey_ == null) {
sshPublicKey_ = new global::Google.Cloud.OsLogin.Common.SshPublicKey();
}
SshPublicKey.MergeFrom(other.SshPublicKey);
}
if (other.updateMask_ != null) {
if (updateMask_ == null) {
updateMask_ = new global::Google.Protobuf.WellKnownTypes.FieldMask();
}
UpdateMask.MergeFrom(other.UpdateMask);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
if (sshPublicKey_ == null) {
sshPublicKey_ = new global::Google.Cloud.OsLogin.Common.SshPublicKey();
}
input.ReadMessage(sshPublicKey_);
break;
}
case 26: {
if (updateMask_ == null) {
updateMask_ = new global::Google.Protobuf.WellKnownTypes.FieldMask();
}
input.ReadMessage(updateMask_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 AddUInt64()
{
var test = new SimpleBinaryOpTest__AddUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AddUInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt64[] inArray1, UInt64[] inArray2, UInt64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt64> _fld1;
public Vector256<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddUInt64 testClass)
{
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddUInt64 testClass)
{
fixed (Vector256<UInt64>* pFld1 = &_fld1)
fixed (Vector256<UInt64>* pFld2 = &_fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt64*)(pFld1)),
Avx.LoadVector256((UInt64*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector256<UInt64> _clsVar1;
private static Vector256<UInt64> _clsVar2;
private Vector256<UInt64> _fld1;
private Vector256<UInt64> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddUInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
}
public SimpleBinaryOpTest__AddUInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Add(
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Add(
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Add(
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Add), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt64>* pClsVar2 = &_clsVar2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt64*)(pClsVar1)),
Avx.LoadVector256((UInt64*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr);
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddUInt64();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AddUInt64();
fixed (Vector256<UInt64>* pFld1 = &test._fld1)
fixed (Vector256<UInt64>* pFld2 = &test._fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt64*)(pFld1)),
Avx.LoadVector256((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt64>* pFld1 = &_fld1)
fixed (Vector256<UInt64>* pFld2 = &_fld2)
{
var result = Avx2.Add(
Avx.LoadVector256((UInt64*)(pFld1)),
Avx.LoadVector256((UInt64*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Add(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.Add(
Avx.LoadVector256((UInt64*)(&test._fld1)),
Avx.LoadVector256((UInt64*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt64> op1, Vector256<UInt64> op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((ulong)(left[0] + right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ulong)(left[i] + right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Add)}<UInt64>(Vector256<UInt64>, Vector256<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using FarseerGames.FarseerPhysics.Interfaces;
#if (XNA)
using Microsoft.Xna.Framework;
#else
using FarseerGames.FarseerPhysics.Mathematics;
#endif
namespace FarseerGames.FarseerPhysics.Collisions
{
/// <summary>
/// Grid is used to test for intersection.
/// Computation of the grid may take a long time, depending on the grid cell size provided.
/// </summary>
public class DistanceGrid : INarrowPhaseCollider
{
private static DistanceGrid _instance;
private DistanceGrid()
{
}
public static DistanceGrid Instance
{
get
{
if (_instance == null)
{
_instance = new DistanceGrid();
}
return _instance;
}
}
private Dictionary<int, DistanceGridData> _distanceGrids = new Dictionary<int, DistanceGridData>();
/// <summary>
///used to calculate a cell size from the AABB whenever the collisionGridCellSize
///is not set explicitly. The more sharp corners a body has, the smaller this Value will
///need to be.
/// </summary>
private const float _gridCellSizeAABBFactor = .1f;
/// <summary>
/// Finds the contactpoints between the two geometries.
/// </summary>
/// <param name="geomA">The first geom.</param>
/// <param name="geomB">The second geom.</param>
/// <param name="contactList">The contact list.</param>
public void Collide(Geom geomA, Geom geomB, ContactList contactList)
{
int vertexIndex = -1;
//Lookup distancegrid A data from list
DistanceGridData geomAGridData = _distanceGrids[geomA.id];
//Iterate the second geometry vertices
for (int i = 0; i < geomB.worldVertices.Count; i++)
{
if (contactList.Count == PhysicsSimulator.MaxContactsToDetect)
break;
vertexIndex += 1;
_vertRef = geomB.WorldVertices[i];
geomA.TransformToLocalCoordinates(ref _vertRef, out _localVertex);
//The geometry intersects when distance <= 0
//Continue in the list if the current vector does not intersect
if (!geomAGridData.Intersect(ref _localVertex, out _feature))
continue;
//If the geometries collide, create a new contact and add it to the contact list.
if (_feature.Distance < 0f)
{
geomA.TransformNormalToWorld(ref _feature.Normal, out _feature.Normal);
Contact contact = new Contact(geomB.WorldVertices[i], _feature.Normal, _feature.Distance,
new ContactId(1, vertexIndex, 2));
contactList.Add(contact);
}
}
//Lookup distancegrid B data from list
DistanceGridData geomBGridData = _distanceGrids[geomB.id];
//Iterate the first geometry vertices
for (int i = 0; i < geomA.WorldVertices.Count; i++)
{
if (contactList.Count == PhysicsSimulator.MaxContactsToDetect)
break;
vertexIndex += 1;
_vertRef = geomA.WorldVertices[i];
geomB.TransformToLocalCoordinates(ref _vertRef, out _localVertex);
if (!geomBGridData.Intersect(ref _localVertex, out _feature))
continue;
if (_feature.Distance < 0f)
{
geomB.TransformNormalToWorld(ref _feature.Normal, out _feature.Normal);
_feature.Normal = -_feature.Normal;
Contact contact = new Contact(geomA.WorldVertices[i], _feature.Normal, _feature.Distance,
new ContactId(2, vertexIndex, 1));
contactList.Add(contact);
}
}
}
/// <summary>
/// Computes the grid.
/// </summary>
/// <param name="geom">The geometry.</param>
/// <exception cref="ArgumentNullException"><c>geometry</c> is null.</exception>
public void CreateDistanceGrid(Geom geom)
{
if (geom == null)
throw new ArgumentNullException("geom", "Geometry can't be null");
//Don't create distancegrid for geometry that already have one.
//NOTE: This should be used to -update- the geometry's distance grid (if grid cell size has changed).
if (_distanceGrids.ContainsKey(geom.id))
return;
//By default, calculate the gridcellsize from the AABB
if (geom.GridCellSize <= 0)
geom.GridCellSize = CalculateGridCellSizeFromAABB(geom.AABB);
//Prepare the geometry. Reset the geometry matrix
Matrix old = geom.Matrix;
geom.Matrix = Matrix.Identity;
//Create data needed for gridcalculations
AABB aabb = new AABB(geom.AABB);
float gridCellSizeInv = 1 / geom.GridCellSize;
//Note: Physics2d have +2
int xSize = (int)Math.Ceiling((double)(aabb.Max.X - aabb.Min.X) * gridCellSizeInv) + 1;
int ySize = (int)Math.Ceiling((double)(aabb.Max.Y - aabb.Min.Y) * gridCellSizeInv) + 1;
float[,] nodes = new float[xSize, ySize];
Vector2 vector = aabb.Min;
for (int x = 0; x < xSize; ++x, vector.X += geom.GridCellSize)
{
vector.Y = aabb.Min.Y;
for (int y = 0; y < ySize; ++y, vector.Y += geom.GridCellSize)
{
nodes[x, y] = geom.GetNearestDistance(ref vector); // shape.GetDistance(vector);
}
}
//restore the geometry
geom.Matrix = old;
DistanceGridData distanceGridData = new DistanceGridData();
distanceGridData.AABB = aabb;
distanceGridData.GridCellSize = geom.GridCellSize;
distanceGridData.GridCellSizeInv = gridCellSizeInv;
distanceGridData.Nodes = nodes;
_distanceGrids.Add(geom.id, distanceGridData);
}
/// <summary>
/// Removes a distance grid from the cache.
/// </summary>
/// <param name="geom">The geom.</param>
public void RemoveDistanceGrid(Geom geom)
{
_distanceGrids.Remove(geom.id);
}
/// <summary>
/// Copies the distance grid from one id to another. This is used in cloning of geometries.
/// </summary>
/// <param name="fromId">From id.</param>
/// <param name="toId">To id.</param>
public void Copy(int fromId, int toId)
{
_distanceGrids.Add(toId, _distanceGrids[fromId]);
}
/// <summary>
/// Calculates the grid cell size from AABB.
/// </summary>
/// <param name="aabb">The AABB.</param>
/// <returns></returns>
private float CalculateGridCellSizeFromAABB(AABB aabb)
{
return aabb.GetShortestSide() * _gridCellSizeAABBFactor;
}
/// <summary>
/// Checks if the specified geom intersect the specified point.
/// </summary>
/// <param name="geom">The geom.</param>
/// <param name="point">The point.</param>
/// <returns></returns>
public bool Intersect(Geom geom, ref Vector2 point)
{
//Lookup the geometry's distancegrid
DistanceGridData gridData = _distanceGrids[geom.id];
Feature feature;
return gridData.Intersect(ref point, out feature);
}
#region Collide variables
private Feature _feature;
private Vector2 _localVertex;
private Vector2 _vertRef;
#endregion
}
/// <summary>
/// Class that holds the distancegrid data
/// </summary>
public sealed class DistanceGridData
{
public AABB AABB;
public float GridCellSize;
public float GridCellSizeInv;
public float[,] Nodes;
/// <summary>
/// Clones this instance.
/// </summary>
/// <returns></returns>
public DistanceGridData Clone()
{
DistanceGridData grid = new DistanceGridData();
grid.GridCellSize = GridCellSize;
grid.GridCellSizeInv = GridCellSizeInv;
grid.AABB = AABB;
grid.Nodes = (float[,])Nodes.Clone();
return grid;
}
/// <summary>
/// Checks if the grid intersects with the specified vector.
/// </summary>
/// <param name="vector">The vector.</param>
/// <param name="feature">The feature.</param>
/// <returns></returns>
public bool Intersect(ref Vector2 vector, out Feature feature)
{
//TODO: Keep and eye out for floating point accuracy issues here. Possibly some
//VERY intermittent errors exist?
if (AABB.Contains(ref vector))
{
int x = (int)Math.Floor((vector.X - AABB.Min.X) * GridCellSizeInv);
int y = (int)Math.Floor((vector.Y - AABB.Min.Y) * GridCellSizeInv);
float bottomLeft = Nodes[x, y];
float bottomRight = Nodes[x + 1, y];
float topLeft = Nodes[x, y + 1];
float topRight = Nodes[x + 1, y + 1];
if (bottomLeft <= 0 ||
bottomRight <= 0 ||
topLeft <= 0 ||
topRight <= 0)
{
float xPercent = (vector.X - (GridCellSize * x + AABB.Min.X)) * GridCellSizeInv;
float yPercent = (vector.Y - (GridCellSize * y + AABB.Min.Y)) * GridCellSizeInv;
float top = MathHelper.Lerp(topLeft, topRight, xPercent);
float bottom = MathHelper.Lerp(bottomLeft, bottomRight, xPercent);
float distance = MathHelper.Lerp(bottom, top, yPercent);
if (distance <= 0)
{
float right = MathHelper.Lerp(bottomRight, topRight, yPercent);
float left = MathHelper.Lerp(bottomLeft, topLeft, yPercent);
Vector2 normal = Vector2.Zero;
normal.X = right - left;
normal.Y = top - bottom;
//Uncommented by Daniel Pramel 08/17/08
//make sure the normal is not zero length.
if (normal.X != 0 || normal.Y != 0)
{
Vector2.Normalize(ref normal, out normal);
feature = new Feature(vector, normal, distance);
return true;
}
}
}
}
feature = new Feature();
return false;
}
}
}
| |
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2011-2012 openxlive.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
/// <summary>
/// A class that implements a Texture Atlas.
/// </summary>
///<remarks>
/// Supported features:
/// The atlas file can be a PVRTC, PNG or any other fomrat supported by Texture2D
/// Quads can be udpated in runtime
/// Quads can be added in runtime
/// Quads can be removed in runtime
/// Quads can be re-ordered in runtime
/// The TextureAtlas capacity can be increased or decreased in runtime
/// OpenGL component: V3F, C4B, T2F.
/// The quads are rendered using an OpenGL ES VBO.
/// To render the quads using an interleaved vertex array list, you should modify the ccConfig.h file
///</remarks>
public class CCTextureAtlas
{
CCQuadVertexBuffer vertexBuffer;
#region Properties
protected internal CCRawList<CCV3F_C4B_T2F_Quad> Quads { get; private set; }
public CCTexture2D Texture { get; set; }
// Indicates whether or not the array buffer of the VBO needs to be updated
protected internal bool Dirty { get; set; }
public int TotalQuads
{
get { return Quads.Count; }
}
public int Capacity
{
get { return Quads.Capacity; }
set { Quads.Capacity = value; }
}
public bool IsAntialiased
{
get { return Texture.IsAntialiased; }
set { Texture.IsAntialiased = value; }
}
#endregion Properties
#region Constructors
public CCTextureAtlas(string file, int capacity) : this(CCTextureCache.SharedTextureCache.AddImage(file), capacity)
{
}
public CCTextureAtlas(CCTexture2D texture, int capacity)
{
Texture = texture;
// Re-initialization is not allowed
Debug.Assert(Quads == null);
if (capacity < 4)
{
capacity = 4;
}
vertexBuffer = new CCQuadVertexBuffer(capacity, CCBufferUsage.WriteOnly);
Quads = vertexBuffer.Data;
Dirty = true;
}
#endregion Constructors
public override string ToString()
{
return string.Format("TotalQuads:{0}", TotalQuads);
}
#region Drawing
public void DrawQuads()
{
DrawNumberOfQuads(TotalQuads, 0);
}
public void DrawNumberOfQuads(int n)
{
DrawNumberOfQuads(n, 0);
}
// draws n quads from an index (offset).
// n + start can't be greater than the capacity of the atlas
public void DrawNumberOfQuads(int n, int start)
{
if (n == 0)
{
return;
}
CCDrawManager.SharedDrawManager.BindTexture(Texture);
if (Dirty)
{
vertexBuffer.UpdateBuffer();
Dirty = false;
}
CCDrawManager.SharedDrawManager.DrawQuadsBuffer(vertexBuffer, start, n);
}
#endregion Drawing
public void ResizeCapacity(int newCapacity)
{
if (newCapacity <= Quads.Capacity)
{
return;
}
vertexBuffer.Capacity = newCapacity;
Quads = vertexBuffer.Data;
Dirty = true;
}
#region Managing Quads
public void IncreaseTotalQuadsWith(int amount)
{
vertexBuffer.Count += amount;
}
public void MoveQuadsFromIndex(int oldIndex, int amount, int newIndex)
{
Debug.Assert(newIndex + amount <= Quads.Count, "insertQuadFromIndex:atIndex: Invalid index");
Debug.Assert(oldIndex < Quads.Count, "insertQuadFromIndex:atIndex: Invalid index");
if (oldIndex == newIndex)
{
return;
}
var tmp = new CCV3F_C4B_T2F_Quad[amount];
Array.Copy(Quads.Elements, oldIndex, tmp, 0, amount);
if (newIndex < oldIndex)
{
// move quads from newIndex to newIndex + amount to make room for buffer
Array.Copy(Quads.Elements, newIndex + amount, Quads.Elements, newIndex, oldIndex - newIndex);
}
else
{
// move quads above back
Array.Copy(Quads.Elements, oldIndex + amount, Quads.Elements, oldIndex, newIndex - oldIndex);
}
Array.Copy(tmp, 0, Quads.Elements, newIndex, amount);
Dirty = true;
}
public void MoveQuadsFromIndex(int index, int newIndex)
{
Debug.Assert(newIndex + (Quads.Count - index) <= Quads.Capacity, "moveQuadsFromIndex move is out of bounds");
Array.Copy(Quads.Elements, index, Quads.Elements, newIndex, Quads.Count - index);
Dirty = true;
}
public void FillWithEmptyQuadsFromIndex(int index, int amount)
{
int to = index + amount;
CCV3F_C4B_T2F_Quad[] elements = Quads.Elements;
var empty = new CCV3F_C4B_T2F_Quad();
for (int i = index; i < to; i++)
{
elements[i] = empty;
}
Dirty = true;
}
public void UpdateQuad(ref CCV3F_C4B_T2F_Quad quad, int index)
{
Debug.Assert(index >= 0 && index <= Quads.Capacity, "updateQuadWithTexture: Invalid index");
Quads.Count = Math.Max(index + 1, Quads.Count);
Quads.Elements[index] = quad;
Dirty = true;
}
public void InsertQuad(ref CCV3F_C4B_T2F_Quad quad, int index)
{
Debug.Assert(index < Quads.Capacity, "insertQuadWithTexture: Invalid index");
Quads.Insert(index, quad);
Dirty = true;
}
public void InsertQuadFromIndex(int oldIndex, int newIndex)
{
Debug.Assert(newIndex >= 0 && newIndex < Quads.Count, "insertQuadFromIndex:atIndex: Invalid index");
Debug.Assert(oldIndex >= 0 && oldIndex < Quads.Count, "insertQuadFromIndex:atIndex: Invalid index");
if (oldIndex == newIndex)
return;
int howMany = Math.Abs(oldIndex - newIndex);
int dst = oldIndex;
int src = oldIndex + 1;
if (oldIndex > newIndex)
{
dst = newIndex + 1;
src = newIndex;
}
CCV3F_C4B_T2F_Quad[] elements = Quads.Elements;
CCV3F_C4B_T2F_Quad quadsBackup = elements[oldIndex];
Array.Copy(elements, src, elements, dst, howMany);
elements[newIndex] = quadsBackup;
Dirty = true;
}
// Removes a quad at a given index number.
// The capacity remains the same, but the total number of quads to be drawn is reduced in 1
public void RemoveQuadAtIndex(int index)
{
Debug.Assert(index < Quads.Count, "removeQuadAtIndex: Invalid index");
Quads.RemoveAt(index);
Dirty = true;
}
public void RemoveQuadsAtIndex(int index, int amount)
{
Debug.Assert(index + amount <= Quads.Count, "removeQuadAtIndex: Invalid index");
Quads.RemoveAt(index, amount);
Dirty = true;
}
public void RemoveAllQuads()
{
Quads.Clear();
Dirty = true;
}
#endregion Managing Quads
}
}
| |
namespace AngleSharp
{
using AngleSharp.Browser;
using AngleSharp.Browser.Dom;
using AngleSharp.Dom;
using System;
using System.Collections.Generic;
/// <summary>
/// A simple and lightweight browsing context.
/// </summary>
public sealed class BrowsingContext : EventTarget, IBrowsingContext, IDisposable
{
#region Fields
private readonly IEnumerable<Object> _originalServices;
private readonly List<Object> _services;
private readonly Sandboxes _security;
private readonly IBrowsingContext? _parent;
private readonly IDocument? _creator;
private readonly IHistory? _history;
private readonly Dictionary<String, WeakReference<IBrowsingContext>> _children;
#endregion
#region ctor
/// <summary>
/// Creates a new browsing context with the given configuration, or the
/// default configuration, if no configuration is provided.
/// </summary>
/// <remarks>
/// This constructor was only added due to PowerShell. See #844 for details.
/// </remarks>
/// <param name="configuration">The optional configuration.</param>
public BrowsingContext(IConfiguration? configuration = null)
: this((configuration ?? AngleSharp.Configuration.Default).Services, Sandboxes.None)
{
}
private BrowsingContext(Sandboxes security)
{
_services = new List<Object>();
_originalServices = _services;
_security = security;
_children = new Dictionary<String, WeakReference<IBrowsingContext>>();
}
internal BrowsingContext(IEnumerable<Object> services, Sandboxes security)
: this(security)
{
_services.AddRange(services);
_originalServices = services;
_history = GetService<IHistory>();
}
internal BrowsingContext(IBrowsingContext parent, Sandboxes security)
: this(parent.OriginalServices, security)
{
_parent = parent;
_creator = _parent.Active;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the currently active document.
/// </summary>
public IDocument? Active
{
get;
set;
}
/// <summary>
/// Gets the document that created the current context, if any. The
/// creator is the active document of the parent at the time of
/// creation.
/// </summary>
public IDocument? Creator => _creator;
/// <summary>
/// Gets the original services for the given browsing context.
/// </summary>
public IEnumerable<Object> OriginalServices => _originalServices;
/// <summary>
/// Gets the current window proxy.
/// </summary>
public IWindow? Current => Active?.DefaultView;
/// <summary>
/// Gets the parent of the current context, if any. If a parent is
/// available, then the current context contains only embedded
/// documents.
/// </summary>
public IBrowsingContext? Parent => _parent;
/// <summary>
/// Gets the session history of the given browsing context, if any.
/// </summary>
public IHistory? SessionHistory => _history;
/// <summary>
/// Gets the sandboxing flag of the context.
/// </summary>
public Sandboxes Security => _security;
#endregion
#region Methods
/// <summary>
/// Gets an instance of the given service.
/// </summary>
/// <typeparam name="T">The type of service to resolve.</typeparam>
/// <returns>The instance of the service or null.</returns>
public T? GetService<T>() where T : class
{
var count = _services.Count;
for (var i = 0; i < count; i++)
{
var service = _services[i];
var instance = service as T;
if (instance is null)
{
if (service is Func<IBrowsingContext, T> creator)
{
instance = creator.Invoke(this);
_services[i] = instance;
}
else
{
continue;
}
}
return instance;
}
return null;
}
/// <summary>
/// Gets all registered instances of the given service.
/// </summary>
/// <typeparam name="T">The type of service to resolve.</typeparam>
/// <returns>An enumerable with all service instances.</returns>
public IEnumerable<T> GetServices<T>() where T : class
{
var count = _services.Count;
for (var i = 0; i < count; i++)
{
var service = _services[i];
var instance = service as T;
if (instance is null)
{
if (service is Func<IBrowsingContext, T> creator)
{
instance = creator.Invoke(this);
_services[i] = instance;
}
else
{
continue;
}
}
yield return instance;
}
}
/// <summary>
/// Creates a new named browsing context as child of the given parent.
/// </summary>
/// <param name="name">The name of the child context, if any.</param>
/// <param name="security">The security flags to apply.</param>
/// <returns></returns>
public IBrowsingContext CreateChild(String? name, Sandboxes security)
{
var context = new BrowsingContext(this, security);
if (name is { Length: > 0 })
{
_children[name] = new WeakReference<IBrowsingContext>(context);
}
return context;
}
/// <summary>
/// Finds a named browsing context.
/// </summary>
/// <param name="name">The name of the browsing context.</param>
/// <returns>The found instance, if any.</returns>
public IBrowsingContext? FindChild(String name)
{
var context = default(IBrowsingContext);
if (!String.IsNullOrEmpty(name) && _children.TryGetValue(name, out var reference))
{
reference.TryGetTarget(out context);
}
return context;
}
/// <summary>
/// Creates a new browsing context with the given configuration, or the
/// default configuration, if no configuration is provided.
/// </summary>
/// <param name="configuration">The optional configuration.</param>
/// <returns>The browsing context to use.</returns>
public static IBrowsingContext New(IConfiguration? configuration = null)
{
if (configuration is null)
{
configuration = AngleSharp.Configuration.Default;
}
return new BrowsingContext(configuration.Services, Sandboxes.None);
}
/// <summary>
/// Creates a new browsing context from the given service.
/// </summary>
/// <param name="instance">The service instance.</param>
/// <returns>The browsing context to use.</returns>
public static IBrowsingContext NewFrom<TService>(TService instance)
{
var configuration = Configuration.Default.WithOnly<TService>(instance);
return new BrowsingContext(configuration.Services, Sandboxes.None);
}
void IDisposable.Dispose()
{
Active?.Dispose();
Active = null;
}
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
namespace System.Reflection.Emit
{
using System.Runtime.InteropServices;
using System;
using CultureInfo = System.Globalization.CultureInfo;
using System.Reflection;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
[HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_FieldBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class FieldBuilder : FieldInfo, _FieldBuilder
{
#region Private Data Members
private int m_fieldTok;
private FieldToken m_tkField;
private TypeBuilder m_typeBuilder;
private String m_fieldName;
private FieldAttributes m_Attributes;
private Type m_fieldType;
#endregion
#region Constructor
[System.Security.SecurityCritical] // auto-generated
internal FieldBuilder(TypeBuilder typeBuilder, String fieldName, Type type,
Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
{
if (fieldName == null)
throw new ArgumentNullException("fieldName");
if (fieldName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "fieldName");
if (fieldName[0] == '\0')
throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), "fieldName");
if (type == null)
throw new ArgumentNullException("type");
if (type == typeof(void))
throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldType"));
Contract.EndContractBlock();
m_fieldName = fieldName;
m_typeBuilder = typeBuilder;
m_fieldType = type;
m_Attributes = attributes & ~FieldAttributes.ReservedMask;
SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(m_typeBuilder.Module);
sigHelp.AddArgument(type, requiredCustomModifiers, optionalCustomModifiers);
int sigLength;
byte[] signature = sigHelp.InternalGetSignature(out sigLength);
m_fieldTok = TypeBuilder.DefineField(m_typeBuilder.GetModuleBuilder().GetNativeHandle(),
typeBuilder.TypeToken.Token, fieldName, signature, sigLength, m_Attributes);
m_tkField = new FieldToken(m_fieldTok, type);
}
#endregion
#region Internal Members
[System.Security.SecurityCritical] // auto-generated
internal void SetData(byte[] data, int size)
{
ModuleBuilder.SetFieldRVAContent(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), m_tkField.Token, data, size);
}
internal TypeBuilder GetTypeBuilder() { return m_typeBuilder; }
#endregion
#region MemberInfo Overrides
internal int MetadataTokenInternal
{
get { return m_fieldTok; }
}
public override Module Module
{
get { return m_typeBuilder.Module; }
}
public override String Name
{
get {return m_fieldName; }
}
public override Type DeclaringType
{
get
{
if (m_typeBuilder.m_isHiddenGlobalType == true)
return null;
return m_typeBuilder;
}
}
public override Type ReflectedType
{
get
{
if (m_typeBuilder.m_isHiddenGlobalType == true)
return null;
return m_typeBuilder;
}
}
#endregion
#region FieldInfo Overrides
public override Type FieldType
{
get { return m_fieldType; }
}
public override Object GetValue(Object obj)
{
// NOTE!! If this is implemented, make sure that this throws
// a NotSupportedException for Save-only dynamic assemblies.
// Otherwise, it could cause the .cctor to be executed.
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override void SetValue(Object obj,Object val,BindingFlags invokeAttr,Binder binder,CultureInfo culture)
{
// NOTE!! If this is implemented, make sure that this throws
// a NotSupportedException for Save-only dynamic assemblies.
// Otherwise, it could cause the .cctor to be executed.
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override RuntimeFieldHandle FieldHandle
{
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
}
public override FieldAttributes Attributes
{
get { return m_Attributes; }
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
#endregion
#region Public Members
public FieldToken GetToken()
{
return m_tkField;
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
public void SetOffset(int iOffset)
{
m_typeBuilder.ThrowIfCreated();
TypeBuilder.SetFieldLayoutOffset(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, iOffset);
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("An alternate API is available: Emit the MarshalAs custom attribute instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public void SetMarshal(UnmanagedMarshal unmanagedMarshal)
{
if (unmanagedMarshal == null)
throw new ArgumentNullException("unmanagedMarshal");
Contract.EndContractBlock();
m_typeBuilder.ThrowIfCreated();
byte[] ubMarshal = unmanagedMarshal.InternalGetBytes();
TypeBuilder.SetFieldMarshal(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, ubMarshal, ubMarshal.Length);
}
[System.Security.SecuritySafeCritical] // auto-generated
public void SetConstant(Object defaultValue)
{
m_typeBuilder.ThrowIfCreated();
TypeBuilder.SetConstantValue(m_typeBuilder.GetModuleBuilder(), GetToken().Token, m_fieldType, defaultValue);
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
throw new ArgumentNullException("con");
if (binaryAttribute == null)
throw new ArgumentNullException("binaryAttribute");
Contract.EndContractBlock();
ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder;
m_typeBuilder.ThrowIfCreated();
TypeBuilder.DefineCustomAttribute(module,
m_tkField.Token, module.GetConstructorToken(con).Token, binaryAttribute, false, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
if (customBuilder == null)
throw new ArgumentNullException("customBuilder");
Contract.EndContractBlock();
m_typeBuilder.ThrowIfCreated();
ModuleBuilder module = m_typeBuilder.Module as ModuleBuilder;
customBuilder.CreateCustomAttribute(module, m_tkField.Token);
}
#endregion
#if !FEATURE_CORECLR
void _FieldBuilder.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _FieldBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _FieldBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _FieldBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using Gibraltar;
using JetBrains.Annotations;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Pdb;
using Mono.Collections.Generic;
namespace Archichect.Reading.AssemblyReading {
public enum DotNetUsage {
_declaresfield,
_declaresevent,
_declaresmethod,
_declaresparameter,
_declaresreturntype,
_declaresvariable,
_isconstrainedby,
_usesmember,
//_usesmemberoftype, // requires declarations of "uses that type" rules, which opens up possibility to use ALL of that type.
// This is not good. Rather, let the user manually add transitive dependencies via the member if this is needed!
_usestype,
_directlyderivedfrom,
_directlyimplements,
_usesasgenericargument,
}
public abstract class AbstractDotNetAssemblyDependencyReader : AbstractDependencyReader {
public const string _abstract = nameof(_abstract);
public const string _array = nameof(_array);
public const string _class = nameof(_class);
public const string _const = nameof(_const);
public const string _ctor = nameof(_ctor);
public const string _definition = nameof(_definition);
public const string _enum = nameof(_enum);
public const string _get = nameof(_get);
public const string _in = nameof(_in);
public const string _interface = nameof(_interface);
public const string _internal = nameof(_internal);
public const string _nested = nameof(_nested);
public const string _nestedprivate = nameof(_nestedprivate);
public const string _notpublic = nameof(_notpublic);
public const string _notserialized = nameof(_notserialized);
public const string _optional = nameof(_optional);
public const string _out = nameof(_out);
public const string _pinned = nameof(_pinned);
public const string _primitive = nameof(_primitive);
public const string _private = nameof(_private);
public const string _protected = nameof(_protected);
public const string _public = nameof(_public);
public const string _readonly = nameof(_readonly);
public const string _ref = nameof(_ref);
public const string _return = nameof(_return);
public const string _runtimespecialname = nameof(_runtimespecialname);
public const string _sealed = nameof(_sealed);
public const string _set = nameof(_set);
public const string _specialname = nameof(_specialname);
public const string _static = nameof(_static);
public const string _struct = nameof(_struct);
public const string _virtual = nameof(_virtual);
public const string _declaresfield = nameof(DotNetUsage._declaresfield);
public const string _declaresevent = nameof(DotNetUsage._declaresevent);
public const string _declaresparameter = nameof(DotNetUsage._declaresparameter);
public const string _declaresreturntype = nameof(DotNetUsage._declaresreturntype);
public const string _declaresvariable = nameof(DotNetUsage._declaresvariable);
public const string _usesmember = nameof(DotNetUsage._usesmember);
public const string _usestype = nameof(DotNetUsage._usestype);
public const string _directlyderivedfrom = nameof(DotNetUsage._directlyderivedfrom);
public const string _directlyimplements = nameof(DotNetUsage._directlyimplements);
public const string _usesasgenericargument = nameof(DotNetUsage._usesasgenericargument);
public static readonly ItemType DOTNETASSEMBLY = DotNetAssemblyDependencyReaderFactory.DOTNETASSEMBLY;
public static readonly ItemType DOTNETEVENT = DotNetAssemblyDependencyReaderFactory.DOTNETEVENT;
public static readonly ItemType DOTNETFIELD = DotNetAssemblyDependencyReaderFactory.DOTNETFIELD;
public static readonly ItemType DOTNETITEM = DotNetAssemblyDependencyReaderFactory.DOTNETITEM;
public static readonly ItemType DOTNETMETHOD = DotNetAssemblyDependencyReaderFactory.DOTNETMETHOD;
public static readonly ItemType DOTNETPARAMETER = DotNetAssemblyDependencyReaderFactory.DOTNETPARAMETER;
public static readonly ItemType DOTNETPROPERTY = DotNetAssemblyDependencyReaderFactory.DOTNETPROPERTY;
public static readonly ItemType DOTNETTYPE = DotNetAssemblyDependencyReaderFactory.DOTNETTYPE;
public static readonly ItemType DOTNETGENERICPARAMETER = DotNetAssemblyDependencyReaderFactory.DOTNETTYPE;
public static readonly ItemType DOTNETVARIABLE = DotNetAssemblyDependencyReaderFactory.DOTNETVARIABLE;
protected readonly DotNetAssemblyDependencyReaderFactory ReaderFactory;
protected readonly DotNetAssemblyDependencyReaderFactory.ReadingContext _readingContext;
public readonly string Assemblyname;
protected readonly Intern<RawUsingItem> _rawUsingItemsCache = new Intern<RawUsingItem>();
protected readonly string[] GET_MARKER = { _get };
protected readonly string[] SET_MARKER = { _set };
private Dictionary<RawUsedItem, Item> _rawItems2Items;
protected AbstractDotNetAssemblyDependencyReader(DotNetAssemblyDependencyReaderFactory readerFactory, string fileName,
DotNetAssemblyDependencyReaderFactory.ReadingContext readingContext)
: base(Path.GetFullPath(fileName), Path.GetFileName(fileName)) {
ReaderFactory = readerFactory;
_readingContext = readingContext;
Assemblyname = Path.GetFileNameWithoutExtension(fileName);
}
public string AssemblyName => Assemblyname;
internal static void Init() {
#pragma warning disable 168
// ReSharper disable once UnusedVariable
// the only purpose of this instruction is to create a reference to Mono.Cecil.Pdb.
// Otherwise Visual Studio won't copy that assembly to the output path.
var readerProvider = new PdbReaderProvider();
#pragma warning restore 168
}
protected abstract class RawAbstractItem {
public readonly ItemType ItemType;
public readonly string NamespaceName;
public readonly string ClassName;
public readonly string AssemblyName;
private readonly string _assemblyVersion;
private readonly string _assemblyCulture;
public readonly string MemberName;
[CanBeNull, ItemNotNull]
private readonly string[] _markers;
[NotNull]
protected readonly WorkingGraph _readingGraph;
protected RawAbstractItem([NotNull] ItemType itemType, [NotNull] string namespaceName, [NotNull] string className,
[NotNull] string assemblyName, [CanBeNull] string assemblyVersion, [CanBeNull] string assemblyCulture,
[CanBeNull] string memberName, [CanBeNull, ItemNotNull] string[] markers, [NotNull] WorkingGraph readingGraph) {
if (itemType == null) {
throw new ArgumentNullException(nameof(itemType));
}
if (namespaceName == null) {
throw new ArgumentNullException(nameof(namespaceName));
}
if (className == null) {
throw new ArgumentNullException(nameof(className));
}
if (assemblyName == null) {
throw new ArgumentNullException(nameof(assemblyName));
}
ItemType = itemType;
NamespaceName = string.Intern(namespaceName);
ClassName = string.Intern(className);
AssemblyName = string.Intern(assemblyName);
_assemblyVersion = string.Intern(assemblyVersion ?? "");
_assemblyCulture = string.Intern(assemblyCulture ?? "");
MemberName = string.Intern(memberName ?? "");
_markers = markers;
_readingGraph = readingGraph;
}
[ExcludeFromCodeCoverage]
public override string ToString() {
return NamespaceName + ":" + ClassName + ":" + AssemblyName + ";" + _assemblyVersion + ";" +
_assemblyCulture + ":" + MemberName + (_markers == null ? "" : "'" + string.Join("+", _markers));
}
[NotNull]
public virtual Item ToItem() {
return _readingGraph.CreateItem(ItemType, new[] { NamespaceName, ClassName, AssemblyName, _assemblyVersion, _assemblyCulture, MemberName }, _markers);
}
[NotNull]
protected RawUsedItem ToRawUsedItem() {
return RawUsedItem.New(ItemType, NamespaceName, ClassName, AssemblyName, _assemblyVersion, _assemblyCulture, MemberName, _markers, _readingGraph);
}
protected bool EqualsRawAbstractItem(RawAbstractItem other) {
return this == other
|| other != null
&& other.NamespaceName == NamespaceName
&& other.ClassName == ClassName
&& other.AssemblyName == AssemblyName
&& other._assemblyVersion == _assemblyVersion
&& other._assemblyCulture == _assemblyCulture
&& other.MemberName == MemberName;
}
protected int GetRawAbstractItemHashCode() {
return unchecked(NamespaceName.GetHashCode() ^ ClassName.GetHashCode() ^ AssemblyName.GetHashCode() ^ (MemberName ?? "").GetHashCode());
}
}
protected sealed class RawUsingItem : RawAbstractItem {
private readonly ItemTail _tail;
private Item _item;
private RawUsedItem _usedItem;
private RawUsingItem([NotNull] ItemType itemType, [NotNull] string namespaceName, [NotNull] string className,
[NotNull] string assemblyName, [CanBeNull] string assemblyVersion, [CanBeNull] string assemblyCulture,
[CanBeNull] string memberName, [CanBeNull, ItemNotNull] string[] markers, [CanBeNull] ItemTail tail,
[NotNull] WorkingGraph readingGraph)
: base(itemType, namespaceName, className, assemblyName, assemblyVersion, assemblyCulture, memberName, markers, readingGraph) {
_tail = tail;
}
public static RawUsingItem New([NotNull] Intern<RawUsingItem> cache, [NotNull] ItemType itemType,
[NotNull] string namespaceName, [NotNull] string className, [NotNull] string assemblyName,
[CanBeNull] string assemblyVersion, [CanBeNull] string assemblyCulture, [CanBeNull] string memberName,
[CanBeNull, ItemNotNull] string[] markers, [CanBeNull] ItemTail tail, [NotNull] WorkingGraph readingGraph) {
return cache.GetReference(new RawUsingItem(itemType, namespaceName, className, assemblyName,
assemblyVersion, assemblyCulture, memberName, markers, tail, readingGraph));
}
public override string ToString() {
return "RawUsingItem(" + base.ToString() + ":" + _tail + ")";
}
public override bool Equals(object obj) {
return EqualsRawAbstractItem(obj as RawUsingItem);
}
public override int GetHashCode() {
return GetRawAbstractItemHashCode();
}
public override Item ToItem() {
// ReSharper disable once ConvertIfStatementToNullCoalescingExpression
if (_item == null) {
_item = base.ToItem().Append(_readingGraph, _tail);
}
return _item;
}
public new RawUsedItem ToRawUsedItem() {
// ReSharper disable once ConvertIfStatementToNullCoalescingExpression
if (_usedItem == null) {
_usedItem = base.ToRawUsedItem();
}
return _usedItem;
}
}
protected sealed class RawUsedItem : RawAbstractItem {
private RawUsedItem([NotNull] ItemType itemType, [NotNull] string namespaceName, [NotNull] string className,
[NotNull] string assemblyName, [CanBeNull] string assemblyVersion, [CanBeNull] string assemblyCulture,
[CanBeNull] string memberName, [CanBeNull, ItemNotNull] string[] markers, [NotNull] WorkingGraph readingGraph)
: base(itemType, namespaceName, className, assemblyName, assemblyVersion, assemblyCulture, memberName, markers, readingGraph) {
}
public static RawUsedItem New([NotNull] ItemType itemType, [NotNull] string namespaceName, [NotNull] string className,
[NotNull] string assemblyName, [CanBeNull] string assemblyVersion, [CanBeNull] string assemblyCulture,
[CanBeNull] string memberName, [CanBeNull, ItemNotNull] string[] markers, [NotNull] WorkingGraph readingGraph) {
//return Intern<RawUsedItem>.GetReference(new RawUsedItem(namespaceName, className, assemblyName,
// assemblyVersion, assemblyCulture, memberName, markers));
// Dont make unique - costs lot of time; and Raw...Items are anyway removed at end of DLL reading.
return new RawUsedItem(itemType, namespaceName, className, assemblyName, assemblyVersion, assemblyCulture, memberName, markers, readingGraph);
}
[ExcludeFromCodeCoverage]
public override string ToString() {
return "RawUsedItem(" + base.ToString() + ")";
}
[CanBeNull] // null (I think) if assemblies do not match (different compiles) and hence a used item is not found in target reader.
public Item ToItemWithTail(WorkingGraph readingGraph, AbstractDotNetAssemblyDependencyReader reader,
int depth) {
return reader.GetFullItemFor(readingGraph, this, depth);
}
public override bool Equals(object obj) {
return EqualsRawAbstractItem(obj as RawUsedItem);
}
public override int GetHashCode() {
return GetRawAbstractItemHashCode();
}
}
[NotNull]
protected abstract IEnumerable<RawUsingItem> ReadUsingItems(int depth, WorkingGraph readingGraph);
[CanBeNull] // null (I think) if assemblies do not match (different compiles) and hence a used item is not found in target reader.
protected Item GetFullItemFor(WorkingGraph readingGraph, RawUsedItem rawUsedItem, int depth) {
if (_rawItems2Items == null) {
_rawItems2Items = new Dictionary<RawUsedItem, Item>();
foreach (var u in ReadUsingItems(depth + 1, readingGraph)) {
RawUsedItem usedItem = u.ToRawUsedItem();
_rawItems2Items[usedItem] = u.ToItem();
}
}
Item result;
_rawItems2Items.TryGetValue(rawUsedItem, out result);
return result;
}
protected sealed class RawDependency {
private readonly SequencePoint _sequencePoint;
private readonly AbstractDotNetAssemblyDependencyReader _readerForUsedItem;
public readonly RawUsingItem UsingItem;
public readonly RawUsedItem UsedItem;
public readonly DotNetUsage Usage;
public RawDependency([NotNull] RawUsingItem usingItem, [NotNull] RawUsedItem usedItem,
DotNetUsage usage, [CanBeNull] SequencePoint sequencePoint, AbstractDotNetAssemblyDependencyReader readerForUsedItem) {
if (usingItem == null) {
throw new ArgumentNullException(nameof(usingItem));
}
if (usedItem == null) {
throw new ArgumentNullException(nameof(usedItem));
}
UsingItem = usingItem;
UsedItem = usedItem;
Usage = usage;
_readerForUsedItem = readerForUsedItem;
_sequencePoint = sequencePoint;
}
public override bool Equals(object obj) {
var other = obj as RawDependency;
return this == obj
|| other != null
&& Equals(other.UsedItem, UsedItem)
&& Equals(other.UsingItem, UsingItem)
&& Equals(other._sequencePoint, _sequencePoint);
}
public override int GetHashCode() {
return UsedItem.GetHashCode() ^ UsingItem.GetHashCode();
}
[ExcludeFromCodeCoverage]
public override string ToString() {
return "RawDep " + UsingItem + "=>" + UsedItem;
}
[NotNull]
private Dependency ToDependency(WorkingGraph readingGraph, Item usedItem, string containerUri) {
return readingGraph.CreateDependency(UsingItem.ToItem(), usedItem, _sequencePoint == null
? (ISourceLocation)new LocalSourceLocation(containerUri, UsingItem.NamespaceName + "." + UsingItem.ClassName + (string.IsNullOrWhiteSpace(UsingItem.MemberName) ? "" : "." + UsingItem.MemberName))
: new ProgramFileSourceLocation(containerUri, _sequencePoint.Document.Url, _sequencePoint.StartLine, _sequencePoint.StartColumn, _sequencePoint.EndLine, _sequencePoint.EndColumn),
Usage.ToString(), 1);
}
[NotNull]
public Dependency ToDependencyWithTail(WorkingGraph readingGraph, int depth, string containerUri) {
// ?? fires if reader == null (i.e., target assembly is not read in), or if assemblies do not match (different compiles) and hence a used item is not found in target reader.
Item usedItem = (_readerForUsedItem == null ? null : UsedItem.ToItemWithTail(readingGraph, _readerForUsedItem, depth)) ?? UsedItem.ToItem();
return ToDependency(readingGraph, usedItem, containerUri);
}
}
[CanBeNull]
protected ItemTail GetCustomSections(WorkingGraph readingGraph, Collection<CustomAttribute> customAttributes, [CanBeNull] ItemTail customSections) {
ItemTail result = customSections;
foreach (var customAttribute in customAttributes) {
result = ExtractCustomSections(readingGraph, customAttribute, null) ?? result;
}
return result;
}
private ItemTail ExtractCustomSections(WorkingGraph readingGraph, CustomAttribute customAttribute, ItemTail parent) {
TypeReference customAttributeTypeReference = customAttribute.AttributeType;
TypeDefinition attributeType = Resolve(customAttributeTypeReference);
bool isSectionAttribute = attributeType != null
&& attributeType.Interfaces.Any(i => i.FullName == "Archichect.ISectionAttribute");
if (isSectionAttribute) {
string[] keys = attributeType.Properties.Select(property => property.Name).ToArray();
FieldDefinition itemTypeNameField = attributeType.Fields.FirstOrDefault(f => f.Name == "ITEM_TYPE");
if (itemTypeNameField == null) {
//??? Log.WriteError();
throw new Exception("string constant ITEM_TYPE not defined in " + attributeType.FullName);
} else {
string itemTypeName = "" + itemTypeNameField.Constant;
ItemType itemType = GetOrDeclareType(itemTypeName, Enumerable.Repeat("CUSTOM", keys.Length), keys.Select(k => "." + k));
var args = keys.Select((k, i) => new {
Key = k,
Index = i,
Property = customAttribute.Properties.FirstOrDefault(p => p.Name == k)
});
string[] values = args.Select(a => a.Property.Name == null
? parent?.Values[a.Index] ?? ""
: "" + a.Property.Argument.Value).ToArray();
return ItemTail.New(readingGraph.ItemTailCache, itemType, values);
}
} else {
return parent;
}
}
[CanBeNull]
protected TypeDefinition Resolve(TypeReference typeReference) {
AssemblyNameReference assemblyNameRef = typeReference.Scope as AssemblyNameReference;
string assemblyFullName = assemblyNameRef?.FullName;
if (assemblyFullName == null || _readingContext.UnresolvableAssemblies.Contains(assemblyFullName)) {
return null;
} else {
try {
return typeReference.Resolve();
} catch (AssemblyResolutionException ex) {
_readingContext.ExceptionCount++;
if (_readingContext.UnresolvableAssemblies.Add(assemblyFullName)) {
Log.WriteInfo("Cannot resolve " + typeReference + " - reason: " + ex.Message);
}
return null;
} catch (Exception ex) {
_readingContext.ExceptionCount++;
Log.WriteWarning("Cannot resolve " + typeReference + " - reason: " + ex.Message);
return null;
}
}
}
private ItemType GetOrDeclareType(string itemTypeName, IEnumerable<string> keys, IEnumerable<string> subkeys) {
return ReaderFactory.GetOrCreateDotNetType(itemTypeName,
DotNetAssemblyDependencyReaderFactory.DOTNETITEM.Keys.Concat(keys).ToArray(),
DotNetAssemblyDependencyReaderFactory.DOTNETITEM.SubKeys.Concat(subkeys).ToArray());
}
protected static void GetTypeInfo(TypeReference reference, out string namespaceName, out string className,
out string assemblyName, out string assemblyVersion, out string assemblyCulture) {
if (reference.DeclaringType != null) {
string parentClassName, ignore1, ignore2, ignore3;
GetTypeInfo(reference.DeclaringType, out namespaceName, out parentClassName, out ignore1, out ignore2, out ignore3);
className = parentClassName + "/" + CleanClassName(reference.Name);
} else {
namespaceName = reference.Namespace;
className = CleanClassName(reference.Name);
}
DotNetAssemblyDependencyReaderFactory.GetTypeAssemblyInfo(reference, out assemblyName, out assemblyVersion, out assemblyCulture);
}
private static string CleanClassName(string className) {
if (!string.IsNullOrEmpty(className)) {
className = className.TrimEnd('[', ']');
int pos = className.LastIndexOf('`');
if (pos > 0) {
className = className.Substring(0, pos);
}
}
return className;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Threading.Tasks.Dataflow.Tests
{
public class BufferBlockTests
{
[Fact]
public void TestCtor()
{
var block = new BufferBlock<int>();
Assert.Equal(expected: 0, actual: block.Count);
Assert.False(block.Completion.IsCompleted);
block = new BufferBlock<int>(new DataflowBlockOptions { MaxMessagesPerTask = 1 });
Assert.Equal(expected: 0, actual: block.Count);
Assert.False(block.Completion.IsCompleted);
block = new BufferBlock<int>(new DataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = new CancellationToken(true) });
Assert.Equal(expected: 0, actual: block.Count);
}
[Fact]
public void TestArgumentExceptions()
{
Assert.Throws<ArgumentNullException>(() => new BufferBlock<int>(null));
DataflowTestHelpers.TestArgumentsExceptions(new BufferBlock<int>());
}
[Fact]
public void TestToString()
{
DataflowTestHelpers.TestToString(nameFormat =>
nameFormat != null ?
new BufferBlock<int>(new DataflowBlockOptions() { NameFormat = nameFormat }) :
new BufferBlock<int>());
}
[Fact]
public async Task TestOfferMessage()
{
var generators = new Func<BufferBlock<int>>[]
{
() => new BufferBlock<int>(),
() => new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 10 }),
() => new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 10, MaxMessagesPerTask = 1 })
};
foreach (var generator in generators)
{
DataflowTestHelpers.TestOfferMessage_ArgumentValidation(generator());
var target = generator();
DataflowTestHelpers.TestOfferMessage_AcceptsDataDirectly(target);
int ignored;
while (target.TryReceive(out ignored)) ;
DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target);
await target.Completion;
target = generator();
await DataflowTestHelpers.TestOfferMessage_AcceptsViaLinking(target);
while (target.TryReceive(out ignored)) ;
DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target);
await target.Completion;
}
}
[Fact]
public void TestPost()
{
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1 })
{
var bb = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
Assert.True(bb.Post(0));
bb.Complete();
Assert.False(bb.Post(0));
}
}
[Fact]
public Task TestCompletionTask()
{
return DataflowTestHelpers.TestCompletionTask(() => new BufferBlock<int>());
}
[Fact]
public async Task TestLinkToOptions()
{
const int Messages = 1;
foreach (bool append in DataflowTestHelpers.BooleanValues)
{
var bb = new BufferBlock<int>();
var values = new int[Messages];
var targets = new ActionBlock<int>[Messages];
for (int i = 0; i < Messages; i++)
{
int slot = i;
targets[i] = new ActionBlock<int>(item => values[slot] = item);
bb.LinkTo(targets[i], new DataflowLinkOptions { MaxMessages = 1, Append = append });
}
bb.PostRange(0, Messages);
bb.Complete();
await bb.Completion;
for (int i = 0; i < Messages; i++)
{
Assert.Equal(
expected: append ? i : Messages - i - 1,
actual: values[i]);
}
}
}
[Fact]
public void TestReceives()
{
for (int test = 0; test < 3; test++)
{
var bb = new BufferBlock<int>();
bb.PostRange(0, 5);
int item;
switch (test)
{
case 0:
IList<int> items;
Assert.True(bb.TryReceiveAll(out items));
Assert.Equal(expected: 5, actual: items.Count);
for (int i = 0; i < items.Count; i++)
{
Assert.Equal(expected: i, actual: items[i]);
}
Assert.False(bb.TryReceiveAll(out items));
break;
case 1:
for (int i = 0; i < 5; i++)
{
Assert.True(bb.TryReceive(f => true, out item));
Assert.Equal(expected: i, actual: item);
}
Assert.False(bb.TryReceive(f => true, out item));
break;
case 2:
for (int i = 0; i < 5; i++)
{
Assert.False(bb.TryReceive(f => f == i + 1, out item));
Assert.True(bb.TryReceive(f => f == i, out item));
Assert.Equal(expected: i, actual: item);
}
Assert.False(bb.TryReceive(f => true, out item));
break;
}
}
}
[Fact]
public async Task TestBoundedReceives()
{
for (int test = 0; test < 4; test++)
{
var bb = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1 });
Assert.True(bb.Post(0));
const int sends = 5;
for (int i = 1; i <= sends; i++)
{
Task<bool> send = bb.SendAsync(i);
Assert.True(await bb.OutputAvailableAsync()); // wait for previously posted/sent item
int item;
switch (test)
{
case 0:
IList<int> items;
Assert.True(bb.TryReceiveAll(out items));
Assert.Equal(expected: 1, actual: items.Count);
Assert.Equal(expected: i - 1, actual: items[0]);
break;
case 1:
Assert.True(bb.TryReceive(f => true, out item));
Assert.Equal(expected: i - 1, actual: item);
break;
case 2:
Assert.False(bb.TryReceive(f => f == i, out item));
Assert.True(bb.TryReceive(f => f == i - 1, out item));
Assert.Equal(expected: i - 1, actual: item);
break;
case 3:
Assert.Equal(expected: i - 1, actual: await bb.ReceiveAsync());
break;
}
}
// Receive remaining item
Assert.Equal(expected: sends, actual: await bb.ReceiveAsync());
bb.Complete();
await bb.Completion;
}
}
[Fact]
[OuterLoop] // waits for a period of time
public async Task TestCircularLinking()
{
for (int boundedCapacity = 1; boundedCapacity <= 3; boundedCapacity++)
{
var b = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
b.PostRange(0, boundedCapacity);
using (b.LinkTo(b))
{
await Task.Delay(200);
}
Assert.Equal(expected: boundedCapacity, actual: b.Count);
}
}
[Fact]
public async Task TestProducerConsumer()
{
foreach (TaskScheduler scheduler in new[] { TaskScheduler.Default, new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler })
foreach (int maxMessagesPerTask in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
{
const int Messages = 100;
var bb = new BufferBlock<int>(new DataflowBlockOptions
{
BoundedCapacity = boundedCapacity,
MaxMessagesPerTask = maxMessagesPerTask,
TaskScheduler = scheduler
});
await Task.WhenAll(
Task.Run(async delegate { // consumer
int i = 0;
while (await bb.OutputAvailableAsync())
{
Assert.Equal(expected: i, actual: await bb.ReceiveAsync());
i++;
}
}),
Task.Run(async delegate { // producer
for (int i = 0; i < Messages; i++)
{
await bb.SendAsync(i);
}
bb.Complete();
}));
}
}
[Fact]
public async Task TestMessagePostponement()
{
foreach (int boundedCapacity in new[] { 1, 3 })
{
const int Excess = 10;
var b = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = boundedCapacity });
var sendAsync = new Task<bool>[boundedCapacity + Excess];
for (int i = 0; i < boundedCapacity + Excess; i++)
sendAsync[i] = b.SendAsync(i);
b.Complete();
for (int i = 0; i < boundedCapacity; i++)
{
Assert.True(sendAsync[i].IsCompleted);
Assert.True(sendAsync[i].Result);
}
for (int i = 0; i < Excess; i++)
{
Assert.False(await sendAsync[boundedCapacity + i]);
}
}
}
[Fact]
public async Task TestReserveReleaseConsume()
{
var bb = new BufferBlock<int>();
bb.Post(1);
await DataflowTestHelpers.TestReserveAndRelease(bb);
bb = new BufferBlock<int>();
bb.Post(2);
await DataflowTestHelpers.TestReserveAndConsume(bb);
}
[Fact]
public void TestSourceCoreSpecifics()
{
var messageHeader = new DataflowMessageHeader(1);
bool consumed;
var block = new BufferBlock<int>();
((ITargetBlock<int>)block).OfferMessage(messageHeader, 42, null, false);
var target = new ActionBlock<int>(i => { });
Assert.True(((ISourceBlock<int>)block).ReserveMessage(messageHeader, target));
((ISourceBlock<int>)block).ReleaseReservation(messageHeader, target);
((ISourceBlock<int>)block).ConsumeMessage(messageHeader, DataflowBlock.NullTarget<int>(), out consumed);
Assert.True(consumed);
Assert.Equal(expected: 0, actual: block.Count);
}
[Fact]
public async Task TestOutputAvailableAsyncAfterTryReceiveAll()
{
Func<Task<bool>> generator = () => {
var buffer = new BufferBlock<object>();
buffer.Post(null);
IList<object> items;
buffer.TryReceiveAll(out items);
var outputAvailableAsync = buffer.OutputAvailableAsync();
buffer.Post(null);
return outputAvailableAsync;
};
bool[] results = await Task.WhenAll(Enumerable.Repeat(0, 10).Select(_ => generator()));
Assert.All(results, Assert.True);
}
[Fact]
public async Task TestCountZeroAtCompletion()
{
var cts = new CancellationTokenSource();
var buffer = new BufferBlock<int>(new DataflowBlockOptions() { CancellationToken = cts.Token });
buffer.Post(1);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => buffer.Completion);
Assert.Equal(expected: 0, actual: buffer.Count);
cts = new CancellationTokenSource();
buffer = new BufferBlock<int>();
buffer.Post(1);
((IDataflowBlock)buffer).Fault(new InvalidOperationException());
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => buffer.Completion);
Assert.Equal(expected: 0, actual: buffer.Count);
}
[Fact]
public void TestCount()
{
var bb = new BufferBlock<int>();
for (int i = 1; i <= 10; i++)
{
bb.Post(i);
Assert.Equal(expected: i, actual: bb.Count);
}
for (int i = 10; i > 0; i--)
{
int item;
Assert.True(bb.TryReceive(out item));
Assert.Equal(expected: 11 - i, actual: item);
Assert.Equal(expected: i - 1, actual: bb.Count);
}
}
[Fact]
public async Task TestChainedSendReceive()
{
foreach (bool post in DataflowTestHelpers.BooleanValues)
{
const int Iters = 10;
var network = DataflowTestHelpers.Chain<BufferBlock<int>, int>(4, () => new BufferBlock<int>());
for (int i = 0; i < Iters; i++)
{
if (post)
{
network.Post(i);
}
else
{
await network.SendAsync(i);
}
Assert.Equal(expected: i, actual: await network.ReceiveAsync());
}
}
}
[Fact]
public async Task TestSendAllThenReceive()
{
foreach (bool post in DataflowTestHelpers.BooleanValues)
{
const int Iters = 10;
var network = DataflowTestHelpers.Chain<BufferBlock<int>, int>(4, () => new BufferBlock<int>());
if (post)
{
network.PostRange(0, Iters);
}
else
{
await Task.WhenAll(from i in Enumerable.Range(0, Iters) select network.SendAsync(i));
}
for (int i = 0; i < Iters; i++)
{
Assert.Equal(expected: i, actual: await network.ReceiveAsync());
}
}
}
[Fact]
public async Task TestPrecanceled()
{
var bb = new BufferBlock<int>(
new DataflowBlockOptions { CancellationToken = new CancellationToken(canceled: true) });
int ignoredValue;
IList<int> ignoredValues;
IDisposable link = bb.LinkTo(DataflowBlock.NullTarget<int>());
Assert.NotNull(link);
link.Dispose();
Assert.False(bb.Post(42));
var t = bb.SendAsync(42);
Assert.True(t.IsCompleted);
Assert.False(t.Result);
Assert.Equal(expected: 0, actual: bb.Count);
Assert.False(bb.TryReceiveAll(out ignoredValues));
Assert.False(bb.TryReceive(out ignoredValue));
Assert.NotNull(bb.Completion);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.Completion);
bb.Complete(); // just make sure it doesn't throw
}
[Fact]
public async Task TestFaultingAndCancellation()
{
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1 })
foreach (bool fault in DataflowTestHelpers.BooleanValues)
{
var cts = new CancellationTokenSource();
var bb = new BufferBlock<int>(new DataflowBlockOptions { CancellationToken = cts.Token, BoundedCapacity = boundedCapacity });
Task<bool>[] sends = Enumerable.Range(0, 4).Select(i => bb.SendAsync(i)).ToArray();
Assert.Equal(expected: 0, actual: await bb.ReceiveAsync());
Assert.Equal(expected: 1, actual: await bb.ReceiveAsync());
if (fault)
{
Assert.Throws<ArgumentNullException>(() => ((IDataflowBlock)bb).Fault(null));
((IDataflowBlock)bb).Fault(new InvalidCastException());
await Assert.ThrowsAsync<InvalidCastException>(() => bb.Completion);
}
else
{
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.Completion);
}
await Task.WhenAll(sends);
Assert.Equal(expected: 0, actual: bb.Count);
}
}
[Fact]
public async Task TestFaultyScheduler()
{
var bb = new BufferBlock<int>(new DataflowBlockOptions
{
TaskScheduler = new DelegateTaskScheduler
{
QueueTaskDelegate = delegate { throw new FormatException(); }
}
});
bb.Post(42);
bb.LinkTo(DataflowBlock.NullTarget<int>());
await Assert.ThrowsAsync<TaskSchedulerException>(() => bb.Completion);
}
[Fact]
public async Task TestFaultyTarget()
{
ISourceBlock<int> bb = new BufferBlock<int>();
bb.Fault(new InvalidCastException());
await Assert.ThrowsAsync<InvalidCastException>(() => bb.Completion);
Assert.Throws<FormatException>(() => {
bb.LinkTo(new DelegatePropagator<int, int>
{
FaultDelegate = delegate { throw new FormatException(); }
}, new DataflowLinkOptions { PropagateCompletion = true });
});
}
[Fact]
public async Task TestFaultySource()
{
var bb = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1 });
bb.Post(1);
var source = new DelegatePropagator<int, int> {
ConsumeMessageDelegate = delegate(DataflowMessageHeader messageHeader, ITargetBlock<int> target, out bool messageConsumed) {
throw new FormatException();
}
};
Assert.Equal(
expected: DataflowMessageStatus.Postponed,
actual: ((ITargetBlock<int>)bb).OfferMessage(new DataflowMessageHeader(1), 2, source, true));
Assert.Equal(expected: 1, actual: bb.Receive());
await Assert.ThrowsAsync<FormatException>(() => bb.Completion);
}
[Fact]
public async Task TestMultiplePostponesFromSameSource()
{
var source = new BufferBlock<int>();
// Fill a target
var target1 = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1 });
target1.Post(1);
// Link to the target from a source; the message should get postponed
source.Post(2);
IDisposable unlink = source.LinkTo(target1);
Assert.Equal(expected: 1, actual: source.Count);
// Unlink, then relink; message should be offered again
unlink.Dispose();
source.LinkTo(target1);
Assert.Equal(expected: 1, actual: source.Count);
// Now receive to empty target1; it should then take the message from the source
Assert.Equal(expected: 1, actual: await target1.ReceiveAsync());
Assert.Equal(expected: 2, actual: await target1.ReceiveAsync());
}
[Fact]
public async Task TestReleasingFailsAtCompletion()
{
// Create a bounded block that's filled
var bb = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1 });
bb.Post(1);
// Create a source that will throw an exception when a message is released,
// which should happen when the buffer block drops any postponed messages
var source = new DelegatePropagator<int, int>
{
ReserveMessageDelegate = (header, target) => true,
ReleaseMessageDelegate = delegate { throw new FormatException(); }
};
// Offer a message from the source. It'll be postponed.
((ITargetBlock<int>)bb).OfferMessage(new DataflowMessageHeader(1), 1, source, consumeToAccept: false);
// Mark the block as complete. This should cause the block to reserve/release any postponed messages,
// which will cause the block to fault.
bb.Complete();
await Assert.ThrowsAsync<FormatException>(() => bb.Completion);
}
}
}
| |
#define SQLITE_ASCII
#define SQLITE_DISABLE_LFS
#define SQLITE_ENABLE_OVERSIZE_CELL_CHECK
#define SQLITE_MUTEX_OMIT
#define SQLITE_OMIT_AUTHORIZATION
#define SQLITE_OMIT_DEPRECATED
#define SQLITE_OMIT_GET_TABLE
#define SQLITE_OMIT_INCRBLOB
#define SQLITE_OMIT_LOOKASIDE
#define SQLITE_OMIT_SHARED_CACHE
#define SQLITE_OMIT_UTF16
#define SQLITE_OMIT_WAL
#define SQLITE_OS_WIN
#define SQLITE_SYSTEM_MALLOC
#define VDBE_PROFILE_OFF
#define WINDOWS_MOBILE
#define NDEBUG
#define _MSC_VER
#define YYFALLBACK
using System.Diagnostics;
using System;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/***** This file contains automatically generated code ******
**
** The code in this file has been automatically generated by
**
** sqlite/tool/mkkeywordhash.c
**
** The code in this file implements a function that determines whether
** or not a given identifier is really an SQL keyword. The same thing
** might be implemented more directly using a hand-written hash table.
** But by using this automatically generated code, the size of the code
** is substantially reduced. This is important for embedded applications
** on platforms with limited memory.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
/* Hash score: 175 */
/* zText[] encodes 811 bytes of keywords in 541 bytes */
/* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
/* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
/* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
/* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
/* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
/* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
/* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
/* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
/* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
/* INITIALLY */
static string zText = new string( new char[540] {
'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G',
#if !SQLITE_OMIT_TRIGGER
'E',
#else
'\0',
#endif
'R',
#if !SQLITE_OMIT_FOREIGN_KEY
'E',
#else
'\0',
#endif
'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
} );
static byte[] aHash = { //aHash[127]
72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
};
static byte[] aNext = { //aNext[121]
0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
35, 64, 0, 0,
};
static byte[] aLen = { //aLen[121]
7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
6, 4, 9, 3,
};
static int[] aOffset = { //aOffset[121]
0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
521, 527, 531, 536,
};
static byte[] aCode = { //aCode[121
TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
TK_ALL,
};
static int keywordCode( string z, int iOffset, int n )
{
int h, i;
if ( n < 2 )
return TK_ID;
h = ( ( sqlite3UpperToLower[z[iOffset + 0]] ) * 4 ^//(charMap(z[iOffset+0]) * 4) ^
( sqlite3UpperToLower[z[iOffset + n - 1]] * 3 ) ^ //(charMap(z[iOffset+n - 1]) * 3) ^
n ) % 127;
for ( i = ( aHash[h] ) - 1; i >= 0; i = ( aNext[i] ) - 1 )
{
if ( aLen[i] == n && String.Compare( zText, aOffset[i], z, iOffset, n, StringComparison.InvariantCultureIgnoreCase ) == 0 )
{
testcase( i == 0 ); /* REINDEX */
testcase( i == 1 ); /* INDEXED */
testcase( i == 2 ); /* INDEX */
testcase( i == 3 ); /* DESC */
testcase( i == 4 ); /* ESCAPE */
testcase( i == 5 ); /* EACH */
testcase( i == 6 ); /* CHECK */
testcase( i == 7 ); /* KEY */
testcase( i == 8 ); /* BEFORE */
testcase( i == 9 ); /* FOREIGN */
testcase( i == 10 ); /* FOR */
testcase( i == 11 ); /* IGNORE */
testcase( i == 12 ); /* REGEXP */
testcase( i == 13 ); /* EXPLAIN */
testcase( i == 14 ); /* INSTEAD */
testcase( i == 15 ); /* ADD */
testcase( i == 16 ); /* DATABASE */
testcase( i == 17 ); /* AS */
testcase( i == 18 ); /* SELECT */
testcase( i == 19 ); /* TABLE */
testcase( i == 20 ); /* LEFT */
testcase( i == 21 ); /* THEN */
testcase( i == 22 ); /* END */
testcase( i == 23 ); /* DEFERRABLE */
testcase( i == 24 ); /* ELSE */
testcase( i == 25 ); /* EXCEPT */
testcase( i == 26 ); /* TRANSACTION */
testcase( i == 27 ); /* ACTION */
testcase( i == 28 ); /* ON */
testcase( i == 29 ); /* NATURAL */
testcase( i == 30 ); /* ALTER */
testcase( i == 31 ); /* RAISE */
testcase( i == 32 ); /* EXCLUSIVE */
testcase( i == 33 ); /* EXISTS */
testcase( i == 34 ); /* SAVEPOINT */
testcase( i == 35 ); /* INTERSECT */
testcase( i == 36 ); /* TRIGGER */
testcase( i == 37 ); /* REFERENCES */
testcase( i == 38 ); /* CONSTRAINT */
testcase( i == 39 ); /* INTO */
testcase( i == 40 ); /* OFFSET */
testcase( i == 41 ); /* OF */
testcase( i == 42 ); /* SET */
testcase( i == 43 ); /* TEMPORARY */
testcase( i == 44 ); /* TEMP */
testcase( i == 45 ); /* OR */
testcase( i == 46 ); /* UNIQUE */
testcase( i == 47 ); /* QUERY */
testcase( i == 48 ); /* ATTACH */
testcase( i == 49 ); /* HAVING */
testcase( i == 50 ); /* GROUP */
testcase( i == 51 ); /* UPDATE */
testcase( i == 52 ); /* BEGIN */
testcase( i == 53 ); /* INNER */
testcase( i == 54 ); /* RELEASE */
testcase( i == 55 ); /* BETWEEN */
testcase( i == 56 ); /* NOTNULL */
testcase( i == 57 ); /* NOT */
testcase( i == 58 ); /* NO */
testcase( i == 59 ); /* NULL */
testcase( i == 60 ); /* LIKE */
testcase( i == 61 ); /* CASCADE */
testcase( i == 62 ); /* ASC */
testcase( i == 63 ); /* DELETE */
testcase( i == 64 ); /* CASE */
testcase( i == 65 ); /* COLLATE */
testcase( i == 66 ); /* CREATE */
testcase( i == 67 ); /* CURRENT_DATE */
testcase( i == 68 ); /* DETACH */
testcase( i == 69 ); /* IMMEDIATE */
testcase( i == 70 ); /* JOIN */
testcase( i == 71 ); /* INSERT */
testcase( i == 72 ); /* MATCH */
testcase( i == 73 ); /* PLAN */
testcase( i == 74 ); /* ANALYZE */
testcase( i == 75 ); /* PRAGMA */
testcase( i == 76 ); /* ABORT */
testcase( i == 77 ); /* VALUES */
testcase( i == 78 ); /* VIRTUAL */
testcase( i == 79 ); /* LIMIT */
testcase( i == 80 ); /* WHEN */
testcase( i == 81 ); /* WHERE */
testcase( i == 82 ); /* RENAME */
testcase( i == 83 ); /* AFTER */
testcase( i == 84 ); /* REPLACE */
testcase( i == 85 ); /* AND */
testcase( i == 86 ); /* DEFAULT */
testcase( i == 87 ); /* AUTOINCREMENT */
testcase( i == 88 ); /* TO */
testcase( i == 89 ); /* IN */
testcase( i == 90 ); /* CAST */
testcase( i == 91 ); /* COLUMN */
testcase( i == 92 ); /* COMMIT */
testcase( i == 93 ); /* CONFLICT */
testcase( i == 94 ); /* CROSS */
testcase( i == 95 ); /* CURRENT_TIMESTAMP */
testcase( i == 96 ); /* CURRENT_TIME */
testcase( i == 97 ); /* PRIMARY */
testcase( i == 98 ); /* DEFERRED */
testcase( i == 99 ); /* DISTINCT */
testcase( i == 100 ); /* IS */
testcase( i == 101 ); /* DROP */
testcase( i == 102 ); /* FAIL */
testcase( i == 103 ); /* FROM */
testcase( i == 104 ); /* FULL */
testcase( i == 105 ); /* GLOB */
testcase( i == 106 ); /* BY */
testcase( i == 107 ); /* IF */
testcase( i == 108 ); /* ISNULL */
testcase( i == 109 ); /* ORDER */
testcase( i == 110 ); /* RESTRICT */
testcase( i == 111 ); /* OUTER */
testcase( i == 112 ); /* RIGHT */
testcase( i == 113 ); /* ROLLBACK */
testcase( i == 114 ); /* ROW */
testcase( i == 115 ); /* UNION */
testcase( i == 116 ); /* USING */
testcase( i == 117 ); /* VACUUM */
testcase( i == 118 ); /* VIEW */
testcase( i == 119 ); /* INITIALLY */
testcase( i == 120 ); /* ALL */
return aCode[i];
}
}
return TK_ID;
}
static int sqlite3KeywordCode( string z, int n )
{
return keywordCode( z, 0, n );
}
public const int SQLITE_N_KEYWORD = 121;//#define SQLITE_N_KEYWORD 121
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// Public type to communicate multiple failures to an end-user.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Threading;
namespace System
{
/// <summary>Represents one or more errors that occur during application execution.</summary>
/// <remarks>
/// <see cref="AggregateException"/> is used to consolidate multiple failures into a single, throwable
/// exception object.
/// </remarks>
[Serializable]
[DebuggerDisplay("Count = {InnerExceptionCount}")]
public class AggregateException : Exception
{
private ReadOnlyCollection<Exception> m_innerExceptions; // Complete set of exceptions.
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class.
/// </summary>
public AggregateException()
: base(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"))
{
m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]);
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with
/// a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public AggregateException(string message)
: base(message)
{
m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]);
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
/// message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerException"/> argument
/// is null.</exception>
public AggregateException(string message, Exception innerException)
: base(message, innerException)
{
if (innerException == null)
{
throw new ArgumentNullException(nameof(innerException));
}
m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[] { innerException });
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with
/// references to the inner exceptions that are the cause of this exception.
/// </summary>
/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
public AggregateException(IEnumerable<Exception> innerExceptions) :
this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with
/// references to the inner exceptions that are the cause of this exception.
/// </summary>
/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
public AggregateException(params Exception[] innerExceptions) :
this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
/// message and references to the inner exceptions that are the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
public AggregateException(string message, IEnumerable<Exception> innerExceptions)
// If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along
// null typed correctly. Otherwise, create an IList from the enumerable and pass that along.
: this(message, innerExceptions as IList<Exception> ?? (innerExceptions == null ? (List<Exception>)null : new List<Exception>(innerExceptions)))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
/// message and references to the inner exceptions that are the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
public AggregateException(string message, params Exception[] innerExceptions) :
this(message, (IList<Exception>)innerExceptions)
{
}
/// <summary>
/// Allocates a new aggregate exception with the specified message and list of inner exceptions.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
private AggregateException(string message, IList<Exception> innerExceptions)
: base(message, innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0] : null)
{
if (innerExceptions == null)
{
throw new ArgumentNullException(nameof(innerExceptions));
}
// Copy exceptions to our internal array and validate them. We must copy them,
// because we're going to put them into a ReadOnlyCollection which simply reuses
// the list passed in to it. We don't want callers subsequently mutating.
Exception[] exceptionsCopy = new Exception[innerExceptions.Count];
for (int i = 0; i < exceptionsCopy.Length; i++)
{
exceptionsCopy[i] = innerExceptions[i];
if (exceptionsCopy[i] == null)
{
throw new ArgumentException(Environment.GetResourceString("AggregateException_ctor_InnerExceptionNull"));
}
}
m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy);
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with
/// references to the inner exception dispatch info objects that represent the cause of this exception.
/// </summary>
/// <param name="innerExceptionInfos">
/// Information about the exceptions that are the cause of the current exception.
/// </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is
/// null.</exception>
internal AggregateException(IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) :
this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptionInfos)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error
/// message and references to the inner exception dispatch info objects that represent the cause of
/// this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerExceptionInfos">
/// Information about the exceptions that are the cause of the current exception.
/// </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is
/// null.</exception>
internal AggregateException(string message, IEnumerable<ExceptionDispatchInfo> innerExceptionInfos)
// If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along
// null typed correctly. Otherwise, create an IList from the enumerable and pass that along.
: this(message, innerExceptionInfos as IList<ExceptionDispatchInfo> ??
(innerExceptionInfos == null ?
(List<ExceptionDispatchInfo>)null :
new List<ExceptionDispatchInfo>(innerExceptionInfos)))
{
}
/// <summary>
/// Allocates a new aggregate exception with the specified message and list of inner
/// exception dispatch info objects.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerExceptionInfos">
/// Information about the exceptions that are the cause of the current exception.
/// </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument
/// is null.</exception>
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is
/// null.</exception>
private AggregateException(string message, IList<ExceptionDispatchInfo> innerExceptionInfos)
: base(message, innerExceptionInfos != null && innerExceptionInfos.Count > 0 && innerExceptionInfos[0] != null ?
innerExceptionInfos[0].SourceException : null)
{
if (innerExceptionInfos == null)
{
throw new ArgumentNullException(nameof(innerExceptionInfos));
}
// Copy exceptions to our internal array and validate them. We must copy them,
// because we're going to put them into a ReadOnlyCollection which simply reuses
// the list passed in to it. We don't want callers subsequently mutating.
Exception[] exceptionsCopy = new Exception[innerExceptionInfos.Count];
for (int i = 0; i < exceptionsCopy.Length; i++)
{
var edi = innerExceptionInfos[i];
if (edi != null) exceptionsCopy[i] = edi.SourceException;
if (exceptionsCopy[i] == null)
{
throw new ArgumentException(Environment.GetResourceString("AggregateException_ctor_InnerExceptionNull"));
}
}
m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy);
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds
/// the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that
/// contains contextual information about the source or destination. </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The exception could not be deserialized correctly.</exception>
protected AggregateException(SerializationInfo info, StreamingContext context) :
base(info, context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
Exception[] innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[];
if (innerExceptions == null)
{
throw new SerializationException(Environment.GetResourceString("AggregateException_DeserializationFailure"));
}
m_innerExceptions = new ReadOnlyCollection<Exception>(innerExceptions);
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about
/// the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds
/// the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that
/// contains contextual information about the source or destination. </param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
base.GetObjectData(info, context);
Exception[] innerExceptions = new Exception[m_innerExceptions.Count];
m_innerExceptions.CopyTo(innerExceptions, 0);
info.AddValue("InnerExceptions", innerExceptions, typeof(Exception[]));
}
/// <summary>
/// Returns the <see cref="System.AggregateException"/> that is the root cause of this exception.
/// </summary>
public override Exception GetBaseException()
{
// Returns the first inner AggregateException that contains more or less than one inner exception
// Recursively traverse the inner exceptions as long as the inner exception of type AggregateException and has only one inner exception
Exception back = this;
AggregateException backAsAggregate = this;
while (backAsAggregate != null && backAsAggregate.InnerExceptions.Count == 1)
{
back = back.InnerException;
backAsAggregate = back as AggregateException;
}
return back;
}
/// <summary>
/// Gets a read-only collection of the <see cref="T:System.Exception"/> instances that caused the
/// current exception.
/// </summary>
public ReadOnlyCollection<Exception> InnerExceptions
{
get { return m_innerExceptions; }
}
/// <summary>
/// Invokes a handler on each <see cref="T:System.Exception"/> contained by this <see
/// cref="AggregateException"/>.
/// </summary>
/// <param name="predicate">The predicate to execute for each exception. The predicate accepts as an
/// argument the <see cref="T:System.Exception"/> to be processed and returns a Boolean to indicate
/// whether the exception was handled.</param>
/// <remarks>
/// Each invocation of the <paramref name="predicate"/> returns true or false to indicate whether the
/// <see cref="T:System.Exception"/> was handled. After all invocations, if any exceptions went
/// unhandled, all unhandled exceptions will be put into a new <see cref="AggregateException"/>
/// which will be thrown. Otherwise, the <see cref="Handle"/> method simply returns. If any
/// invocations of the <paramref name="predicate"/> throws an exception, it will halt the processing
/// of any more exceptions and immediately propagate the thrown exception as-is.
/// </remarks>
/// <exception cref="AggregateException">An exception contained by this <see
/// cref="AggregateException"/> was not handled.</exception>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="predicate"/> argument is
/// null.</exception>
public void Handle(Func<Exception, bool> predicate)
{
if (predicate == null)
{
throw new ArgumentNullException(nameof(predicate));
}
List<Exception> unhandledExceptions = null;
for (int i = 0; i < m_innerExceptions.Count; i++)
{
// If the exception was not handled, lazily allocate a list of unhandled
// exceptions (to be rethrown later) and add it.
if (!predicate(m_innerExceptions[i]))
{
if (unhandledExceptions == null)
{
unhandledExceptions = new List<Exception>();
}
unhandledExceptions.Add(m_innerExceptions[i]);
}
}
// If there are unhandled exceptions remaining, throw them.
if (unhandledExceptions != null)
{
throw new AggregateException(Message, unhandledExceptions);
}
}
/// <summary>
/// Flattens the inner instances of <see cref="AggregateException"/> by expanding its contained <see cref="Exception"/> instances
/// into a new <see cref="AggregateException"/>
/// </summary>
/// <returns>A new, flattened <see cref="AggregateException"/>.</returns>
/// <remarks>
/// If any inner exceptions are themselves instances of
/// <see cref="AggregateException"/>, this method will recursively flatten all of them. The
/// inner exceptions returned in the new <see cref="AggregateException"/>
/// will be the union of all of the the inner exceptions from exception tree rooted at the provided
/// <see cref="AggregateException"/> instance.
/// </remarks>
public AggregateException Flatten()
{
// Initialize a collection to contain the flattened exceptions.
List<Exception> flattenedExceptions = new List<Exception>();
// Create a list to remember all aggregates to be flattened, this will be accessed like a FIFO queue
List<AggregateException> exceptionsToFlatten = new List<AggregateException>();
exceptionsToFlatten.Add(this);
int nDequeueIndex = 0;
// Continue removing and recursively flattening exceptions, until there are no more.
while (exceptionsToFlatten.Count > nDequeueIndex)
{
// dequeue one from exceptionsToFlatten
IList<Exception> currentInnerExceptions = exceptionsToFlatten[nDequeueIndex++].InnerExceptions;
for (int i = 0; i < currentInnerExceptions.Count; i++)
{
Exception currentInnerException = currentInnerExceptions[i];
if (currentInnerException == null)
{
continue;
}
AggregateException currentInnerAsAggregate = currentInnerException as AggregateException;
// If this exception is an aggregate, keep it around for later. Otherwise,
// simply add it to the list of flattened exceptions to be returned.
if (currentInnerAsAggregate != null)
{
exceptionsToFlatten.Add(currentInnerAsAggregate);
}
else
{
flattenedExceptions.Add(currentInnerException);
}
}
}
return new AggregateException(Message, flattenedExceptions);
}
/// <summary>Gets a message that describes the exception.</summary>
public override string Message
{
get
{
if (m_innerExceptions.Count == 0)
{
return base.Message;
}
StringBuilder sb = StringBuilderCache.Acquire();
sb.Append(base.Message);
sb.Append(' ');
for (int i = 0; i < m_innerExceptions.Count; i++)
{
sb.Append('(');
sb.Append(m_innerExceptions[i].Message);
sb.Append(") ");
}
sb.Length -= 1;
return StringBuilderCache.GetStringAndRelease(sb);
}
}
/// <summary>
/// Creates and returns a string representation of the current <see cref="AggregateException"/>.
/// </summary>
/// <returns>A string representation of the current exception.</returns>
public override string ToString()
{
string text = base.ToString();
for (int i = 0; i < m_innerExceptions.Count; i++)
{
text = String.Format(
CultureInfo.InvariantCulture,
Environment.GetResourceString("AggregateException_ToString"),
text, Environment.NewLine, i, m_innerExceptions[i].ToString(), "<---", Environment.NewLine);
}
return text;
}
/// <summary>
/// This helper property is used by the DebuggerDisplay.
///
/// Note that we don't want to remove this property and change the debugger display to {InnerExceptions.Count}
/// because DebuggerDisplay should be a single property access or parameterless method call, so that the debugger
/// can use a fast path without using the expression evaluator.
///
/// See http://msdn.microsoft.com/en-us/library/x810d419.aspx
/// </summary>
private int InnerExceptionCount
{
get
{
return InnerExceptions.Count;
}
}
}
}
| |
// This class is not a part of the Smart Localization system, it only utilizes it.
// Created by Daniele Giardini - 2011 - Holoville - http://www.holoville.com
// Found at: http://wiki.unity3d.com/index.php?title=EditorUndoManager
using UnityEditor;
using UnityEngine;
/// <summary>
/// Editor undo manager.
/// To use it:
/// <list type="number">
/// <item>
/// <description>Store an instance in the related Editor Class (instantiate it inside the <code>OnEnable</code> method).</description>
/// </item>
/// <item>
/// <description>Call <code>undoManagerInstance.CheckUndo()</code> BEFORE the first UnityGUI call in <code>OnInspectorGUI</code>.</description>
/// </item>
/// <item>
/// <description>Call <code>undoManagerInstance.CheckDirty()</code> AFTER the last UnityGUI call in <code>OnInspectorGUI</code>.</description>
/// </item>
/// </list>
/// </summary>
public class HOEditorUndoManager
{
// VARS ///////////////////////////////////////////////////
private Object defTarget;
private string defName;
private bool autoSetDirty;
private bool listeningForGuiChanges;
private bool isMouseDown;
private Object waitingToRecordPrefab; // If different than NULL indicates the prefab instance that will need to record its state as soon as the mouse is released.
// ***********************************************************************************
// CONSTRUCTOR
// ***********************************************************************************
/// <summary>
/// Creates a new HOEditorUndoManager,
/// setting it so that the target is marked as dirty each time a new undo is stored.
/// </summary>
/// <param name="p_target">
/// The default <see cref="Object"/> you want to save undo info for.
/// </param>
/// <param name="p_name">
/// The default name of the thing to undo (displayed as "Undo [name]" in the main menu).
/// </param>
public HOEditorUndoManager( Object p_target, string p_name ) : this( p_target, p_name, true ) {}
/// <summary>
/// Creates a new HOEditorUndoManager.
/// </summary>
/// <param name="p_target">
/// The default <see cref="Object"/> you want to save undo info for.
/// </param>
/// <param name="p_name">
/// The default name of the thing to undo (displayed as "Undo [name]" in the main menu).
/// </param>
/// <param name="p_autoSetDirty">
/// If TRUE, marks the target as dirty each time a new undo is stored.
/// </param>
public HOEditorUndoManager( Object p_target, string p_name, bool p_autoSetDirty )
{
defTarget = p_target;
defName = p_name;
autoSetDirty = p_autoSetDirty;
}
// ===================================================================================
// METHODS ---------------------------------------------------------------------------
/// <summary>
/// Call this method BEFORE any undoable UnityGUI call.
/// Manages undo for the default target, with the default name.
/// </summary>
public void CheckUndo() { CheckUndo( defTarget, defName ); }
/// <summary>
/// Call this method BEFORE any undoable UnityGUI call.
/// Manages undo for the given target, with the default name.
/// </summary>
/// <param name="p_target">
/// The <see cref="Object"/> you want to save undo info for.
/// </param>
public void CheckUndo( Object p_target ) { CheckUndo( p_target, defName ); }
/// <summary>
/// Call this method BEFORE any undoable UnityGUI call.
/// Manages undo for the given target, with the given name.
/// </summary>
/// <param name="p_target">
/// The <see cref="Object"/> you want to save undo info for.
/// </param>
/// <param name="p_name">
/// The name of the thing to undo (displayed as "Undo [name]" in the main menu).
/// </param>
public void CheckUndo( Object p_target, string p_name )
{
Event e = Event.current;
if ( waitingToRecordPrefab != null ) {
// Record eventual prefab instance modification.
// TODO Avoid recording if nothing changed (no harm in doing so, but it would be nicer).
switch ( e.type ) {
case EventType.MouseDown :
case EventType.MouseUp :
case EventType.KeyDown :
case EventType.KeyUp :
PrefabUtility.RecordPrefabInstancePropertyModifications( waitingToRecordPrefab );
break;
}
}
if ( ( e.type == EventType.MouseDown && e.button == 0 ) || ( e.type == EventType.KeyUp && e.keyCode == KeyCode.Tab ) ) {
// When the LMB is pressed or the TAB key is released,
// store a snapshot, but don't register it as an undo
// (so that if nothing changes we avoid storing a useless undo).
Undo.SetSnapshotTarget( p_target, p_name );
Undo.CreateSnapshot();
Undo.ClearSnapshotTarget(); // Not sure if this is necessary.
listeningForGuiChanges = true;
}
}
/// <summary>
/// Call this method AFTER any undoable UnityGUI call.
/// Manages undo for the default target, with the default name,
/// and returns a value of TRUE if the target is marked as dirty.
/// </summary>
public bool CheckDirty() { return CheckDirty( defTarget, defName ); }
/// <summary>
/// Call this method AFTER any undoable UnityGUI call.
/// Manages undo for the given target, with the default name,
/// and returns a value of TRUE if the target is marked as dirty.
/// </summary>
/// <param name="p_target">
/// The <see cref="Object"/> you want to save undo info for.
/// </param>
public bool CheckDirty( Object p_target ) { return CheckDirty( p_target, defName ); }
/// <summary>
/// Call this method AFTER any undoable UnityGUI call.
/// Manages undo for the given target, with the given name,
/// and returns a value of TRUE if the target is marked as dirty.
/// </summary>
/// <param name="p_target">
/// The <see cref="Object"/> you want to save undo info for.
/// </param>
/// <param name="p_name">
/// The name of the thing to undo (displayed as "Undo [name]" in the main menu).
/// </param>
public bool CheckDirty( Object p_target, string p_name )
{
if ( listeningForGuiChanges && GUI.changed ) {
// Some GUI value changed after pressing the mouse
// or releasing the TAB key.
// Register the previous snapshot as a valid undo.
SetDirty( p_target, p_name );
return true;
}
return false;
}
/// <summary>
/// Call this method AFTER any undoable UnityGUI call.
/// Forces undo for the default target, with the default name.
/// Used to undo operations that are performed by pressing a button,
/// which doesn't set the GUI to a changed state.
/// </summary>
public void ForceDirty() { ForceDirty( defTarget, defName ); }
/// <summary>
/// Call this method AFTER any undoable UnityGUI call.
/// Forces undo for the given target, with the default name.
/// Used to undo operations that are performed by pressing a button,
/// which doesn't set the GUI to a changed state.
/// </summary>
/// <param name="p_target">
/// The <see cref="Object"/> you want to save undo info for.
/// </param>
public void ForceDirty( Object p_target ) { ForceDirty( p_target, defName ); }
/// <summary>
/// Call this method AFTER any undoable UnityGUI call.
/// Forces undo for the given target, with the given name.
/// Used to undo operations that are performed by pressing a button,
/// which doesn't set the GUI to a changed state.
/// </summary>
/// <param name="p_target">
/// The <see cref="Object"/> you want to save undo info for.
/// </param>
/// <param name="p_name">
/// The name of the thing to undo (displayed as "Undo [name]" in the main menu).
/// </param>
public void ForceDirty( Object p_target, string p_name )
{
if ( !listeningForGuiChanges ) {
// Create a new snapshot.
Undo.SetSnapshotTarget( p_target, p_name );
Undo.CreateSnapshot();
Undo.ClearSnapshotTarget();
}
SetDirty( p_target, p_name );
}
// ===================================================================================
// PRIVATE METHODS -------------------------------------------------------------------
private void SetDirty( Object p_target, string p_name )
{
Undo.SetSnapshotTarget( p_target, p_name );
Undo.RegisterSnapshot();
Undo.ClearSnapshotTarget(); // Not sure if this is necessary.
if ( autoSetDirty ) EditorUtility.SetDirty( p_target );
listeningForGuiChanges = false;
if ( CheckTargetIsPrefabInstance( p_target ) ) {
// Prefab instance: record immediately and also wait for value to be changed and than re-record it
// (otherwise prefab instances are not updated correctly when using Custom Inspectors).
PrefabUtility.RecordPrefabInstancePropertyModifications( p_target );
waitingToRecordPrefab = p_target;
} else {
waitingToRecordPrefab = null;
}
}
private bool CheckTargetIsPrefabInstance( Object p_target )
{
return ( PrefabUtility.GetPrefabType( p_target ) == PrefabType.PrefabInstance );
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/3/2008 5:21:49 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
namespace DotSpatial.Data
{
public struct Number : IComparable, IComparable<Number>, IComparable<double>
{
#region Private methods
private readonly int _significantFigures;
private int _decimalCount;
private NumberFormat _format;
private bool _hasValue;
private double _value;
#endregion
/// <summary>
/// Creates a value from an object
/// </summary>
/// <param name="value">A numeric value that is, or can be parsed to a numeric value.</param>
/// <exception cref="NonNumericException">Not Numeric</exception>
public Number(object value)
{
if (Global.IsShort(value))
{
_value = Global.GetDouble(value);
_significantFigures = 5;
_decimalCount = 0;
_format = NumberFormat.General;
_hasValue = true;
return;
}
if (Global.IsInteger(value))
{
_value = Global.GetDouble(value);
_significantFigures = 10;
_decimalCount = 0;
_format = NumberFormat.General;
_hasValue = true;
return;
}
if (Global.IsFloat(value))
{
_value = Global.GetDouble(value);
_significantFigures = 8;
_decimalCount = 7;
_format = NumberFormat.General;
_hasValue = true;
return;
}
if (Global.IsDouble(value))
{
// doubles can have 16 digits, so in scientific notation
_value = Global.GetDouble(value);
_significantFigures = 16;
_decimalCount = 15;
_format = NumberFormat.General;
_hasValue = true;
return;
}
throw new NonNumericException("value");
}
/// <summary>
/// Creates a number to fit the specified double value.
/// </summary>
/// <param name="value">A double</param>
public Number(double value)
{
// doubles can have 16 digits, so in scientific notation
_value = value;
_significantFigures = 16;
_decimalCount = 15;
_format = NumberFormat.General;
_hasValue = true;
}
/// <summary>
/// Creates a number to fit the specified int value
/// </summary>
/// <param name="value">An integer</param>
public Number(int value)
{
_value = value;
_significantFigures = 10;
_decimalCount = 0;
_format = NumberFormat.General;
_hasValue = true;
}
/// <summary>
/// Creates a number to fit the specified float value
/// </summary>
/// <param name="value">The value to work with</param>
public Number(float value)
{
_value = value;
_significantFigures = 8;
_decimalCount = 7;
_format = NumberFormat.General;
_hasValue = true;
}
/// <summary>
/// Creates a number from a short
/// </summary>
/// <param name="value">A short</param>
public Number(short value)
{
_value = value;
_significantFigures = 5;
_decimalCount = 0;
_format = NumberFormat.General;
_hasValue = true;
}
/// <summary>
/// Gets the alphabetical letter code for ToString(-Code-)
/// </summary>
public string Code
{
get
{
switch (_format)
{
case NumberFormat.Currency: return "C";
case NumberFormat.Exponential: return "E";
case NumberFormat.FixedPoint: return "F";
case NumberFormat.General: return "G";
case NumberFormat.Number: return "N";
case NumberFormat.Percent: return "P";
case NumberFormat.Unspecified: return "G";
}
return "G";
}
}
/// <summary>
/// A NumberFormats enumeration giving the various formatting options
/// </summary>
public NumberFormat Format
{
get { return _format; }
set { _format = value; }
}
/// <summary>
/// Tests to see if a value has been assigned to this Number
/// </summary>
public bool IsEmpty
{
get { return !_hasValue; }
}
/// <summary>
/// Gets or sets the number of digits that folow the decimal
/// when converting this value to string notation.
/// </summary>
public int DecimalsCount
{
get { return _decimalCount; }
set { _decimalCount = value; }
}
/// <summary>
/// Gets the precision (determined by the data type) which
/// effectively describes how many significant figures there are.
/// </summary>
public int SignificantFigures
{
get { return _significantFigures; }
}
/// <summary>
/// Gets this number as a double
/// </summary>
/// <returns>a double</returns>
public double Value
{
get
{
return _value;
}
set
{
_value = value;
_hasValue = true;
}
}
#region IComparable Members
/// <summary>
/// Compares this with the specified value. Returns 1 if the other
/// item is greater than this value, 0 if they are equal and -1 if
/// the other value is less than this value.
/// </summary>
/// <param name="other">The value to be tested.</param>
/// <returns>An integer: 1 if the other
/// item is greater than this value, 0 if they are equal and -1 if
/// the other value is less than this value. </returns>
public int CompareTo(object other)
{
if (Global.IsDouble(other) == false)
{
throw new NonNumericException("other");
}
return _value.CompareTo(Global.GetDouble(other));
}
#endregion
#region IComparable<double> Members
/// <summary>
/// Compares this with the specified value. Returns 1 if the other
/// item is greater than this value, 0 if they are equal and -1 if
/// the other value is less than this value.
/// </summary>
/// <param name="other">The value to be tested.</param>
/// <returns>An integer: 1 if the other
/// item is greater than this value, 0 if they are equal and -1 if
/// the other value is less than this value. </returns>
public int CompareTo(double other)
{
return _value.CompareTo(other);
}
#endregion
#region IComparable<Number> Members
/// <summary>
/// Compares this with the specified value. Returns 1 if the other
/// item is greater than this value, 0 if they are equal and -1 if
/// the other value is less than this value.
/// </summary>
/// <param name="other">The value to be tested.</param>
/// <returns>An integer: 1 if the other
/// item is greater than this value, 0 if they are equal and -1 if
/// the other value is less than this value. </returns>
public int CompareTo(Number other)
{
return _value.CompareTo(other.Value);
}
#endregion
/// <summary>
/// Returns this Number as a string.
/// </summary>
/// <returns>The string created using the specified number format and precision.</returns>
public override string ToString()
{
return _value.ToString(Code + DecimalsCount, CulturePreferences.CultureInformation.NumberFormat);
}
/// <summary>
/// Returns this Number as a string.
/// </summary>
/// <param name="provider">An IFormatProvider that provides culture specific formatting information.</param>
/// <returns>A string with the formatted number.</returns>
public string ToString(IFormatProvider provider)
{
return _value.ToString(Code + DecimalsCount, provider);
}
/// <summary>
/// Returns this Number as a string.
/// </summary>
/// <param name="format">A string that controls how this value should be formatted.</param>
/// <returns>A string with the formatted number.</returns>
public string ToString(string format)
{
return _value.ToString(format, CulturePreferences.CultureInformation.NumberFormat);
}
/// <summary>
/// Returns this Number as a string.
/// </summary>
/// <param name="format">A string that controls how this value should be formatted.</param>
/// <param name="provider">An IFormatProvider that provides culture specific formatting information.</param>
/// <returns>A string with the formatted number.</returns>
public string ToString(string format, IFormatProvider provider)
{
return _value.ToString(format, provider);
}
/// <summary>
/// Gets this number as an int 32
/// </summary>
/// <returns>An integer</returns>
public int ToInt32()
{
if (_value > int.MaxValue) return int.MaxValue;
if (_value < int.MinValue) return int.MinValue;
return Convert.ToInt32(_value);
}
/// <summary>
/// Gets this number as a short, or a short.MaxValue/short.MinValue
/// </summary>
/// <returns>A short</returns>
public short ToInt16()
{
if (_value > short.MaxValue) return short.MaxValue;
if (_value < short.MinValue) return short.MinValue;
return Convert.ToInt16(_value);
}
/// <summary>
/// Gets this number as a float
/// </summary>
/// <returns>A float </returns>
public float ToFloat()
{
if (_value > float.MaxValue) return float.MaxValue;
if (_value > float.MinValue) return float.MinValue;
return Convert.ToSingle(_value);
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
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.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using SpatialAnalysis.Miscellaneous;
namespace SpatialAnalysis.Data.Visualization
{
/// <summary>
/// Interaction logic for ParameterSetting.xaml
/// </summary>
public partial class ParameterSetting : Window
{
#region Hiding the close button
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
//Hiding the close button
private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
#endregion
#region ParameterName Definition
/// <summary>
/// The parameter name property
/// </summary>
public static DependencyProperty ParameterNameProperty =
DependencyProperty.Register("ParameterName", typeof(string), typeof(ParameterSetting),
new FrameworkPropertyMetadata(string.Empty, ParameterSetting.ParameterNamePropertyChanged, ParameterSetting.PropertyCoerce));
/// <summary>
/// Gets or sets the name of the parameter.
/// </summary>
/// <value>The name of the parameter.</value>
public string ParameterName
{
get { return (string)GetValue(ParameterNameProperty); }
set { SetValue(ParameterNameProperty, value); }
}
private static void ParameterNamePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
ParameterSetting parameterSetting = (ParameterSetting)obj;
if ((string)args.NewValue != (string)args.OldValue)
{
parameterSetting.ParameterName = (string)args.NewValue;
}
}
private static object PropertyCoerce(DependencyObject obj, object value)
{
return value;
}
#endregion
OSMDocument _host;
/// <summary>
/// Initializes a new instance of the <see cref="ParameterSetting"/> class.
/// </summary>
/// <param name="host">The document to which this window belongs</param>
/// <param name="insertmode">If set to <c>true</c> inserts the selected parameter.</param>
public ParameterSetting(OSMDocument host, bool insertmode)
{
InitializeComponent();
this.Loaded += Window_Loaded;
this._host = host;
foreach (var item in this._host.Parameters.Keys)
{
this._parameterList.Items.Add(item);
}
this._close.Click += _close_Click;
this._createAndAdd.Click += _createAndAdd_Click;
this._parameterList.SelectionChanged += _parameterList_SelectionChanged;
this._update.Click += _update_Click;
this._paramMax.TextChanged += _updateEnabled;
this._paramMin.TextChanged += _updateEnabled;
this._paramValue.TextChanged += _updateEnabled;
this._insert.Click += _insert_Click;
this._delete.Click += new RoutedEventHandler(_delete_Click);
if (insertmode)
{
this._close.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
this._insert.Visibility = System.Windows.Visibility.Collapsed;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ParameterSetting"/> class.
/// </summary>
/// <param name="host">The host.</param>
/// <param name="insertmode">If set to <c>true</c> inserts the selected parameter.</param>
/// <param name="newParameterName">New name of the parameter.</param>
public ParameterSetting(OSMDocument host, bool insertmode, string newParameterName)
{
InitializeComponent();
this.Loaded += Window_Loaded;
this._host = host;
foreach (var item in this._host.Parameters.Keys)
{
this._parameterList.Items.Add(item);
}
this._close.Click += _close_Click;
this._createAndAdd.Click += _createAndAdd_Click;
this._parameterList.SelectionChanged += _parameterList_SelectionChanged;
this._update.Click += _update_Click;
this._paramMax.TextChanged += _updateEnabled;
this._paramMin.TextChanged += _updateEnabled;
this._paramValue.TextChanged += _updateEnabled;
this._insert.Click += _insert_Click;
this._delete.Click += new RoutedEventHandler(_delete_Click);
this._name.Text = newParameterName;
this._name.SelectAll();
if (insertmode)
{
this._close.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
this._insert.Visibility = System.Windows.Visibility.Collapsed;
}
}
void _delete_Click(object sender, RoutedEventArgs e)
{
if (this._parameterList.SelectedIndex != -1)
{
string name = (string)this._parameterList.SelectedValue;
if (!this._host.Parameters.ContainsKey(name))
{
MessageBox.Show("Parameter not found");
return;
}
if (this._host.RemoveParameter(name))
{
this._paramName.Text = string.Empty;
this._paramMax.Text = string.Empty;
this._paramMin.Text = string.Empty;
this._paramValue.Text = string.Empty;
this._update.IsEnabled = false;
this._parameterList.SelectedIndex = -1;
this._parameterList.Items.Remove(name);
}
}
else
{
MessageBox.Show("No parameter selected", "", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
void _insert_Click(object sender, RoutedEventArgs e)
{
if (this._parameterList.SelectedIndex == -1)
{
var result = MessageBox.Show("No Parameter Selected!\nDo you want to continue with no selection?",
"No Selection Made", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
if (result == MessageBoxResult.Yes)
{
this.Close();
}
else
{
return;
}
}
else
{
string name = (string)this._parameterList.SelectedValue;
if (!this._host.Parameters.ContainsKey(name))
{
MessageBox.Show("Parameter not found");
return;
}
this.ParameterName = name;
this.Close();
}
}
void _updateEnabled(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(this._paramMax.Text) && !string.IsNullOrWhiteSpace(this._paramMax.Text) &&
!string.IsNullOrEmpty(this._paramMin.Text) && !string.IsNullOrWhiteSpace(this._paramMin.Text) &&
!string.IsNullOrEmpty(this._paramValue.Text) && !string.IsNullOrWhiteSpace(this._paramValue.Text))
{
if (this._parameterList.SelectedIndex != -1)
{
string name = (string)this._parameterList.SelectedValue;
if (this._host.Parameters.ContainsKey(name))
{
var param = this._host.Parameters[name];
if (this._paramMax.Text != param.Maximum.ToString() ||
this._paramMin.Text != param.Minimum.ToString() ||
this._paramValue.Text != param.Value.ToString())
{
this._update.IsEnabled = true;
}
}
}
}
}
void _update_Click(object sender, RoutedEventArgs e)
{
double min, max, value;
if (!double.TryParse(this._paramMin.Text, out min) ||
!double.TryParse(this._paramMax.Text, out max) ||
!double.TryParse(this._paramValue.Text, out value))
{
MessageBox.Show("Invalid input values for updating the selected parameter");
return;
}
string name = (string)this._parameterList.SelectedValue;
if (!this._host.Parameters.ContainsKey(name))
{
MessageBox.Show("Parameter not found");
return;
}
var param = this._host.Parameters[name];
try
{
param.Maximum = max;
param.Minimum = min;
param.Value = value;
}
catch (Exception error)
{
MessageBox.Show(error.Report());
return;
}
this._update.IsEnabled = false;
}
void _parameterList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this._parameterList.SelectedIndex == -1)
{
return;
}
this._update.IsEnabled = false;
string name = (string)this._parameterList.SelectedValue;
if (!this._host.Parameters.ContainsKey(name))
{
MessageBox.Show("Parameter not found");
return;
}
var param = this._host.Parameters[name];
this._paramName.Text = param.Name;
this._paramMax.Text = param.Maximum.ToString();
this._paramMin.Text = param.Minimum.ToString();
this._paramValue.Text = param.Value.ToString();
}
void _createAndAdd_Click(object sender, RoutedEventArgs e)
{
double min, max, value;
if (!double.TryParse(this._min.Text, out min) ||
!double.TryParse(this._max.Text, out max) ||
!double.TryParse(this._value.Text, out value))
{
MessageBox.Show("Invalid input values for the new parameter");
return;
}
string name = this._name.Text;
if (this._host.Parameters.ContainsKey(name))
{
MessageBox.Show("A parameter with the same name exists");
return;
}
Parameter param = null;
try
{
param = new Parameter(name, value, min, max);
}
catch (Exception error)
{
MessageBox.Show(error.Report());
}
if (param != null)
{
this._host.AddParameter(param);
this._value.Text = string.Empty;
this._min.Text = string.Empty;
this._max.Text = string.Empty;
this._value.Text = string.Empty;
this._name.Text = string.Empty;
this._parameterList.Items.Add(param.Name);
}
}
void _close_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System.Diagnostics;
using FarseerPhysics.Common;
using FarseerPhysics.Common.ConvexHull;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// Represents a simple non-selfintersecting convex polygon.
/// Create a convex hull from the given array of points.
/// </summary>
public class PolygonShape : Shape
{
private Vertices _vertices;
private Vertices _normals;
/// <summary>
/// Initializes a new instance of the <see cref="PolygonShape"/> class.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="density">The density.</param>
public PolygonShape(Vertices vertices, float density)
: base(density)
{
ShapeType = ShapeType.Polygon;
_radius = Settings.PolygonRadius;
Vertices = vertices;
}
/// <summary>
/// Create a new PolygonShape with the specified density.
/// </summary>
/// <param name="density">The density.</param>
public PolygonShape(float density)
: base(density)
{
Debug.Assert(density >= 0f);
ShapeType = ShapeType.Polygon;
_radius = Settings.PolygonRadius;
_vertices = new Vertices(Settings.MaxPolygonVertices);
_normals = new Vertices(Settings.MaxPolygonVertices);
}
internal PolygonShape()
: base(0)
{
ShapeType = ShapeType.Polygon;
_radius = Settings.PolygonRadius;
_vertices = new Vertices(Settings.MaxPolygonVertices);
_normals = new Vertices(Settings.MaxPolygonVertices);
}
/// <summary>
/// Create a convex hull from the given array of local points.
/// The number of vertices must be in the range [3, Settings.MaxPolygonVertices].
/// Warning: the points may be re-ordered, even if they form a convex polygon
/// Warning: collinear points are handled but not removed. Collinear points may lead to poor stacking behavior.
/// </summary>
public Vertices Vertices
{
get { return _vertices; }
set
{
_vertices = new Vertices(value);
Debug.Assert(_vertices.Count >= 3 && _vertices.Count <= Settings.MaxPolygonVertices);
if (Settings.UseConvexHullPolygons)
{
//FPE note: This check is required as the GiftWrap algorithm early exits on triangles
//So instead of giftwrapping a triangle, we just force it to be clock wise.
if (_vertices.Count <= 3)
_vertices.ForceCounterClockWise();
else
_vertices = GiftWrap.GetConvexHull(_vertices);
}
_normals = new Vertices(_vertices.Count);
// Compute normals. Ensure the edges have non-zero length.
for (int i = 0; i < _vertices.Count; ++i)
{
int next = i + 1 < _vertices.Count ? i + 1 : 0;
Vector2 edge = _vertices[next] - _vertices[i];
Debug.Assert(edge.LengthSquared() > Settings.Epsilon * Settings.Epsilon);
//FPE optimization: Normals.Add(MathHelper.Cross(edge, 1.0f));
Vector2 temp = new Vector2(edge.Y, -edge.X);
temp.Normalize();
_normals.Add(temp);
}
// Compute the polygon mass data
ComputeProperties();
}
}
public Vertices Normals { get { return _normals; } }
public override int ChildCount { get { return 1; } }
protected override void ComputeProperties()
{
// Polygon mass, centroid, and inertia.
// Let rho be the polygon density in mass per unit area.
// Then:
// mass = rho * int(dA)
// centroid.X = (1/mass) * rho * int(x * dA)
// centroid.Y = (1/mass) * rho * int(y * dA)
// I = rho * int((x*x + y*y) * dA)
//
// We can compute these integrals by summing all the integrals
// for each triangle of the polygon. To evaluate the integral
// for a single triangle, we make a change of variables to
// the (u,v) coordinates of the triangle:
// x = x0 + e1x * u + e2x * v
// y = y0 + e1y * u + e2y * v
// where 0 <= u && 0 <= v && u + v <= 1.
//
// We integrate u from [0,1-v] and then v from [0,1].
// We also need to use the Jacobian of the transformation:
// D = cross(e1, e2)
//
// Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
//
// The rest of the derivation is handled by computer algebra.
Debug.Assert(Vertices.Count >= 3);
//FPE optimization: Early exit as polygons with 0 density does not have any properties.
if (_density <= 0)
return;
//FPE optimization: Consolidated the calculate centroid and mass code to a single method.
Vector2 center = Vector2.Zero;
float area = 0.0f;
float I = 0.0f;
// pRef is the reference point for forming triangles.
// It's location doesn't change the result (except for rounding error).
Vector2 s = Vector2.Zero;
// This code would put the reference point inside the polygon.
for (int i = 0; i < Vertices.Count; ++i)
{
s += Vertices[i];
}
s *= 1.0f / Vertices.Count;
const float k_inv3 = 1.0f / 3.0f;
for (int i = 0; i < Vertices.Count; ++i)
{
// Triangle vertices.
Vector2 e1 = Vertices[i] - s;
Vector2 e2 = i + 1 < Vertices.Count ? Vertices[i + 1] - s : Vertices[0] - s;
float D = MathUtils.Cross(e1, e2);
float triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * (e1 + e2);
float ex1 = e1.X, ey1 = e1.Y;
float ex2 = e2.X, ey2 = e2.Y;
float intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2;
float inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2;
I += (0.25f * k_inv3 * D) * (intx2 + inty2);
}
//The area is too small for the engine to handle.
Debug.Assert(area > Settings.Epsilon);
// We save the area
MassData.Area = area;
// Total mass
MassData.Mass = _density * area;
// Center of mass
center *= 1.0f / area;
MassData.Centroid = center + s;
// Inertia tensor relative to the local origin (point s).
MassData.Inertia = _density * I;
// Shift to center of mass then to original body origin.
MassData.Inertia += MassData.Mass * (Vector2.Dot(MassData.Centroid, MassData.Centroid) - Vector2.Dot(center, center));
}
public override bool TestPoint(ref Transform transform, ref Vector2 point)
{
Vector2 pLocal = MathUtils.MulT(transform.q, point - transform.p);
for (int i = 0; i < Vertices.Count; ++i)
{
float dot = Vector2.Dot(Normals[i], pLocal - Vertices[i]);
if (dot > 0.0f)
{
return false;
}
}
return true;
}
public override bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform, int childIndex)
{
output = new RayCastOutput();
// Put the ray into the polygon's frame of reference.
Vector2 p1 = MathUtils.MulT(transform.q, input.Point1 - transform.p);
Vector2 p2 = MathUtils.MulT(transform.q, input.Point2 - transform.p);
Vector2 d = p2 - p1;
float lower = 0.0f, upper = input.MaxFraction;
int index = -1;
for (int i = 0; i < Vertices.Count; ++i)
{
// p = p1 + a * d
// dot(normal, p - v) = 0
// dot(normal, p1 - v) + a * dot(normal, d) = 0
float numerator = Vector2.Dot(Normals[i], Vertices[i] - p1);
float denominator = Vector2.Dot(Normals[i], d);
if (denominator == 0.0f)
{
if (numerator < 0.0f)
{
return false;
}
}
else
{
// Note: we want this predicate without division:
// lower < numerator / denominator, where denominator < 0
// Since denominator < 0, we have to flip the inequality:
// lower < numerator / denominator <==> denominator * lower > numerator.
if (denominator < 0.0f && numerator < lower * denominator)
{
// Increase lower.
// The segment enters this half-space.
lower = numerator / denominator;
index = i;
}
else if (denominator > 0.0f && numerator < upper * denominator)
{
// Decrease upper.
// The segment exits this half-space.
upper = numerator / denominator;
}
}
// The use of epsilon here causes the assert on lower to trip
// in some cases. Apparently the use of epsilon was to make edge
// shapes work, but now those are handled separately.
//if (upper < lower - b2_epsilon)
if (upper < lower)
{
return false;
}
}
Debug.Assert(0.0f <= lower && lower <= input.MaxFraction);
if (index >= 0)
{
output.Fraction = lower;
output.Normal = MathUtils.Mul(transform.q, Normals[index]);
return true;
}
return false;
}
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex)
{
Vector2 lower = MathUtils.Mul(ref transform, Vertices[0]);
Vector2 upper = lower;
for (int i = 1; i < Vertices.Count; ++i)
{
Vector2 v = MathUtils.Mul(ref transform, Vertices[i]);
lower = Vector2.Min(lower, v);
upper = Vector2.Max(upper, v);
}
Vector2 r = new Vector2(Radius, Radius);
aabb.LowerBound = lower - r;
aabb.UpperBound = upper + r;
}
public override float ComputeSubmergedArea(ref Vector2 normal, float offset, ref Transform xf, out Vector2 sc)
{
sc = Vector2.Zero;
//Transform plane into shape co-ordinates
Vector2 normalL = MathUtils.MulT(xf.q, normal);
float offsetL = offset - Vector2.Dot(normal, xf.p);
float[] depths = new float[Settings.MaxPolygonVertices];
int diveCount = 0;
int intoIndex = -1;
int outoIndex = -1;
bool lastSubmerged = false;
int i;
for (i = 0; i < Vertices.Count; i++)
{
depths[i] = Vector2.Dot(normalL, Vertices[i]) - offsetL;
bool isSubmerged = depths[i] < -Settings.Epsilon;
if (i > 0)
{
if (isSubmerged)
{
if (!lastSubmerged)
{
intoIndex = i - 1;
diveCount++;
}
}
else
{
if (lastSubmerged)
{
outoIndex = i - 1;
diveCount++;
}
}
}
lastSubmerged = isSubmerged;
}
switch (diveCount)
{
case 0:
if (lastSubmerged)
{
//Completely submerged
sc = MathUtils.Mul(ref xf, MassData.Centroid);
return MassData.Mass / Density;
}
//Completely dry
return 0;
case 1:
if (intoIndex == -1)
{
intoIndex = Vertices.Count - 1;
}
else
{
outoIndex = Vertices.Count - 1;
}
break;
}
int intoIndex2 = (intoIndex + 1) % Vertices.Count;
int outoIndex2 = (outoIndex + 1) % Vertices.Count;
float intoLambda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]);
float outoLambda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]);
Vector2 intoVec = new Vector2(Vertices[intoIndex].X * (1 - intoLambda) + Vertices[intoIndex2].X * intoLambda, Vertices[intoIndex].Y * (1 - intoLambda) + Vertices[intoIndex2].Y * intoLambda);
Vector2 outoVec = new Vector2(Vertices[outoIndex].X * (1 - outoLambda) + Vertices[outoIndex2].X * outoLambda, Vertices[outoIndex].Y * (1 - outoLambda) + Vertices[outoIndex2].Y * outoLambda);
//Initialize accumulator
float area = 0;
Vector2 center = new Vector2(0, 0);
Vector2 p2 = Vertices[intoIndex2];
const float k_inv3 = 1.0f / 3.0f;
//An awkward loop from intoIndex2+1 to outIndex2
i = intoIndex2;
while (i != outoIndex2)
{
i = (i + 1) % Vertices.Count;
Vector2 p3;
if (i == outoIndex2)
p3 = outoVec;
else
p3 = Vertices[i];
//Add the triangle formed by intoVec,p2,p3
{
Vector2 e1 = p2 - intoVec;
Vector2 e2 = p3 - intoVec;
float D = MathUtils.Cross(e1, e2);
float triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * (intoVec + p2 + p3);
}
p2 = p3;
}
//Normalize and transform centroid
center *= 1.0f / area;
sc = MathUtils.Mul(ref xf, center);
return area;
}
public bool CompareTo(PolygonShape shape)
{
if (Vertices.Count != shape.Vertices.Count)
return false;
for (int i = 0; i < Vertices.Count; i++)
{
if (Vertices[i] != shape.Vertices[i])
return false;
}
return (Radius == shape.Radius && MassData == shape.MassData);
}
public override Shape Clone()
{
PolygonShape clone = new PolygonShape();
clone.ShapeType = ShapeType;
clone._radius = _radius;
clone._density = _density;
clone._vertices = new Vertices(_vertices);
clone._normals = new Vertices(_normals);
clone.MassData = MassData;
return clone;
}
}
}
| |
//
// MethodBodyReader.cs
//
// Author:
// Jb Evain (jbevain@novell.com)
//
// (C) 2009 - 2010 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace ILDisassembler
{
internal class MethodBodyReader
{
private static readonly OpCode[] oneByteOpCodes;
private static readonly OpCode[] twoByteOpCodes;
private readonly MethodBase method;
private readonly MethodBody body;
private readonly Module module;
private readonly Type[] typeArguments;
private readonly Type[] methodArguments;
private readonly ByteBuffer ilBuffer;
private readonly ParameterInfo[] parameters;
private readonly IList<LocalVariableInfo> locals;
private readonly List<Instruction> instructions;
static MethodBodyReader()
{
oneByteOpCodes = new OpCode[0xe1];
twoByteOpCodes = new OpCode[0x1f];
var fields = typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (var field in fields)
{
var opcode = (OpCode)field.GetValue(null);
if (opcode.OpCodeType == OpCodeType.Nternal)
{
continue;
}
if (opcode.Size == 1)
{
oneByteOpCodes[opcode.Value] = opcode;
}
else
{
twoByteOpCodes[opcode.Value & 0xff] = opcode;
}
}
}
private MethodBodyReader(MethodBase method)
{
this.method = method;
this.body = method.GetMethodBody();
if (this.body == null)
throw new ArgumentException("Method has no body");
var bytes = body.GetILAsByteArray();
if (bytes == null)
{
throw new ArgumentException("Can not get the body of the method");
}
if (!(method is ConstructorInfo))
{
methodArguments = method.GetGenericArguments();
}
if (method.DeclaringType != null)
{
typeArguments = method.DeclaringType.GetGenericArguments();
}
this.parameters = method.GetParameters();
this.locals = body.LocalVariables;
this.module = method.Module;
this.ilBuffer = new ByteBuffer(bytes);
this.instructions = new List<Instruction>((bytes.Length + 1) / 2);
}
void ReadInstructions()
{
Instruction previous = null;
while (ilBuffer.position < ilBuffer.buffer.Length)
{
var instruction = new Instruction(ilBuffer.position, ReadOpCode());
ReadOperand(instruction);
if (previous != null)
{
instruction.Previous = previous;
previous.Next = instruction;
}
instructions.Add(instruction);
previous = instruction;
}
ResolveBranches();
}
void ReadOperand(Instruction instruction)
{
switch (instruction.OpCode.OperandType)
{
case OperandType.InlineNone:
break;
case OperandType.InlineSwitch:
int length = ilBuffer.ReadInt32();
int base_offset = ilBuffer.position + (4 * length);
int[] branches = new int[length];
for (int i = 0; i < length; i++)
{
branches[i] = ilBuffer.ReadInt32() + base_offset;
}
instruction.Operand = branches;
break;
case OperandType.ShortInlineBrTarget:
instruction.Operand = (((sbyte)ilBuffer.ReadByte()) + ilBuffer.position);
break;
case OperandType.InlineBrTarget:
instruction.Operand = ilBuffer.ReadInt32() + ilBuffer.position;
break;
case OperandType.ShortInlineI:
if (instruction.OpCode == OpCodes.Ldc_I4_S)
{
instruction.Operand = (sbyte)ilBuffer.ReadByte();
}
else
{
instruction.Operand = ilBuffer.ReadByte();
}
break;
case OperandType.InlineI:
instruction.Operand = ilBuffer.ReadInt32();
break;
case OperandType.ShortInlineR:
instruction.Operand = ilBuffer.ReadSingle();
break;
case OperandType.InlineR:
instruction.Operand = ilBuffer.ReadDouble();
break;
case OperandType.InlineI8:
instruction.Operand = ilBuffer.ReadInt64();
break;
case OperandType.InlineSig:
instruction.Operand = module.ResolveSignature(ilBuffer.ReadInt32());
break;
case OperandType.InlineString:
instruction.Operand = module.ResolveString(ilBuffer.ReadInt32());
break;
case OperandType.InlineTok:
case OperandType.InlineType:
case OperandType.InlineMethod:
case OperandType.InlineField:
instruction.Operand = module.ResolveMember(ilBuffer.ReadInt32(), typeArguments, methodArguments);
break;
case OperandType.ShortInlineVar:
instruction.Operand = GetVariable(instruction, ilBuffer.ReadByte());
break;
case OperandType.InlineVar:
instruction.Operand = GetVariable(instruction, ilBuffer.ReadInt16());
break;
default:
throw new NotSupportedException();
}
}
void ResolveBranches()
{
foreach (var instruction in instructions)
{
switch (instruction.OpCode.OperandType)
{
case OperandType.ShortInlineBrTarget:
case OperandType.InlineBrTarget:
instruction.Operand = GetInstruction(instructions, (int)instruction.Operand);
break;
case OperandType.InlineSwitch:
var offsets = (int[])instruction.Operand;
var branches = new Instruction[offsets.Length];
for (int j = 0; j < offsets.Length; j++)
{
branches[j] = GetInstruction(instructions, offsets[j]);
}
instruction.Operand = branches;
break;
}
}
}
static Instruction GetInstruction(List<Instruction> instructions, int offset)
{
var size = instructions.Count;
if (offset < 0 || offset > instructions[size - 1].Offset)
{
return null;
}
int min = 0;
int max = size - 1;
while (min <= max)
{
int mid = min + ((max - min) / 2);
var instruction = instructions[mid];
var instruction_offset = instruction.Offset;
if (offset == instruction_offset)
{
return instruction;
}
if (offset < instruction_offset)
{
max = mid - 1;
}
else
{
min = mid + 1;
}
}
return null;
}
object GetVariable(Instruction instruction, int index)
{
return TargetsLocalVariable(instruction.OpCode)
? (object)GetLocalVariable(index)
: (object)GetParameter(index);
}
static bool TargetsLocalVariable(OpCode opcode)
{
return opcode.Name.Contains("loc");
}
LocalVariableInfo GetLocalVariable(int index)
{
return locals[index];
}
ParameterInfo GetParameter(int index)
{
return parameters[method.IsStatic ? index : index - 1];
}
OpCode ReadOpCode()
{
byte op = ilBuffer.ReadByte();
return op != 0xfe
? oneByteOpCodes[op]
: twoByteOpCodes[ilBuffer.ReadByte()];
}
/// <summary>
/// Returns the instruction for the given method
/// </summary>
/// <param name="method">The method</param>
public static IList<Instruction> GetInstructions(MethodBase method)
{
var reader = new MethodBodyReader(method);
reader.ReadInstructions();
return reader.instructions;
}
}
}
| |
/*
* 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 QuantConnect.Securities;
using QuantConnect.Securities.Cfd;
using QuantConnect.Securities.Forex;
using QuantConnect.Securities.Crypto;
namespace QuantConnect.Util
{
/// <summary>
/// Utility methods for decomposing and comparing currency pairs
/// </summary>
public static class CurrencyPairUtil
{
private static readonly Lazy<SymbolPropertiesDatabase> SymbolPropertiesDatabase =
new Lazy<SymbolPropertiesDatabase>(Securities.SymbolPropertiesDatabase.FromDataFolder);
/// <summary>
/// Tries to decomposes the specified currency pair into a base and quote currency provided as out parameters
/// </summary>
/// <param name="currencyPair">The input currency pair to be decomposed</param>
/// <param name="baseCurrency">The output base currency</param>
/// <param name="quoteCurrency">The output quote currency</param>
/// <returns>True if was able to decompose the currency pair</returns>
public static bool TryDecomposeCurrencyPair(Symbol currencyPair, out string baseCurrency, out string quoteCurrency)
{
baseCurrency = null;
quoteCurrency = null;
if (!IsValidSecurityType(currencyPair?.SecurityType, throwException: false))
{
return false;
}
try
{
DecomposeCurrencyPair(currencyPair, out baseCurrency, out quoteCurrency);
return true;
}
catch
{
// ignored
}
return false;
}
/// <summary>
/// Decomposes the specified currency pair into a base and quote currency provided as out parameters
/// </summary>
/// <param name="currencyPair">The input currency pair to be decomposed</param>
/// <param name="baseCurrency">The output base currency</param>
/// <param name="quoteCurrency">The output quote currency</param>
/// <param name="defaultQuoteCurrency">Optionally can provide a default quote currency</param>
public static void DecomposeCurrencyPair(Symbol currencyPair, out string baseCurrency, out string quoteCurrency, string defaultQuoteCurrency = Currencies.USD)
{
IsValidSecurityType(currencyPair?.SecurityType, throwException: true);
var securityType = currencyPair.SecurityType;
if (securityType == SecurityType.Forex)
{
Forex.DecomposeCurrencyPair(currencyPair.Value, out baseCurrency, out quoteCurrency);
return;
}
var symbolProperties = SymbolPropertiesDatabase.Value.GetSymbolProperties(
currencyPair.ID.Market,
currencyPair,
currencyPair.SecurityType,
defaultQuoteCurrency);
if (securityType == SecurityType.Cfd)
{
Cfd.DecomposeCurrencyPair(currencyPair, symbolProperties, out baseCurrency, out quoteCurrency);
}
else
{
Crypto.DecomposeCurrencyPair(currencyPair, symbolProperties, out baseCurrency, out quoteCurrency);
}
}
/// <summary>
/// Checks whether a symbol is decomposable into a base and a quote currency
/// </summary>
/// <param name="currencyPair">The pair to check for</param>
/// <returns>True if the pair can be decomposed into base and quote currencies, false if not</returns>
public static bool IsDecomposable(Symbol currencyPair)
{
if (currencyPair == null)
{
return false;
}
if (currencyPair.SecurityType == SecurityType.Forex)
{
return currencyPair.Value.Length == 6;
}
if (currencyPair.SecurityType == SecurityType.Cfd || currencyPair.SecurityType == SecurityType.Crypto)
{
var symbolProperties = SymbolPropertiesDatabase.Value.GetSymbolProperties(
currencyPair.ID.Market,
currencyPair,
currencyPair.SecurityType,
Currencies.USD);
return currencyPair.Value.EndsWith(symbolProperties.QuoteCurrency);
}
return false;
}
/// <summary>
/// You have currencyPair AB and one known symbol (A or B). This function returns the other symbol (B or A).
/// </summary>
/// <param name="currencyPair">Currency pair AB</param>
/// <param name="knownSymbol">Known part of the currencyPair (either A or B)</param>
/// <returns>The other part of currencyPair (either B or A), or null if known symbol is not part of currencyPair</returns>
public static string CurrencyPairDual(this Symbol currencyPair, string knownSymbol)
{
string baseCurrency;
string quoteCurrency;
DecomposeCurrencyPair(currencyPair, out baseCurrency, out quoteCurrency);
return CurrencyPairDual(baseCurrency, quoteCurrency, knownSymbol);
}
/// <summary>
/// You have currencyPair AB and one known symbol (A or B). This function returns the other symbol (B or A).
/// </summary>
/// <param name="baseCurrency">The base currency of the currency pair</param>
/// <param name="quoteCurrency">The quote currency of the currency pair</param>
/// <param name="knownSymbol">Known part of the currencyPair (either A or B)</param>
/// <returns>The other part of currencyPair (either B or A), or null if known symbol is not part of the currency pair</returns>
public static string CurrencyPairDual(string baseCurrency, string quoteCurrency, string knownSymbol)
{
if (baseCurrency == knownSymbol)
{
return quoteCurrency;
}
if (quoteCurrency == knownSymbol)
{
return baseCurrency;
}
return null;
}
/// <summary>
/// Represents the relation between two currency pairs
/// </summary>
public enum Match
{
/// <summary>
/// The two currency pairs don't match each other normally nor when one is reversed
/// </summary>
NoMatch,
/// <summary>
/// The two currency pairs match each other exactly
/// </summary>
ExactMatch,
/// <summary>
/// The two currency pairs are the inverse of each other
/// </summary>
InverseMatch
}
/// <summary>
/// Returns how two currency pairs are related to each other
/// </summary>
/// <param name="pairA">The first pair</param>
/// <param name="baseCurrencyB">The base currency of the second pair</param>
/// <param name="quoteCurrencyB">The quote currency of the second pair</param>
/// <returns>The <see cref="Match"/> member that represents the relation between the two pairs</returns>
public static Match ComparePair(this Symbol pairA, string baseCurrencyB, string quoteCurrencyB)
{
if (pairA.Value == baseCurrencyB + quoteCurrencyB)
{
return Match.ExactMatch;
}
if (pairA.Value == quoteCurrencyB + baseCurrencyB)
{
return Match.InverseMatch;
}
return Match.NoMatch;
}
private static bool IsValidSecurityType(SecurityType? securityType, bool throwException)
{
if (securityType == null)
{
if (throwException)
{
throw new ArgumentException("Currency pair must not be null");
}
return false;
}
if (securityType != SecurityType.Forex &&
securityType != SecurityType.Cfd &&
securityType != SecurityType.Crypto)
{
if (throwException)
{
throw new ArgumentException($"Unsupported security type: {securityType}");
}
return false;
}
return true;
}
}
}
| |
#region Header
//
// CmdSlopedFloor.cs - create a sloped floor
//
// Copyright (C) 2008-2021 by Jeremy Tammik,
// Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#region Namespaces
using System.Collections.Generic;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
#endregion // Namespaces
namespace BuildingCoder
{
/// <summary>
/// Create sloped slab using the NewSlab method.
/// Also demonstrate checking whether a specific
/// level exists and creating it is not.
/// </summary>
[Transaction(TransactionMode.Manual)]
public class CmdCreateSlopedSlab : IExternalCommand
{
public Result Execute(
ExternalCommandData revit,
ref string message,
ElementSet elements)
{
var uiapp = revit.Application;
var uidoc = uiapp.ActiveUIDocument;
var doc = uidoc.Document;
using var tx = new Transaction(doc);
tx.Start("Create Sloped Slab");
var width = 19.685039400;
var length = 59.055118200;
var height = 9.84251968503937;
var pts = new[]
{
new(0.0, 0.0, height),
new XYZ(width, 0.0, height),
new XYZ(width, length, height),
new XYZ(0, length, height)
};
#region Before Floor.Create method
#if BEFORE_FLOOR_CREATE_METHOD
CurveArray profile_arr
= uiapp.Application.Create.NewCurveArray();
Line line = null;
int n = pts.GetLength( 0 );
XYZ q = pts[n - 1];
foreach( XYZ p in pts )
{
line = Line.CreateBound( q, p );
profile_arr.Append( line );
q = p;
}
Level level
= new FilteredElementCollector( doc )
.OfClass( typeof( Level ) )
.Where<Element>(
e => e.Name.Equals( "CreateSlopedSlab" ) )
.FirstOrDefault<Element>() as Level;
if( null == level )
{
//level = doc.Create.NewLevel( height ); // 2015
level = Level.Create( doc, height ); // 2016
level.Name = "Sloped Slab";
}
Floor floor1 = doc.Create.NewSlab(
profile_arr, level, line, 0.5, true ); // 2021
#endif // BEFORE_FLOOR_CREATE_METHOD
#endregion // Before Floor.Create method
var isFoundation = true;
var floorTypeId = Floor.GetDefaultFloorType(
doc, isFoundation);
double offset;
var levelId = Level.GetNearestLevelId(
doc, height, out offset);
// Build a floor profile for the floor creation
var profile = new CurveLoop();
profile.Append(Line.CreateBound(pts[0], pts[1]));
profile.Append(Line.CreateBound(pts[1], pts[2]));
profile.Append(Line.CreateBound(pts[2], pts[3]));
profile.Append(Line.CreateBound(pts[3], pts[0]));
// The elevation of the curve loops is not taken
// into account (unlike the obsolete NewFloor and
// NewSlab methods).
// If the default elevation is not what you want,
// you need to set it explicitly.
var floor = Floor.Create(doc,
new List<CurveLoop> {profile},
floorTypeId, levelId);
var param = floor.get_Parameter(
BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM);
param.Set(offset);
tx.Commit();
return Result.Succeeded;
}
}
#region Unsuccessful attempt to modify existing floor slope
/// <summary>
/// Unsuccessful attempt to change the
/// slope of an existing floor element.
/// </summary>
[Transaction(TransactionMode.Manual)]
public class CmdChangeFloorSlope : IExternalCommand
{
public Result Execute(
ExternalCommandData revit,
ref string message,
ElementSet elements)
{
var uiapp = revit.Application;
var uidoc = uiapp.ActiveUIDocument;
var doc = uidoc.Document;
var sel = uidoc.Selection;
var ref1 = sel.PickObject(
ObjectType.Element, "Please pick a floor.");
if (doc.GetElement(ref1) is not Floor f)
return Result.Failed;
// Retrieve floor edge model line elements.
ICollection<ElementId> deleted_ids;
using (var tx = new Transaction(doc))
{
tx.Start("Temporarily Delete Floor");
deleted_ids = doc.Delete(f.Id);
tx.RollBack();
}
// Grab the first floor edge model line.
ModelLine ml = null;
foreach (var id in deleted_ids)
{
ml = doc.GetElement(id) as ModelLine;
if (null != ml) break;
}
if (null != ml)
{
using var tx = new Transaction(doc);
tx.Start("Change Slope Angle");
// This parameter is read only. Therefore,
// the change does not work and we cannot
// change the floor slope angle after the
// floor is created.
ml.get_Parameter(
BuiltInParameter.CURVE_IS_SLOPE_DEFINING)
.Set(1);
ml.get_Parameter(
BuiltInParameter.ROOF_SLOPE)
.Set(1.2);
tx.Commit();
}
return Result.Succeeded;
}
}
#endregion // Unsuccessful attempt to modify existing floor slope
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using TicTacToe.Web.Areas.HelpPage.ModelDescriptions;
using TicTacToe.Web.Areas.HelpPage.Models;
namespace TicTacToe.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
//#define _TWO_PHASE_CELL_MANIPULATION_
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Net;
using Trinity;
using System.Runtime.CompilerServices;
using Trinity.Core.Lib;
using Trinity.Configuration;
namespace Trinity.Storage
{
public unsafe partial class LocalMemoryStorage : Storage
{
/// <summary>
/// Releases the cell lock associated with the current cell.
/// Do not call this method to release a cell that is not acquired
/// by this thread or task.
/// </summary>
/// <param name="cellId">A 64-bit cell id.</param>
/// <param name="entryIndex">The hash slot index corresponding to the current cell.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReleaseCellLock(long cellId, int entryIndex)
{
CLocalMemoryStorage.CReleaseCellLock(cellId, entryIndex);
}
/// <summary>
/// Locks the current cell and gets its underlying storage information.
/// </summary>
/// <param name="cellId">A 64-bit cell id.</param>
/// <param name="size">The size of the cell in bytes.</param>
/// <param name="type">A 16-bit unsigned integer indicating the cell type.</param>
/// <param name="cellPtr">A pointer pointing to the underlying cell buffer.</param>
/// <param name="entryIndex">The hash slot index corresponding to the current cell.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if the operation succeeds; <c>TrinityErrorCode.E_CELL_NOT_FOUND</c> if the specified cell is not found. </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TrinityErrorCode GetLockedCellInfo(long cellId, out int size, out ushort type, out byte* cellPtr, out int entryIndex)
{
TrinityErrorCode eResult = CLocalMemoryStorage.CGetLockedCellInfo4CellAccessor(cellId, out size, out type, out cellPtr, out entryIndex);
return eResult;
}
/// <summary>
/// Adds a new cell with the specified cell id or uses the cell if a cell with the specified cell id already exists.
/// </summary>
/// <param name="cellId">A 64-bit cell id.</param>
/// <param name="cellBuff">The buffer of the cell to be added.</param>
/// <param name="size">The size of the cell to be added. It will be overwritten to the size of the existing cell with specified cell id if it exists.</param>
/// <param name="cellType">A 16-bit unsigned integer indicating the cell type.</param>
/// <param name="cellPtr">A pointer pointing to the underlying cell buffer.</param>
/// <param name="cellEntryIndex">The hash slot index corresponding to the current cell.</param>
/// <returns><c>TrinityErrorCode.E_CELL_FOUND</c> if the specified cell is found; <c>TrinityErrorCode.E_WRONG_CELL_TYPE</c> if the cell type of the cell with the specified cellId does not match the specified cellType; <c>TrinityErrorCode.E_CELL_NOT_FOUND</c> if the specified cell is not found.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TrinityErrorCode AddOrUse(long cellId, byte[] cellBuff, ref int size, ushort cellType, out byte* cellPtr, out int cellEntryIndex)
{
TrinityErrorCode eResult = CLocalMemoryStorage.CGetLockedCellInfo4AddOrUseCell(cellId, ref size, cellType, out cellPtr, out cellEntryIndex);
if (eResult == TrinityErrorCode.E_CELL_NOT_FOUND)
{
Memory.Copy(cellBuff, cellPtr, size);
}
return eResult;
}
/// <summary>
/// Resizes the cell with the specified cell id.
/// Do not call this method to resize a cell that is not locked
/// by this thread/task.
/// </summary>
/// <param name="cell_id">A 64-bit cell id.</param>
/// <param name="cellEntryIndex">The hash slot index corresponding to the current cell.</param>
/// <param name="offset">The offset starting which the underlying storage needs to expand or shrink.</param>
/// <param name="delta">The size to expand or shrink, in bytes.</param>
/// <returns>The pointer pointing to the underlying cell buffer after resizing.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public byte* ResizeCell(long cell_id, int cellEntryIndex, int offset, int delta)
{
return CLocalMemoryStorage.CResizeCell(cell_id, cellEntryIndex, offset, delta);
}
/// <summary>
/// Adds a new cell to the key-value store if the cell Id does not exist, or updates an existing cell in the key-value store if the cell Id already exists.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if saving succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode SaveCell(long cellId, byte[] buff)
{
fixed (byte* p = buff)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CSaveCell(cellId, p, buff.Length, StorageConfig.c_UndefinedCellType);
return eResult;
}
}
/// <summary>
/// Adds a new cell to the key-value store if the cell Id does not exist, or updates an existing cell in the key-value store if the cell Id already exists.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="cellType">Indicates the cell type.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if saving succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TrinityErrorCode SaveCell(long cellId, byte[] buff, ushort cellType)
{
fixed (byte* p = buff)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CSaveCell(cellId, p, buff.Length, cellType);
return eResult;
}
}
/// <summary>
/// Adds a new cell to the key-value store if the cell Id does not exist, or updates an existing cell in the key-value store if the cell Id already exists.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="offset">The byte offset into the buff.</param>
/// <param name="cellSize">The size of the cell.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if saving succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode SaveCell(long cellId, byte[] buff, int offset, int cellSize)
{
fixed (byte* p = buff)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CSaveCell(cellId, p + offset, cellSize, StorageConfig.c_UndefinedCellType);
return eResult;
}
}
/// <summary>
/// Adds a new cell to the key-value store if the cell Id does not exist, or updates an existing cell in the key-value store if the cell Id already exists.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="offset">The byte offset into the buff.</param>
/// <param name="cellSize">The size of the cell.</param>
/// <param name="cellType">Indicates the cell type.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if saving succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode SaveCell(long cellId, byte[] buff, int offset, int cellSize, ushort cellType)
{
fixed (byte* p = buff)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CSaveCell(cellId, p + offset, cellSize, cellType);
return eResult;
}
}
/// <summary>
/// Adds a new cell to the key-value store if the cell Id does not exist, or updates an existing cell in the key-value store if the cell Id already exists.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="cellSize">The size of the cell.</param>
/// <param name="cellType">Indicates the cell type.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if saving succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode SaveCell(long cellId, byte* buff, int cellSize, ushort cellType)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CSaveCell(cellId, buff, cellSize, cellType);
return eResult;
}
/// <summary>
/// Adds a new cell to the key-value store if the cell Id does not exist, or updates an existing cell in the key-value store if the cell Id already exists.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="cellSize">The size of the cell.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if saving succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode SaveCell(long cellId, byte* buff, int cellSize)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CSaveCell(cellId, buff, cellSize, StorageConfig.c_UndefinedCellType);
return eResult;
}
/// <summary>
/// Adds a new cell to the Trinity key-value store.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="cellSize">The size of the cell.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if adding succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode AddCell(long cellId, byte* buff, int cellSize)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CAddCell(cellId, buff, cellSize, StorageConfig.c_UndefinedCellType);
return eResult;
}
/// <summary>
/// Adds a new cell to the Trinity key-value store.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if adding succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode AddCell(long cellId, byte[] buff)
{
fixed (byte* p = buff)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CAddCell(cellId, p, buff.Length, StorageConfig.c_UndefinedCellType);
return eResult;
}
}
/// <summary>
/// Adds a new cell to the Trinity key-value store.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="offset">The byte offset into the buff.</param>
/// <param name="cellSize">The size of the cell.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if adding succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode AddCell(long cellId, byte[] buff, int offset, int cellSize)
{
fixed (byte* p = buff)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CAddCell(cellId, p + offset, cellSize, StorageConfig.c_UndefinedCellType);
return eResult;
}
}
/// <summary>
/// Adds a new cell to the Trinity key-value store.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="offset">The byte offset into the buff.</param>
/// <param name="cellSize">The size of the cell.</param>
/// <param name="cellType">Indicates the cell type.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if adding succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode AddCell(long cellId, byte[] buff, int offset, int cellSize, ushort cellType)
{
fixed (byte* p = buff)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CAddCell(cellId, p + offset, cellSize, cellType);
return eResult;
}
}
/// <summary>
/// Adds a new cell to the Trinity key-value store.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="cellSize">The size of the cell.</param>
/// <param name="cellType">Indicates the cell type.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if adding succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode AddCell(long cellId, byte* buff, int cellSize, ushort cellType)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CAddCell(cellId, buff, cellSize, cellType);
return eResult;
}
/// <summary>
/// Updates an existing cell in the Trinity key-value store.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="cellSize">The size of the cell.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if updating succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode UpdateCell(long cellId, byte* buff, int cellSize)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CUpdateCell(cellId, buff, cellSize);
return eResult;
}
/// <summary>
/// Updates an existing cell in the Trinity key-value store.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if updating succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode UpdateCell(long cellId, byte[] buff)
{
fixed (byte* p = buff)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CUpdateCell(cellId, p, buff.Length);
return eResult;
}
}
/// <summary>
/// Updates an existing cell in the Trinity key-value store.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="buff">A memory buffer that contains the cell content.</param>
/// <param name="offset">The byte offset into the buff.</param>
/// <param name="cellSize">The size of the cell.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if updating succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode UpdateCell(long cellId, byte[] buff, int offset, int cellSize)
{
fixed (byte* p = buff)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CUpdateCell(cellId, p + offset, cellSize);
return eResult;
}
}
/// <summary>
/// Loads the bytes of the cell with the specified cell Id.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="cellBuff">The bytes of the cell. An empty byte array is returned if the cell is not found.</param>
/// <param name="cellType">The type of the cell, represented with a 16-bit unsigned integer.</param>
/// <returns>A Trinity error code. Possible values are E_SUCCESS and E_NOT_FOUND.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode LoadCell(long cellId, out byte[] cellBuff, out ushort cellType)
{
int index, cellSize;
byte* cellPtr = null;
TrinityErrorCode eResult= CLocalMemoryStorage.CGetLockedCellInfo4CellAccessor(cellId, out cellSize, out cellType, out cellPtr, out index);
if (eResult == TrinityErrorCode.E_CELL_NOT_FOUND)
{
cellBuff = new byte[0];
cellType = StorageConfig.c_UndefinedCellType;
return eResult;
}
cellBuff = new byte[cellSize];
Memory.Copy(cellPtr, 0, cellBuff, 0, cellSize);
CLocalMemoryStorage.CReleaseCellLock(cellId, index);
return TrinityErrorCode.E_SUCCESS;
}
/// <summary>
/// Loads the bytes of the cell with the specified cell Id.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="cellBuff">The bytes of the cell. An empty byte array is returned if the cell is not found.</param>
/// <returns>A Trinity error code. Possible values are E_SUCCESS and E_NOT_FOUND.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode LoadCell(long cellId, out byte[] cellBuff)
{
int index, cellSize;
byte* cellPtr = null;
TrinityErrorCode eResult= CLocalMemoryStorage.CGetLockedCellInfo4LoadCell(cellId, out cellSize, out cellPtr, out index);
if (eResult == TrinityErrorCode.E_CELL_NOT_FOUND)
{
cellBuff = new byte[0];
return eResult;
}
cellBuff = new byte[cellSize];
Memory.Copy(cellPtr, 0, cellBuff, 0, cellSize);
CLocalMemoryStorage.CReleaseCellLock(cellId, index);
return TrinityErrorCode.E_SUCCESS;
}
/// <summary>
/// Removes the cell with the specified cell Id from the key-value store.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <returns><c>TrinityErrorCode.E_SUCCESS</c> if removing succeeds; otherwise, an error code.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode RemoveCell(long cellId)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CRemoveCell(cellId);
return eResult;
}
/// <summary>
/// Gets the type of the cell with specified cell Id.
/// </summary>
/// <param name="cellId">A 64-bit cell Id.</param>
/// <param name="cellType">The type of the cell specified by cellId.</param>
/// <returns>A Trinity error code. Possible values are E_SUCCESS and E_NOT_FOUND.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TrinityErrorCode GetCellType(long cellId, out ushort cellType)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CGetCellType(cellId, out cellType);
return eResult;
}
/// <summary>
/// Determines whether there is a cell with the specified cell Id in Trinity key-value store.
/// </summary>
/// <param name="cellId">A 64-bit cell id.</param>
/// <returns>true if a cell whose Id is cellId is found; otherwise, false.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Contains(long cellId)
{
TrinityErrorCode eResult= CLocalMemoryStorage.CContains(cellId);
switch (eResult)
{
case TrinityErrorCode.E_CELL_FOUND:
return true;
case TrinityErrorCode.E_DEADLOCK:
throw new DeadlockException();
case TrinityErrorCode.E_CELL_NOT_FOUND:
default:
return false;
}
}
/// <summary>
/// Gets the size of the current cell. The caller must hold the cell lock before calling this function.
/// </summary>
/// <param name="cellId">A 64-bit cell id.</param>
/// <param name="entryIndex">The hash slot index corresponding to the current cell.</param>
/// <param name="size">The size of the specified cell.</param>
/// <returns>A Trinity error code. This function always returns E_SUCCESS.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public TrinityErrorCode LockedGetCellSize(long cellId, int entryIndex, out int size)
{
return CLocalMemoryStorage.CLockedGetCellSize(cellId, entryIndex, out size);
}
}
}
| |
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 KGSBrowseMVC.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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.ActionDescriptor.ReturnType;
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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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 GeckoUBL.Ubl21.Cac;
using GeckoUBL.Ubl21.Cec;
using GeckoUBL.Ubl21.Udt;
namespace GeckoUBL.Ubl21.Documents
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:OrderChange-2")]
[System.Xml.Serialization.XmlRootAttribute("OrderChange", Namespace="urn:oasis:names:specification:ubl:schema:xsd:OrderChange-2", IsNullable=false)]
public class OrderChangeType {
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2")]
[System.Xml.Serialization.XmlArrayItemAttribute("UBLExtension", IsNullable=false)]
public UBLExtensionType[] UBLExtensions { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType UBLVersionID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType CustomizationID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType ProfileID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType ProfileExecutionID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType ID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType SalesOrderID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IndicatorType CopyIndicator { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType UUID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public DateType IssueDate { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TimeType IssueTime { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public IdentifierType SequenceNumberID { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Note", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType[] Note { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public CodeType RequestedInvoiceCurrencyCode { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public CodeType DocumentCurrencyCode { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public CodeType PricingCurrencyCode { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public CodeType TaxCurrencyCode { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType CustomerReference { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public CodeType AccountingCostCode { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public TextType AccountingCost { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
public NumericType LineCountNumeric { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ValidityPeriod", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public PeriodType[] ValidityPeriod { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public OrderReferenceType OrderReference { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public DocumentReferenceType QuotationDocumentReference { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public DocumentReferenceType OriginatorDocumentReference { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("AdditionalDocumentReference", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public DocumentReferenceType[] AdditionalDocumentReference { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Contract", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public ContractType[] Contract { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Signature", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public SignatureType[] Signature { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public CustomerPartyType BuyerCustomerParty { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public SupplierPartyType SellerSupplierParty { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public CustomerPartyType OriginatorCustomerParty { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public PartyType FreightForwarderParty { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public CustomerPartyType AccountingCustomerParty { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public SupplierPartyType AccountingSupplierParty { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Delivery", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public DeliveryType[] Delivery { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public DeliveryTermsType DeliveryTerms { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("PaymentMeans", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public PaymentMeansType[] PaymentMeans { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("PaymentTerms", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public PaymentTermsType[] PaymentTerms { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public TransactionConditionsType TransactionConditions { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("AllowanceCharge", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public AllowanceChargeType[] AllowanceCharge { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public ExchangeRateType TaxExchangeRate { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public ExchangeRateType PricingExchangeRate { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public ExchangeRateType PaymentExchangeRate { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public CountryType DestinationCountry { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("TaxTotal", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public TaxTotalType[] TaxTotal { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public MonetaryTotalType AnticipatedMonetaryTotal { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("OrderLine", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
public OrderLineType[] OrderLine { get; set; }
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.DotNet.PlatformAbstractions;
namespace Microsoft.DotNet.Tools.Common
{
public static class PathUtility
{
public static bool IsPlaceholderFile(string path)
{
return string.Equals(Path.GetFileName(path), "_._", StringComparison.Ordinal);
}
public static bool IsChildOfDirectory(string dir, string candidate)
{
if (dir == null)
{
throw new ArgumentNullException(nameof(dir));
}
if (candidate == null)
{
throw new ArgumentNullException(nameof(candidate));
}
dir = Path.GetFullPath(dir);
dir = EnsureTrailingSlash(dir);
candidate = Path.GetFullPath(candidate);
return candidate.StartsWith(dir, StringComparison.OrdinalIgnoreCase);
}
public static string EnsureTrailingSlash(string path)
{
return EnsureTrailingCharacter(path, Path.DirectorySeparatorChar);
}
public static string EnsureTrailingForwardSlash(string path)
{
return EnsureTrailingCharacter(path, '/');
}
private static string EnsureTrailingCharacter(string path, char trailingCharacter)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
// if the path is empty, we want to return the original string instead of a single trailing character.
if (path.Length == 0 || path[path.Length - 1] == trailingCharacter)
{
return path;
}
return path + trailingCharacter;
}
public static string EnsureNoTrailingDirectorySeparator(string path)
{
if (!string.IsNullOrEmpty(path))
{
char lastChar = path[path.Length - 1];
if (lastChar == Path.DirectorySeparatorChar)
{
path = path.Substring(0, path.Length - 1);
}
}
return path;
}
public static void EnsureParentDirectory(string filePath)
{
string directory = Path.GetDirectoryName(filePath);
EnsureDirectory(directory);
}
public static void EnsureDirectory(string directoryPath)
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
/// <summary>
/// Returns path2 relative to path1, with Path.DirectorySeparatorChar as separator
/// </summary>
public static string GetRelativePath(string path1, string path2)
{
return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, true);
}
/// <summary>
/// Returns path2 relative to path1, with Path.DirectorySeparatorChar as separator but ignoring directory
/// traversals.
/// </summary>
public static string GetRelativePathIgnoringDirectoryTraversals(string path1, string path2)
{
return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, false);
}
/// <summary>
/// Returns path2 relative to path1, with given path separator
/// </summary>
public static string GetRelativePath(string path1, string path2, char separator, bool includeDirectoryTraversals)
{
if (string.IsNullOrEmpty(path1))
{
throw new ArgumentException("Path must have a value", nameof(path1));
}
if (string.IsNullOrEmpty(path2))
{
throw new ArgumentException("Path must have a value", nameof(path2));
}
StringComparison compare;
if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows)
{
compare = StringComparison.OrdinalIgnoreCase;
// check if paths are on the same volume
if (!string.Equals(Path.GetPathRoot(path1), Path.GetPathRoot(path2)))
{
// on different volumes, "relative" path is just path2
return path2;
}
}
else
{
compare = StringComparison.Ordinal;
}
var index = 0;
var path1Segments = path1.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var path2Segments = path2.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// if path1 does not end with / it is assumed the end is not a directory
// we will assume that is isn't a directory by ignoring the last split
var len1 = path1Segments.Length - 1;
var len2 = path2Segments.Length;
// find largest common absolute path between both paths
var min = Math.Min(len1, len2);
while (min > index)
{
if (!string.Equals(path1Segments[index], path2Segments[index], compare))
{
break;
}
// Handle scenarios where folder and file have same name (only if os supports same name for file and directory)
// e.g. /file/name /file/name/app
else if ((len1 == index && len2 > index + 1) || (len1 > index && len2 == index + 1))
{
break;
}
++index;
}
var path = "";
// check if path2 ends with a non-directory separator and if path1 has the same non-directory at the end
if (len1 + 1 == len2 && !string.IsNullOrEmpty(path1Segments[index]) &&
string.Equals(path1Segments[index], path2Segments[index], compare))
{
return path;
}
if (includeDirectoryTraversals)
{
for (var i = index; len1 > i; ++i)
{
path += ".." + separator;
}
}
for (var i = index; len2 - 1 > i; ++i)
{
path += path2Segments[i] + separator;
}
// if path2 doesn't end with an empty string it means it ended with a non-directory name, so we add it back
if (!string.IsNullOrEmpty(path2Segments[len2 - 1]))
{
path += path2Segments[len2 - 1];
}
return path;
}
public static string GetAbsolutePath(string basePath, string relativePath)
{
if (basePath == null)
{
throw new ArgumentNullException(nameof(basePath));
}
if (relativePath == null)
{
throw new ArgumentNullException(nameof(relativePath));
}
Uri resultUri = new Uri(new Uri(basePath), new Uri(relativePath, UriKind.Relative));
return resultUri.LocalPath;
}
public static string GetDirectoryName(string path)
{
path = path.TrimEnd(Path.DirectorySeparatorChar);
return path.Substring(Path.GetDirectoryName(path).Length).Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
public static string GetPathWithForwardSlashes(string path)
{
return path.Replace('\\', '/');
}
public static string GetPathWithBackSlashes(string path)
{
return path.Replace('/', '\\');
}
public static string GetPathWithDirectorySeparator(string path)
{
if (Path.DirectorySeparatorChar == '/')
{
return GetPathWithForwardSlashes(path);
}
else
{
return GetPathWithBackSlashes(path);
}
}
public static bool HasExtension(string filePath, string extension)
{
var comparison = StringComparison.Ordinal;
if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows)
{
comparison = StringComparison.OrdinalIgnoreCase;
}
return Path.GetExtension(filePath).Equals(extension, comparison);
}
/// <summary>
/// Gets the fully-qualified path without failing if the
/// path is empty.
/// </summary>
public static string GetFullPath(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return path;
}
return Path.GetFullPath(path);
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Dialogflow.Cx.V3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedTestCasesClientTest
{
[xunit::FactAttribute]
public void BatchDeleteTestCasesRequestObject()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
TestCaseNames =
{
TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
},
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.BatchDeleteTestCases(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
client.BatchDeleteTestCases(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BatchDeleteTestCasesRequestObjectAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
TestCaseNames =
{
TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
},
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.BatchDeleteTestCasesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
await client.BatchDeleteTestCasesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.BatchDeleteTestCasesAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BatchDeleteTestCases()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.BatchDeleteTestCases(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
client.BatchDeleteTestCases(request.Parent);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BatchDeleteTestCasesAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.BatchDeleteTestCasesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
await client.BatchDeleteTestCasesAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.BatchDeleteTestCasesAsync(request.Parent, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void BatchDeleteTestCasesResourceNames()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.BatchDeleteTestCases(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
client.BatchDeleteTestCases(request.ParentAsAgentName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task BatchDeleteTestCasesResourceNamesAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.BatchDeleteTestCasesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
await client.BatchDeleteTestCasesAsync(request.ParentAsAgentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.BatchDeleteTestCasesAsync(request.ParentAsAgentName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTestCaseRequestObject()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseRequest request = new GetTestCaseRequest
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.GetTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase response = client.GetTestCase(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTestCaseRequestObjectAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseRequest request = new GetTestCaseRequest
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.GetTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase responseCallSettings = await client.GetTestCaseAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCase responseCancellationToken = await client.GetTestCaseAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTestCase()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseRequest request = new GetTestCaseRequest
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.GetTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase response = client.GetTestCase(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTestCaseAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseRequest request = new GetTestCaseRequest
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.GetTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase responseCallSettings = await client.GetTestCaseAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCase responseCancellationToken = await client.GetTestCaseAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTestCaseResourceNames()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseRequest request = new GetTestCaseRequest
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.GetTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase response = client.GetTestCase(request.TestCaseName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTestCaseResourceNamesAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseRequest request = new GetTestCaseRequest
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.GetTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase responseCallSettings = await client.GetTestCaseAsync(request.TestCaseName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCase responseCancellationToken = await client.GetTestCaseAsync(request.TestCaseName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTestCaseRequestObject()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTestCaseRequest request = new CreateTestCaseRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
TestCase = new TestCase(),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.CreateTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase response = client.CreateTestCase(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTestCaseRequestObjectAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTestCaseRequest request = new CreateTestCaseRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
TestCase = new TestCase(),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.CreateTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase responseCallSettings = await client.CreateTestCaseAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCase responseCancellationToken = await client.CreateTestCaseAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTestCase()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTestCaseRequest request = new CreateTestCaseRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
TestCase = new TestCase(),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.CreateTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase response = client.CreateTestCase(request.Parent, request.TestCase);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTestCaseAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTestCaseRequest request = new CreateTestCaseRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
TestCase = new TestCase(),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.CreateTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase responseCallSettings = await client.CreateTestCaseAsync(request.Parent, request.TestCase, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCase responseCancellationToken = await client.CreateTestCaseAsync(request.Parent, request.TestCase, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTestCaseResourceNames()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTestCaseRequest request = new CreateTestCaseRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
TestCase = new TestCase(),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.CreateTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase response = client.CreateTestCase(request.ParentAsAgentName, request.TestCase);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTestCaseResourceNamesAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTestCaseRequest request = new CreateTestCaseRequest
{
ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
TestCase = new TestCase(),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.CreateTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase responseCallSettings = await client.CreateTestCaseAsync(request.ParentAsAgentName, request.TestCase, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCase responseCancellationToken = await client.CreateTestCaseAsync(request.ParentAsAgentName, request.TestCase, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateTestCaseRequestObject()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTestCaseRequest request = new UpdateTestCaseRequest
{
TestCase = new TestCase(),
UpdateMask = new wkt::FieldMask(),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.UpdateTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase response = client.UpdateTestCase(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateTestCaseRequestObjectAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTestCaseRequest request = new UpdateTestCaseRequest
{
TestCase = new TestCase(),
UpdateMask = new wkt::FieldMask(),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.UpdateTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase responseCallSettings = await client.UpdateTestCaseAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCase responseCancellationToken = await client.UpdateTestCaseAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateTestCase()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTestCaseRequest request = new UpdateTestCaseRequest
{
TestCase = new TestCase(),
UpdateMask = new wkt::FieldMask(),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.UpdateTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase response = client.UpdateTestCase(request.TestCase, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateTestCaseAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTestCaseRequest request = new UpdateTestCaseRequest
{
TestCase = new TestCase(),
UpdateMask = new wkt::FieldMask(),
};
TestCase expectedResponse = new TestCase
{
TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"),
Tags = { "tags52c47ad5", },
DisplayName = "display_name137f65c2",
Notes = "notes00b55843",
TestCaseConversationTurns =
{
new ConversationTurn(),
},
CreationTime = new wkt::Timestamp(),
LastTestResult = new TestCaseResult(),
TestConfig = new TestConfig(),
};
mockGrpcClient.Setup(x => x.UpdateTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCase responseCallSettings = await client.UpdateTestCaseAsync(request.TestCase, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCase responseCancellationToken = await client.UpdateTestCaseAsync(request.TestCase, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CalculateCoverageRequestObject()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateCoverageRequest request = new CalculateCoverageRequest
{
Type = CalculateCoverageRequest.Types.CoverageType.TransitionRouteGroup,
AgentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
};
CalculateCoverageResponse expectedResponse = new CalculateCoverageResponse
{
IntentCoverage = new IntentCoverage(),
TransitionCoverage = new TransitionCoverage(),
AgentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
RouteGroupCoverage = new TransitionRouteGroupCoverage(),
};
mockGrpcClient.Setup(x => x.CalculateCoverage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
CalculateCoverageResponse response = client.CalculateCoverage(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CalculateCoverageRequestObjectAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CalculateCoverageRequest request = new CalculateCoverageRequest
{
Type = CalculateCoverageRequest.Types.CoverageType.TransitionRouteGroup,
AgentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
};
CalculateCoverageResponse expectedResponse = new CalculateCoverageResponse
{
IntentCoverage = new IntentCoverage(),
TransitionCoverage = new TransitionCoverage(),
AgentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"),
RouteGroupCoverage = new TransitionRouteGroupCoverage(),
};
mockGrpcClient.Setup(x => x.CalculateCoverageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CalculateCoverageResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
CalculateCoverageResponse responseCallSettings = await client.CalculateCoverageAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
CalculateCoverageResponse responseCancellationToken = await client.CalculateCoverageAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTestCaseResultRequestObject()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseResultRequest request = new GetTestCaseResultRequest
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
};
TestCaseResult expectedResponse = new TestCaseResult
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
ConversationTurns =
{
new ConversationTurn(),
},
TestResult = TestResult.Failed,
TestTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetTestCaseResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCaseResult response = client.GetTestCaseResult(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTestCaseResultRequestObjectAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseResultRequest request = new GetTestCaseResultRequest
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
};
TestCaseResult expectedResponse = new TestCaseResult
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
ConversationTurns =
{
new ConversationTurn(),
},
TestResult = TestResult.Failed,
TestTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetTestCaseResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCaseResult>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCaseResult responseCallSettings = await client.GetTestCaseResultAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCaseResult responseCancellationToken = await client.GetTestCaseResultAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTestCaseResult()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseResultRequest request = new GetTestCaseResultRequest
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
};
TestCaseResult expectedResponse = new TestCaseResult
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
ConversationTurns =
{
new ConversationTurn(),
},
TestResult = TestResult.Failed,
TestTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetTestCaseResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCaseResult response = client.GetTestCaseResult(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTestCaseResultAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseResultRequest request = new GetTestCaseResultRequest
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
};
TestCaseResult expectedResponse = new TestCaseResult
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
ConversationTurns =
{
new ConversationTurn(),
},
TestResult = TestResult.Failed,
TestTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetTestCaseResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCaseResult>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCaseResult responseCallSettings = await client.GetTestCaseResultAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCaseResult responseCancellationToken = await client.GetTestCaseResultAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTestCaseResultResourceNames()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseResultRequest request = new GetTestCaseResultRequest
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
};
TestCaseResult expectedResponse = new TestCaseResult
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
ConversationTurns =
{
new ConversationTurn(),
},
TestResult = TestResult.Failed,
TestTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetTestCaseResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCaseResult response = client.GetTestCaseResult(request.TestCaseResultName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTestCaseResultResourceNamesAsync()
{
moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTestCaseResultRequest request = new GetTestCaseResultRequest
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
};
TestCaseResult expectedResponse = new TestCaseResult
{
TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"),
EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
ConversationTurns =
{
new ConversationTurn(),
},
TestResult = TestResult.Failed,
TestTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetTestCaseResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCaseResult>(stt::Task.FromResult(expectedResponse), null, null, null, null));
TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null);
TestCaseResult responseCallSettings = await client.GetTestCaseResultAsync(request.TestCaseResultName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
TestCaseResult responseCancellationToken = await client.GetTestCaseResultAsync(request.TestCaseResultName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#define CONTRACTS_FULL
#define CODE_ANALYSIS // For the SuppressMessage attribute
// The regression defines 4 cases as a compiler switch: LOW, MEDIUMLOW, MEDIUM, FULL
// We expect to see less messages with LOW, more with MEDIUMLOW, MEDIUM and all with FULL
// This file is to test the behavior
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Research.ClousotRegression;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
#pragma warning disable 0649
namespace Full
{
public class WarningScores
{
public string f;
[ClousotRegressionTest]
#if MEDIUM || MEDIUMLOW || LOW
// masked
#endif
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly accessing a field on a null reference 'w'",PrimaryILOffset=1,MethodILOffset=0)] // (score: 0.0135)
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"assert unproven",PrimaryILOffset=12,MethodILOffset=0)] // (score: 0.006)
#endif
public int OtherObject(WarningScores w)
{
Contract.Assert(w.f != null);
return w.f.Length;
}
#if MEDIUM || MEDIUMLOW ||LOW
// masked
#endif
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly calling a method on a null reference 'this.f'",PrimaryILOffset=6,MethodILOffset=0)] // (score: 0.00416666666666667)
#endif
[ClousotRegressionTest]
public int MissingObjectInvariant()
{
return f.Length;
}
[ClousotRegressionTest]
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly calling a method on a null reference 's'",PrimaryILOffset=1,MethodILOffset=0)] // (score: 0.015)
#endif
#if MEDIUM || MEDIUMLOW ||LOW
// masked
#endif
public int MissingPrecondition(string s)
{
return s.Length;
}
[ClousotRegressionTest]
#if LOW|| MEDIUMLOW
// nothing to show
#endif
// We want to shot it with mediumlow, as we have all the code, so we should fix it
#if FULL || MEDIUM
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"requires unproven: x >= 0. Are you making some assumption on MissingPrecondition that the static checker is unaware of? ",PrimaryILOffset=7,MethodILOffset=22)]
#endif
public void MissingPostconditionInAPrecondition(string s)
{
Contract.Requires(s != null);
var l = MissingPrecondition(s);
RequiresNonNegative(l);
}
[ClousotRegressionTest]
#if LOW|| MEDIUMLOW
// nothing to show
#endif
#if FULL || MEDIUM
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"assert unproven. Are you making some assumption on MissingPrecondition that the static checker is unaware of? ",PrimaryILOffset=27,MethodILOffset=0)] // (score: 60
#endif
public void MissingPostconditionInAnAssert(string s)
{
Contract.Requires(s != null);
var l = MissingPrecondition(s);
Contract.Assert(l >= 0);
}
[ClousotRegressionTest]
#if LOW || MEDIUM || MEDIUMLOW
#endif
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly calling a method on a null reference 'collection'",PrimaryILOffset=3,MethodILOffset=0)] // (score: 0.015)
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly calling a method on a null reference 'x'. Do you expect that System.Collections.Generic.IEnumerator`1<System.String>.get_Current returns non-null? ",PrimaryILOffset=20,MethodILOffset=0)] // (score: 25)
#endif
public void IterNotNull(IEnumerable<string> collection)
{
int l = 0;
foreach (var x in collection)
{
l += x.Length;
}
}
[ClousotRegressionTest]
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly calling a method on a null reference 's'",PrimaryILOffset=32,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly calling a method on a null reference 't'. The static checker determined that the condition 't != null' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add a precondition to document it: Contract.Requires(t != null);",PrimaryILOffset=21,MethodILOffset=0)]
#endif
public void Func(string s, List<char> t)
{
// We do not infer a precondition for t, but we detect it is unmodified from the entry
foreach (var ch in s)
{
if(ch == 'a')
t.Add(ch);
}
}
[ClousotRegressionTest]
public void RequiresNonNegative(int x)
{
Contract.Requires(x >= 0);
}
}
static public class AlwaysShow
{
static public void NonNull(string s)
{
Contract.Requires(s != null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.False,Message="requires is false: s != null",PrimaryILOffset=7,MethodILOffset=1)]
#if CLOUSOT2
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Invoking method 'CallWithNull' will always lead to an error. If this is wanted, consider adding Contract.Requires(false) to document it",PrimaryILOffset=0,MethodILOffset=0)]
#else
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Invoking method 'CallWithNull' will always lead to an error. If this is wanted, consider adding Contract.Requires(false) to document it",PrimaryILOffset=1,MethodILOffset=0)]
#endif
static public void CallWithNull()
{
NonNull(null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.False,Message="Calling a method on a null reference 'o'. Maybe the guard o == null is too weak? ",PrimaryILOffset=4,MethodILOffset=0)]
static public int WrongCheck(object o)
{
if (o == null)
{
return o.GetHashCode();
}
return 1;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.False,Message="Cannot create an array of negative length. Maybe the guard z < 0 is too weak? ",PrimaryILOffset=5,MethodILOffset=0)]
static public int[] WrongCheckArrayInit(int z)
{
if (z < 0)
{
return new int[z];
}
return null;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"assert unproven. The error may be caused by the initialization of s. ",PrimaryILOffset=26,MethodILOffset=0)]
static public void ItIsAWarning_Assert()
{
bool b = NonDet();
string s;
if(b)
s = null;
else
s = "ciao";
Contract.Assert(s != null); // Should never be masked
}
[ContractVerification(false)] // Just a dummy call
static private bool NonDet()
{
return false;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly calling a method on a null reference 's'. The error may be caused by the initialization of s. ",PrimaryILOffset=14,MethodILOffset=0)]
static public int ItIsAWarning_Deref(bool b)
{
string s;
if(b)
s = null;
else
s = "ciao";
return s.Length; // Should never be masked
}
}
public class MaskBecauseOfAssumptions
{
int foo;
int[] z;
[ClousotRegressionTest]
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be below the lower bound",PrimaryILOffset=12,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound",PrimaryILOffset=12,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'this.z'",PrimaryILOffset=12,MethodILOffset=0)]
#endif
public int ExpectFoo()
{
return this.z[foo];
}
}
public class MaskBecauseOutParam
{
public Dictionary<string, string> myDict;
[ClousotRegressionTest]
#if MEDIUMLOW || LOW
#endif
#if MEDIUM || FULL
#endif
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"ensures unproven: Contract.Result<string>() != null. The variable 'res' flows from an out parameter. Consider adding a postconditon to the callee or an assumption after the call to document it",PrimaryILOffset=23,MethodILOffset=45)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly calling a method on a null reference 'this.myDict'",PrimaryILOffset=37,MethodILOffset=0)]
#endif
public string Foo(string s)
{
Contract.Requires(s != null);
Contract.Ensures(Contract.Result<string>() != null);
string res;
if (myDict.TryGetValue(s, out res))
{
return res;
}
res = "ciao";
return res;
}
}
}
namespace ReadonlyAccessMasking
{
public class ReadOnly<T>
where T : class
{
private readonly T p;
public ReadOnly(T p)
{
if (p == null)
{
throw new ArgumentNullException("p");
}
this.p = p;
}
[ClousotRegressionTest]
#if FULL
// Masked because readonly
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"assert unproven",PrimaryILOffset=17,MethodILOffset=0)]
#endif
public void SomeMethod()
{
Contract.Assert(this.p != null);
}
[ClousotRegressionTest]
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly accessing a field on a null reference 'other'",PrimaryILOffset=1,MethodILOffset=0)]
// Masked because readonly
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"assert unproven",PrimaryILOffset=17,MethodILOffset=0)]
#endif
public void AssertOther(ReadOnly<T> other)
{
Contract.Assert(other.p != null);
}
[ClousotRegressionTest]
public string MyToString()
{
return this.p.ToString();
}
}
}
namespace ForAllFiltering
{
public class Iterator
{
[ClousotRegressionTest]
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"ensures unproven: Contract.ForAll(Contract.Result<IEnumerable<T>>(), x => x != null)",PrimaryILOffset=22,MethodILOffset=28)]
#endif
public IEnumerable<T> GetIterator<T>(List<T> myList)
{
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<T>>(), x => x != null));
return myList;
}
}
}
namespace UseCodeFixes
{
public class Ranking
{
[ClousotRegressionTest]
// We promote this warning to be shown with low, as the code fix determines the guard should be less permessive
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound. Maybe the guard i <= args.Length is too weak? ",PrimaryILOffset=7,MethodILOffset=0)]
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'args'",PrimaryILOffset=14,MethodILOffset=0)]
#endif
static void Foo(string[] args)
{
for (var i = 0; i <= args.Length; i++)
{
args[i] = null;
}
}
}
static public class OffByByOne
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound",PrimaryILOffset=59,MethodILOffset=0)]
#if MEDIUM || MEDIUMLOW || LOW
// nothing
#endif
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'list'",PrimaryILOffset=16,MethodILOffset=0)]
#endif
static public string[] Add(string[] list, ref int count, string value)
{
Contract.Requires(count >= 0);
Contract.Requires(count <= list.Length);
if(count == list.Length)
{
var tmp = new string[count *2];
list = tmp;
}
list[count++] = value;
return list;
}
}
}
namespace RoslynCSharpCompiler
{
public class SyntaxTree { }
public class SyntaxNode
{
internal readonly SyntaxNode Green;
internal virtual SyntaxNode ToRed(SyntaxNode parent, int position)
{
throw new NotImplementedException();
}
private SyntaxTree syntaxTree;
[ClousotRegressionTest]
#if LOW || MEDIUMLOW
// nothing
#endif
#if FULL || MEDIUM
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly accessing a field on a null reference 'clone'. Are you making some assumption on ToRed that the static checker is unaware of? ",PrimaryILOffset=31,MethodILOffset=0)]
#endif
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly accessing a field on a null reference 'node'",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly calling a method on a null reference '((RoslynCSharpCompiler.SyntaxNode)node).Green'",PrimaryILOffset=13,MethodILOffset=0)]
#endif
internal static T CloneNodeAsRoot<T>(T node, SyntaxTree syntaxTree)
where T : SyntaxNode
{
T clone = (T)node.Green.ToRed(null, 0);
clone.syntaxTree = syntaxTree;
return clone;
}
}
abstract public class Proxy
{
public List<object> Sizes;
}
public class SmallReproForAnonymousCall
{
[ClousotRegressionTest]
#if LOW || MEDIUMLOW || MEDIUM
// nothing to show
#endif
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly calling a method on a null reference. Do you expect that System.Collections.Generic.List`1<System.Object>.get_Item(System.Int32) returns non-null? ",PrimaryILOffset=30,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly accessing a field on a null reference 'rankSpec'",PrimaryILOffset=1,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly calling a method on a null reference 'rankSpec.Sizes'",PrimaryILOffset=6,MethodILOffset=0)]
#endif
private static int GetNumberOfNonOmittedArraySizes(Proxy rankSpec)
{
int count = rankSpec.Sizes.Count;
int result = 0;
for (int i = 0; i < count; i++)
{
if (rankSpec.Sizes[i].ToString() != "")
{
result++;
}
}
return result;
}
}
public abstract class SmallReproForLowerBoundAccess
{
protected SyntaxNode CurrentNode;
int tokenOffset;
protected SyntaxNode[] blendedTokens;
[ClousotRegressionTest]
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound",PrimaryILOffset=58,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'this.blendedTokens'",PrimaryILOffset=58,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be below the lower bound",PrimaryILOffset=58,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly accessing a field on a null reference 'this.CurrentNode'",PrimaryILOffset=6,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'this.blendedTokens'",PrimaryILOffset=24,MethodILOffset=0)]
#endif
protected void EatNode()
{
SyntaxNode result = this.CurrentNode.Green;
if (this.tokenOffset >= this.blendedTokens.Length)
{
this.AddTokenSlot();
}
this.blendedTokens[this.tokenOffset++] = null;
}
abstract public void AddTokenSlot();
}
public class SmallReproForCastFromList
{
[ClousotRegressionTest]
#if LOW || MEDIUM || MEDIUMLOW
#endif
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly calling a method on a null reference 'asStr'. Are you making some assumption on get_Item that the static checker is unaware of? ",PrimaryILOffset=26,MethodILOffset=0)]
#endif
public bool Repro(List<object> objects)
{
if (objects != null && objects.Count > 0)
{
string asStr = (string) objects[0];
return asStr.GetHashCode() % 34 == 2;
}
return false;
}
}
public class SyntaxTokenList
{
private int count;
private int[] nodes;
public SyntaxTokenList() { }
public SyntaxTokenList(int count, int nodes, int n1, int n2, int n3 )
{
this.count = count;
this.nodes = new int[nodes];
}
public SyntaxTokenList(int count)
: this(count, 1, 0, 0, 0)
{
}
public SyntaxTokenList(int count, int nodes)
: this(count, nodes, 0, 0, 0)
{
}
public SyntaxTokenList(int count, int nodes, int n1)
: this(count, nodes, n1, 0, 0)
{
}
public SyntaxTokenList(int count, int nodes, int n1, int n2)
: this(count, nodes, n1, n2, 0)
{
}
// We want to mask the array accesses via fields but keep them in the medium warning
[ClousotRegressionTest]
#if MEDIUM || FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound. Did you mean 0 instead of 1? ",PrimaryILOffset=97,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound. Did you mean 1 instead of 2? ",PrimaryILOffset=105,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound. Did you mean 0 instead of 1? ",PrimaryILOffset=73,MethodILOffset=0)]
#endif
#if FULL
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound. The static checker determined that the condition '0 < this.nodes.Length' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add an explicit assumption at entry to document it: Contract.Assume(0 < this.nodes.Length);",PrimaryILOffset=89,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound. The static checker determined that the condition '0 < this.nodes.Length' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add an explicit assumption at entry to document it: Contract.Assume(0 < this.nodes.Length);",PrimaryILOffset=65,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Array access might be above the upper bound. The static checker determined that the condition '0 < this.nodes.Length' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add an explicit assumption at entry to document it: Contract.Assume(0 < this.nodes.Length);",PrimaryILOffset=51,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'this.nodes'. The static checker determined that the condition 'this.nodes != null' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add an explicit assumption at entry to document it: Contract.Assume(this.nodes != null);",PrimaryILOffset=89,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'this.nodes'. The static checker determined that the condition 'this.nodes != null' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add an explicit assumption at entry to document it: Contract.Assume(this.nodes != null);",PrimaryILOffset=65,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'this.nodes'. The static checker determined that the condition 'this.nodes != null' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add an explicit assumption at entry to document it: Contract.Assume(this.nodes != null);",PrimaryILOffset=51,MethodILOffset=0)]
#endif
public SyntaxTokenList ToList()
{
if (this.count <= 0)
{
return new SyntaxTokenList();
}
switch (this.count)
{
case 1:
return new SyntaxTokenList(this.nodes[0]);
case 2:
return new SyntaxTokenList(this.nodes[0], this.nodes[1], 0, 0);
case 3:
return new SyntaxTokenList(this.nodes[0], this.nodes[1], this.nodes[2], 0, 0);
}
return null;
}
}
}
namespace UseWitnesses
{
public class TestMayReturnNull
{
[ClousotRegressionTest]
public int[] CanReturnNullOrNotNull(int b)
{
if (b > 100)
return new int[b];
else
return null;
}
[ClousotRegressionTest]
public int[] ReturnSomethingThatCanReturnNullOrNotNull(int b)
{
if (b > 200)
return new int[b];
else
return CanReturnNullOrNotNull(b);
}
[ClousotRegressionTest]
// We always want to see this warning
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="assert unproven. Are you making some assumption on CanReturnNullOrNotNull that the static checker is unaware of? ",PrimaryILOffset=15,MethodILOffset=0)]
public void TestThrowNullPointer()
{
var res = CanReturnNullOrNotNull(0);
// here res == null
Contract.Assert(res != null); // should be false;
}
[ClousotRegressionTest]
#if LOW
// Nothing
#else
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possible use of a null array 'res'. Are you making some assumption on ReturnSomethingThatCanReturnNullOrNotNull that the static checker is unaware of? ",PrimaryILOffset=30,MethodILOffset=0)]
#endif
public int TestThrowNullPointer(int b)
{
var res = ReturnSomethingThatCanReturnNullOrNotNull(b);
int i = 0;
foreach (var x in res)
{
i++;
}
return i;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableListBuilderTest : ImmutableListTestBase
{
[Fact]
public void CreateBuilder()
{
ImmutableList<string>.Builder builder = ImmutableList.CreateBuilder<string>();
Assert.NotNull(builder);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableList<int>.Empty.ToBuilder();
builder.Add(3);
builder.Add(5);
builder.Add(5);
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var list = builder.ToImmutable();
Assert.Equal(builder.Count, list.Count);
builder.Add(8);
Assert.Equal(4, builder.Count);
Assert.Equal(3, list.Count);
Assert.True(builder.Contains(8));
Assert.False(list.Contains(8));
}
[Fact]
public void BuilderFromList()
{
var list = ImmutableList<int>.Empty.Add(1);
var builder = list.ToBuilder();
Assert.True(builder.Contains(1));
builder.Add(3);
builder.Add(5);
builder.Add(5);
Assert.Equal(4, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var list2 = builder.ToImmutable();
Assert.Equal(builder.Count, list2.Count);
Assert.True(list2.Contains(1));
builder.Add(8);
Assert.Equal(5, builder.Count);
Assert.Equal(4, list2.Count);
Assert.True(builder.Contains(8));
Assert.False(list.Contains(8));
Assert.False(list2.Contains(8));
}
[Fact]
public void SeveralChanges()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
var immutable1 = mutable.ToImmutable();
Assert.Same(immutable1, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences.");
mutable.Add(1);
var immutable2 = mutable.ToImmutable();
Assert.NotSame(immutable1, immutable2); //, "Mutating the collection did not reset the Immutable property.");
Assert.Same(immutable2, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences.");
Assert.Equal(1, immutable2.Count);
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 10)).ToBuilder();
Assert.Equal(Enumerable.Range(1, 10), builder);
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
Assert.Equal(Enumerable.Range(1, 11), builder);
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
Assert.Equal(Enumerable.Range(1, 11), builder);
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableList<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void Insert()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.Insert(0, 1);
mutable.Insert(0, 0);
mutable.Insert(2, 3);
Assert.Equal(new[] { 0, 1, 3 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.Insert(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.Insert(4, 0));
}
[Fact]
public void InsertRange()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.InsertRange(0, new[] { 1, 4, 5 });
Assert.Equal(new[] { 1, 4, 5 }, mutable);
mutable.InsertRange(1, new[] { 2, 3 });
Assert.Equal(new[] { 1, 2, 3, 4, 5 }, mutable);
mutable.InsertRange(5, new[] { 6 });
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable);
mutable.InsertRange(5, new int[0]);
Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(-1, new int[0]));
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(mutable.Count + 1, new int[0]));
}
[Fact]
public void AddRange()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.AddRange(new[] { 1, 4, 5 });
Assert.Equal(new[] { 1, 4, 5 }, mutable);
mutable.AddRange(new[] { 2, 3 });
Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable);
mutable.AddRange(new int[0]);
Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable);
Assert.Throws<ArgumentNullException>(() => mutable.AddRange(null));
}
[Fact]
public void Remove()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
Assert.False(mutable.Remove(5));
mutable.Add(1);
mutable.Add(2);
mutable.Add(3);
Assert.True(mutable.Remove(2));
Assert.Equal(new[] { 1, 3 }, mutable);
Assert.True(mutable.Remove(1));
Assert.Equal(new[] { 3 }, mutable);
Assert.True(mutable.Remove(3));
Assert.Equal(new int[0], mutable);
Assert.False(mutable.Remove(5));
}
[Fact]
public void RemoveAt()
{
var mutable = ImmutableList<int>.Empty.ToBuilder();
mutable.Add(1);
mutable.Add(2);
mutable.Add(3);
mutable.RemoveAt(2);
Assert.Equal(new[] { 1, 2 }, mutable);
mutable.RemoveAt(0);
Assert.Equal(new[] { 2 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(1));
mutable.RemoveAt(0);
Assert.Equal(new int[0], mutable);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(1));
}
[Fact]
public void Reverse()
{
var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
mutable.Reverse();
Assert.Equal(Enumerable.Range(1, 3).Reverse(), mutable);
}
[Fact]
public void Clear()
{
var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
mutable.Clear();
Assert.Equal(0, mutable.Count);
// Do it again for good measure. :)
mutable.Clear();
Assert.Equal(0, mutable.Count);
}
[Fact]
public void IsReadOnly()
{
ICollection<int> builder = ImmutableList.Create<int>().ToBuilder();
Assert.False(builder.IsReadOnly);
}
[Fact]
public void Indexer()
{
var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Equal(2, mutable[1]);
mutable[1] = 5;
Assert.Equal(5, mutable[1]);
mutable[0] = -2;
mutable[2] = -3;
Assert.Equal(new[] { -2, 5, -3 }, mutable);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable[3] = 4);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable[-1] = 4);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable[3]);
Assert.Throws<ArgumentOutOfRangeException>(() => mutable[-1]);
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableList.CreateRange(seq).ToBuilder(),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableList.CreateRange(seq).ToBuilder(),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void GetEnumeratorExplicit()
{
ICollection<int> builder = ImmutableList.Create<int>().ToBuilder();
var enumerator = builder.GetEnumerator();
Assert.NotNull(enumerator);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = ImmutableList.Create<int>().ToBuilder();
Assert.False(collection.IsSynchronized);
}
[Fact]
public void IListMembers()
{
IList list = ImmutableList.Create<int>().ToBuilder();
Assert.False(list.IsReadOnly);
Assert.False(list.IsFixedSize);
Assert.Equal(0, list.Add(5));
Assert.Equal(1, list.Add(8));
Assert.True(list.Contains(5));
Assert.False(list.Contains(7));
list.Insert(1, 6);
Assert.Equal(6, list[1]);
list.Remove(5);
list[0] = 9;
Assert.Equal(new[] { 9, 8 }, list.Cast<int>().ToArray());
list.Clear();
Assert.Equal(0, list.Count);
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableList<T>.Empty.AddRange(contents).ToBuilder();
}
protected override void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test)
{
var builder = list.ToBuilder();
var bcl = list.ToList();
int expected = bcl.RemoveAll(test);
var actual = builder.RemoveAll(test);
Assert.Equal(expected, actual);
Assert.Equal<T>(bcl, builder.ToList());
}
protected override void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count)
{
var expected = list.ToList();
expected.Reverse(index, count);
var builder = list.ToBuilder();
builder.Reverse(index, count);
Assert.Equal<T>(expected, builder.ToList());
}
internal override IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list)
{
return list.ToBuilder();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list)
{
var builder = list.ToBuilder();
builder.Sort();
return builder.ToImmutable().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison)
{
var builder = list.ToBuilder();
builder.Sort(comparison);
return builder.ToImmutable().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer)
{
var builder = list.ToBuilder();
builder.Sort(comparer);
return builder.ToImmutable().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer)
{
var builder = list.ToBuilder();
builder.Sort(index, count, comparer);
return builder.ToImmutable().ToList();
}
}
}
| |
/*
* 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.IO;
using System.Linq;
using System.Threading;
using QuantConnect.Api;
using QuantConnect.Util;
using QuantConnect.Logging;
using QuantConnect.Interfaces;
using System.Collections.Generic;
using QuantConnect.Configuration;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// An instance of the <see cref="IDataProvider"/> that will download and update data files as needed via QC's Api.
/// </summary>
public class ApiDataProvider : BaseDownloaderDataProvider
{
private readonly int _uid = Config.GetInt("job-user-id", 0);
private readonly string _token = Config.Get("api-access-token", "1");
private readonly string _organizationId = Config.Get("job-organization-id");
private readonly string _dataPath = Config.Get("data-folder", "../../../Data/");
private decimal _purchaseLimit = Config.GetValue("data-purchase-limit", decimal.MaxValue); //QCC
private readonly HashSet<SecurityType> _unsupportedSecurityType;
private readonly DataPricesList _dataPrices;
private readonly Api.Api _api;
private readonly bool _subscribedToIndiaEquityMapAndFactorFiles;
private readonly bool _subscribedToUsaEquityMapAndFactorFiles;
private readonly bool _subscribedToFutureMapAndFactorFiles;
private volatile bool _invalidSecurityTypeLog;
/// <summary>
/// Initialize a new instance of the <see cref="ApiDataProvider"/>
/// </summary>
public ApiDataProvider()
{
_api = new Api.Api();
_unsupportedSecurityType = new HashSet<SecurityType> { SecurityType.Future, SecurityType.FutureOption, SecurityType.Index, SecurityType.IndexOption };
_api.Initialize(_uid, _token, _dataPath);
// If we have no value for organization get account preferred
if (string.IsNullOrEmpty(_organizationId))
{
var account = _api.ReadAccount();
_organizationId = account?.OrganizationId;
Log.Trace($"ApiDataProvider(): Will use organization Id '{_organizationId}'.");
}
// Read in data prices and organization details
_dataPrices = _api.ReadDataPrices(_organizationId);
var organization = _api.ReadOrganization(_organizationId);
foreach (var productItem in organization.Products.Where(x => x.Type == ProductType.Data).SelectMany(product => product.Items))
{
if (productItem.Id == 37)
{
// Determine if the user is subscribed to Equity map and factor files (Data product Id 37)
_subscribedToUsaEquityMapAndFactorFiles = true;
}
else if (productItem.Id == 137)
{
// Determine if the user is subscribed to Future map and factor files (Data product Id 137)
_subscribedToFutureMapAndFactorFiles = true;
}
else if (productItem.Id == 172)
{
// Determine if the user is subscribed to India map and factor files (Data product Id 172)
_subscribedToIndiaEquityMapAndFactorFiles = true;
}
}
// Verify user has agreed to data provider agreements
if (organization.DataAgreement.Signed)
{
//Log Agreement Highlights
Log.Trace("ApiDataProvider(): Data Terms of Use has been signed. \r\n" +
$" Find full agreement at: {_dataPrices.AgreementUrl} \r\n" +
"==========================================================================\r\n" +
$"CLI API Access Agreement: On {organization.DataAgreement.SignedTime:d} You Agreed:\r\n" +
" - Display or distribution of data obtained through CLI API Access is not permitted. \r\n" +
" - Data and Third Party Data obtained via CLI API Access can only be used for individual or internal employee's use.\r\n" +
" - Data is provided in LEAN format can not be manipulated for transmission or use in other applications. \r\n" +
" - QuantConnect is not liable for the quality of data received and is not responsible for trading losses. \r\n" +
"==========================================================================");
Thread.Sleep(TimeSpan.FromSeconds(3));
}
else
{
// Log URL to go accept terms
throw new InvalidOperationException($"ApiDataProvider(): Must agree to terms at {_dataPrices.AgreementUrl}, before using the ApiDataProvider");
}
// Verify we have the balance to maintain our purchase limit, if not adjust it to meet our balance
var balance = organization.Credit.Balance;
if (balance < _purchaseLimit)
{
if (_purchaseLimit != decimal.MaxValue)
{
Log.Error("ApiDataProvider(): Purchase limit is greater than balance." +
$" Setting purchase limit to balance : {balance}");
}
_purchaseLimit = balance;
}
}
/// <summary>
/// Retrieves data to be used in an algorithm.
/// If file does not exist, an attempt is made to download them from the api
/// </summary>
/// <param name="key">File path representing where the data requested</param>
/// <returns>A <see cref="Stream"/> of the data requested</returns>
public override Stream Fetch(string key)
{
return DownloadOnce(key, s =>
{
// Verify we have enough credit to handle this
var pricePath = Api.Api.FormatPathForDataRequest(key);
var price = _dataPrices.GetPrice(pricePath);
// No price found
if (price == -1)
{
throw new ArgumentException($"ApiDataProvider.Fetch(): No price found for {pricePath}");
}
if (_purchaseLimit < price)
{
throw new ArgumentException($"ApiDataProvider.Fetch(): Cost {price} for {pricePath} data exceeds remaining purchase limit: {_purchaseLimit}");
}
if (DownloadData(key))
{
// Update our purchase limit.
_purchaseLimit -= price;
}
});
}
/// <summary>
/// Main filter to determine if this file needs to be downloaded
/// </summary>
/// <param name="filePath">File we are looking at</param>
/// <returns>True if should download</returns>
protected override bool NeedToDownload(string filePath)
{
// Ignore null and fine fundamental data requests
if (filePath == null || filePath.Contains("fine", StringComparison.InvariantCultureIgnoreCase) && filePath.Contains("fundamental", StringComparison.InvariantCultureIgnoreCase))
{
return false;
}
// Some security types can't be downloaded, lets attempt to extract that information
if (LeanData.TryParseSecurityType(filePath, out SecurityType securityType, out var market) && _unsupportedSecurityType.Contains(securityType))
{
// we do support future auxiliary data (map and factor files)
if (securityType != SecurityType.Future || !IsAuxiliaryData(filePath))
{
if (!_invalidSecurityTypeLog)
{
// let's log this once. Will still use any existing data on disk
_invalidSecurityTypeLog = true;
Log.Error($"ApiDataProvider(): does not support security types: {string.Join(", ", _unsupportedSecurityType)}");
}
return false;
}
}
// Only download if it doesn't exist or is out of date.
// Files are only "out of date" for non date based files (hour, daily, margins, etc.) because this data is stored all in one file
var shouldDownload = !File.Exists(filePath) || filePath.IsOutOfDate();
if (shouldDownload)
{
if (securityType == SecurityType.Future)
{
if (!_subscribedToFutureMapAndFactorFiles)
{
throw new ArgumentException("ApiDataProvider(): Must be subscribed to map and factor files to use the ApiDataProvider " +
"to download Future auxiliary data from QuantConnect. " +
"Please visit https://www.quantconnect.com/datasets/quantconnect-us-futures-security-master for details.");
}
}
// Final check; If we want to download and the request requires equity data we need to be sure they are subscribed to map and factor files
else if (!_subscribedToUsaEquityMapAndFactorFiles && market.Equals(Market.USA, StringComparison.InvariantCultureIgnoreCase)
&& (securityType == SecurityType.Equity || securityType == SecurityType.Option || IsAuxiliaryData(filePath)))
{
throw new ArgumentException("ApiDataProvider(): Must be subscribed to map and factor files to use the ApiDataProvider " +
"to download Equity data from QuantConnect. " +
"Please visit https://www.quantconnect.com/datasets/quantconnect-security-master for details.");
}
else if (!_subscribedToIndiaEquityMapAndFactorFiles && market.Equals(Market.India, StringComparison.InvariantCultureIgnoreCase)
&& (securityType == SecurityType.Equity || securityType == SecurityType.Option || IsAuxiliaryData(filePath)))
{
throw new ArgumentException("ApiDataProvider(): Must be subscribed to map and factor files to use the ApiDataProvider " +
"to download India data from QuantConnect. " +
"Please visit https://www.quantconnect.com/datasets/truedata-india-equity-security-master for details.");
}
}
return shouldDownload;
}
/// <summary>
/// Attempt to download data using the Api for and return a FileStream of that data.
/// </summary>
/// <param name="filePath">The path to store the file</param>
/// <returns>A FileStream of the data</returns>
protected virtual bool DownloadData(string filePath)
{
if (Log.DebuggingEnabled)
{
Log.Debug($"ApiDataProvider.Fetch(): Attempting to get data from QuantConnect.com's data library for {filePath}.");
}
if (_api.DownloadData(filePath, _organizationId))
{
Log.Trace($"ApiDataProvider.Fetch(): Successfully retrieved data for {filePath}.");
return true;
}
// Failed to download; _api.DownloadData() will post error
return false;
}
/// <summary>
/// Helper method to determine if this filepath is auxiliary data
/// </summary>
/// <param name="filepath">The target file path</param>
/// <returns>True if this file is of auxiliary data</returns>
private static bool IsAuxiliaryData(string filepath)
{
return filepath.Contains("map_files", StringComparison.InvariantCulture)
|| filepath.Contains("factor_files", StringComparison.InvariantCulture)
|| filepath.Contains("fundamental", StringComparison.InvariantCulture)
|| filepath.Contains("shortable", StringComparison.InvariantCulture);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class ConstructorInitializerSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public ConstructorInitializerSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new ConstructorInitializerSignatureHelpProvider();
}
#region "Regular tests"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParameters()
{
var markup = @"
class BaseClass
{
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base($$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base($$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", "Summary for BaseClass", null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class BaseClass
{
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base($$2, 3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base($$2, 3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param a", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base(2, $$3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base(2, $$3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestThisInvocation()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() [|: this(2, $$3|]) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParen()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() [|: this(2, $$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Current Parameter Name"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(b: 2, a: $$
}";
await VerifyCurrentParameterNameAsync(markup, "a");
}
#endregion
#region "Trigger tests"
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerParens()
{
var markup = @"
class Foo
{
public Foo(int a) { }
public Foo() : this($$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0),
new SignatureHelpTestItem("Foo(int a)", string.Empty, string.Empty, currentParameterIndex: 0),
};
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(2,$$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(2, $$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAlways()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateNever()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAdvanced()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateMixed()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public BaseClass(int x)
{ }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public BaseClass(int x, int y)
{ }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret
{
public Secret(int secret)
{
}
}
#endif
class SuperSecret : Secret
{
public SuperSecret(int secret) : base($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret
{
public Secret(int secret)
{
}
}
#endif
#if BAR
class SuperSecret : Secret
{
public SuperSecret(int secret) : base($$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WorkItem(1067933)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// foo($$";
await TestAsync(markup);
}
[WorkItem(1082601)]
[WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithBadParameterList()
{
var markup = @"
class BaseClass
{
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base{$$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems);
}
}
}
| |
// 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.
/// <license>
/// This is a port of the SciMark2a Java Benchmark to C# by
/// Chris Re (cmr28@cornell.edu) and Werner Vogels (vogels@cs.cornell.edu)
///
/// For details on the original authors see http://math.nist.gov/scimark2
///
/// This software is likely to burn your processor, bitflip your memory chips
/// anihilate your screen and corrupt all your disks, so you it at your
/// own risk.
/// </license>
using Microsoft.Xunit.Performance;
using System;
[assembly: OptimizeForBenchmarks]
namespace SciMark2
{
public static class kernel
{
[Benchmark]
public static void benchFFT()
{
SciMark2.Random R = new SciMark2.Random(Constants.RANDOM_SEED);
int N = Constants.FFT_SIZE;
long Iterations = 20000;
double[] x = RandomVector(2 * N, R);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
innerFFT(x, Iterations);
}
}
validateFFT(N, x);
}
private static void innerFFT(double[] x, long Iterations)
{
for (int i = 0; i < Iterations; i++)
{
FFT.transform(x); // forward transform
FFT.inverse(x); // backward transform
}
}
private static void validateFFT(int N, double[] x)
{
const double EPS = 1.0e-10;
if (FFT.test(x) / N > EPS)
{
throw new Exception("FFT failed to validate");
}
}
public static double measureFFT(int N, double mintime, Random R)
{
// initialize FFT data as complex (N real/img pairs)
double[] x = RandomVector(2 * N, R);
long cycles = 1;
Stopwatch Q = new Stopwatch();
while (true)
{
Q.start();
innerFFT(x, cycles);
Q.stop();
if (Q.read() >= mintime)
break;
cycles *= 2;
}
validateFFT(N, x);
// approx Mflops
return FFT.num_flops(N) * cycles / Q.read() * 1.0e-6;
}
[Benchmark]
public static void benchSOR()
{
int N = Constants.SOR_SIZE;
SciMark2.Random R = new SciMark2.Random(Constants.RANDOM_SEED);
int Iterations = 20000;
double[][] G = RandomMatrix(N, N, R);
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SOR.execute(1.25, G, Iterations);
}
}
}
public static double measureSOR(int N, double min_time, Random R)
{
double[][] G = RandomMatrix(N, N, R);
Stopwatch Q = new Stopwatch();
int cycles = 1;
while (true)
{
Q.start();
SOR.execute(1.25, G, cycles);
Q.stop();
if (Q.read() >= min_time)
break;
cycles *= 2;
}
// approx Mflops
return SOR.num_flops(N, N, cycles) / Q.read() * 1.0e-6;
}
[Benchmark]
public static void benchMonteCarlo()
{
SciMark2.Random R = new SciMark2.Random(Constants.RANDOM_SEED);
int Iterations = 40000000;
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
MonteCarlo.integrate(Iterations);
}
}
}
public static double measureMonteCarlo(double min_time, Random R)
{
Stopwatch Q = new Stopwatch();
int cycles = 1;
while (true)
{
Q.start();
MonteCarlo.integrate(cycles);
Q.stop();
if (Q.read() >= min_time)
break;
cycles *= 2;
}
// approx Mflops
return MonteCarlo.num_flops(cycles) / Q.read() * 1.0e-6;
}
[Benchmark]
public static void benchSparseMult()
{
int N = Constants.SPARSE_SIZE_M;
int nz = Constants.SPARSE_SIZE_nz;
int Iterations = 100000;
SciMark2.Random R = new SciMark2.Random(Constants.RANDOM_SEED);
double[] x = RandomVector(N, R);
double[] y = new double[N];
int nr = nz / N; // average number of nonzeros per row
int anz = nr * N; // _actual_ number of nonzeros
double[] val = RandomVector(anz, R);
int[] col = new int[anz];
int[] row = new int[N + 1];
row[0] = 0;
for (int r = 0; r < N; r++)
{
// initialize elements for row r
int rowr = row[r];
row[r + 1] = rowr + nr;
int step = r / nr;
if (step < 1)
step = 1;
// take at least unit steps
for (int i = 0; i < nr; i++)
col[rowr + i] = i * step;
}
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
SparseCompRow.matmult(y, val, row, col, x, Iterations);
}
}
}
public static double measureSparseMatmult(int N, int nz, double min_time, Random R)
{
// initialize vector multipliers and storage for result
// y = A*y;
double[] x = RandomVector(N, R);
double[] y = new double[N];
// initialize square sparse matrix
//
// for this test, we create a sparse matrix wit M/nz nonzeros
// per row, with spaced-out evenly between the begining of the
// row to the main diagonal. Thus, the resulting pattern looks
// like
// +-----------------+
// +* +
// +*** +
// +* * * +
// +** * * +
// +** * * +
// +* * * * +
// +* * * * +
// +* * * * +
// +-----------------+
//
// (as best reproducible with integer artihmetic)
// Note that the first nr rows will have elements past
// the diagonal.
int nr = nz / N; // average number of nonzeros per row
int anz = nr * N; // _actual_ number of nonzeros
double[] val = RandomVector(anz, R);
int[] col = new int[anz];
int[] row = new int[N + 1];
row[0] = 0;
for (int r = 0; r < N; r++)
{
// initialize elements for row r
int rowr = row[r];
row[r + 1] = rowr + nr;
int step = r / nr;
if (step < 1)
step = 1;
// take at least unit steps
for (int i = 0; i < nr; i++)
col[rowr + i] = i * step;
}
Stopwatch Q = new Stopwatch();
int cycles = 1;
while (true)
{
Q.start();
SparseCompRow.matmult(y, val, row, col, x, cycles);
Q.stop();
if (Q.read() >= min_time)
break;
cycles *= 2;
}
// approx Mflops
return SparseCompRow.num_flops(N, nz, cycles) / Q.read() * 1.0e-6;
}
[Benchmark]
public static void benchmarkLU()
{
int N = Constants.LU_SIZE;
SciMark2.Random R = new SciMark2.Random(Constants.RANDOM_SEED);
int Iterations = 2000;
double[][] A = RandomMatrix(N, N, R);
double[][] lu = new double[N][];
for (int i = 0; i < N; i++)
{
lu[i] = new double[N];
}
int[] pivot = new int[N];
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
for (int i = 0; i < Iterations; i++)
{
CopyMatrix(lu, A);
LU.factor(lu, pivot);
}
}
}
validateLU(N, R, lu, A, pivot);
}
public static void validateLU(int N, SciMark2.Random R, double[][] lu, double[][] A, int[] pivot)
{
// verify that LU is correct
double[] b = RandomVector(N, R);
double[] x = NewVectorCopy(b);
LU.solve(lu, pivot, x);
const double EPS = 1.0e-12;
if (normabs(b, matvec(A, x)) / N > EPS)
{
throw new Exception("LU failed to validate");
}
}
public static double measureLU(int N, double min_time, Random R)
{
// compute approx Mlfops, or O if LU yields large errors
double[][] A = RandomMatrix(N, N, R);
double[][] lu = new double[N][];
for (int i = 0; i < N; i++)
{
lu[i] = new double[N];
}
int[] pivot = new int[N];
Stopwatch Q = new Stopwatch();
int cycles = 1;
while (true)
{
Q.start();
for (int i = 0; i < cycles; i++)
{
CopyMatrix(lu, A);
LU.factor(lu, pivot);
}
Q.stop();
if (Q.read() >= min_time)
break;
cycles *= 2;
}
validateLU(N, R, lu, A, pivot);
return LU.num_flops(N) * cycles / Q.read() * 1.0e-6;
}
private static double[] NewVectorCopy(double[] x)
{
int N = x.Length;
double[] y = new double[N];
for (int i = 0; i < N; i++)
y[i] = x[i];
return y;
}
private static void CopyVector(double[] B, double[] A)
{
int N = A.Length;
for (int i = 0; i < N; i++)
B[i] = A[i];
}
private static double normabs(double[] x, double[] y)
{
int N = x.Length;
double sum = 0.0;
for (int i = 0; i < N; i++)
sum += System.Math.Abs(x[i] - y[i]);
return sum;
}
private static void CopyMatrix(double[][] B, double[][] A)
{
int M = A.Length;
int N = A[0].Length;
int remainder = N & 3; // N mod 4;
for (int i = 0; i < M; i++)
{
double[] Bi = B[i];
double[] Ai = A[i];
for (int j = 0; j < remainder; j++)
Bi[j] = Ai[j];
for (int j = remainder; j < N; j += 4)
{
Bi[j] = Ai[j];
Bi[j + 1] = Ai[j + 1];
Bi[j + 2] = Ai[j + 2];
Bi[j + 3] = Ai[j + 3];
}
}
}
private static double[][] RandomMatrix(int M, int N, Random R)
{
double[][] A = new double[M][];
for (int i = 0; i < M; i++)
{
A[i] = new double[N];
}
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
A[i][j] = R.nextDouble();
return A;
}
private static double[] RandomVector(int N, Random R)
{
double[] A = new double[N];
for (int i = 0; i < N; i++)
A[i] = R.nextDouble();
return A;
}
private static double[] matvec(double[][] A, double[] x)
{
int N = x.Length;
double[] y = new double[N];
matvec(A, x, y);
return y;
}
private static void matvec(double[][] A, double[] x, double[] y)
{
int M = A.Length;
int N = A[0].Length;
for (int i = 0; i < M; i++)
{
double sum = 0.0;
double[] Ai = A[i];
for (int j = 0; j < N; j++)
sum += Ai[j] * x[j];
y[i] = sum;
}
}
}
}
| |
/*
* TempFileCollection.cs - Implementation of the
* System.CodeDom.Compiler.TempFileCollection class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.CodeDom.Compiler
{
#if CONFIG_CODEDOM
using System.IO;
using System.Collections;
using System.Security.Cryptography;
public class TempFileCollection : ICollection, IEnumerable, IDisposable
{
// Internal state.
private String tempDir;
private String basePath;
private bool keepFiles;
private Hashtable files;
// Constructors.
public TempFileCollection() : this(null, false) {}
public TempFileCollection(String tempDir) : this(tempDir, false) {}
public TempFileCollection(String tempDir, bool keepFiles)
{
this.tempDir = tempDir;
this.basePath = null;
this.keepFiles = keepFiles;
this.files = new Hashtable();
}
// Destructor.
~TempFileCollection()
{
Dispose(false);
}
// Get an enumerator for this collection.
public IEnumerator GetEnumerator()
{
return files.Keys.GetEnumerator();
}
// Properties.
public String BasePath
{
get
{
// Bail out early if we already have a base path.
if(basePath != null)
{
return basePath;
}
// Get the temporary directory to be used.
if(tempDir == null || tempDir.Length == 0)
{
tempDir = Path.GetTempPath();
}
// Create a random name in the temporary directory.
RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[] data = new byte [6];
rng.GetBytes(data);
String name = Convert.ToBase64String(data);
name = name.Replace('/', '-');
name = "tmp" + name.Replace('+', '_');
// Construct the full temporary file base name.
basePath = Path.Combine(tempDir, name);
return basePath;
}
}
public int Count
{
get
{
return files.Count;
}
}
public bool KeepFiles
{
get
{
return keepFiles;
}
set
{
keepFiles = value;
}
}
public String TempDir
{
get
{
if(tempDir != null)
{
return tempDir;
}
else
{
return String.Empty;
}
}
}
// Implement the ICollection interface.
int ICollection.Count
{
get
{
return files.Count;
}
}
void ICollection.CopyTo(Array array, int index)
{
files.CopyTo(array, index);
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
Object ICollection.SyncRoot
{
get
{
return null;
}
}
// Implement the IEnumerable interface.
IEnumerator IEnumerable.GetEnumerator()
{
return files.Keys.GetEnumerator();
}
// Implement the IDisposable interface.
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Add an extension to a temporary file.
public String AddExtension(String fileExtension)
{
return AddExtension(fileExtension, keepFiles);
}
public String AddExtension(String fileExtension, bool keepFile)
{
if(fileExtension == null || fileExtension.Length == 0)
{
throw new ArgumentException
(S._("ArgRange_StringNonEmpty"), "fileExtension");
}
String filename = BasePath + "." + fileExtension;
AddFile(filename, keepFile);
return filename;
}
// Add a file to this temporary file collection.
public void AddFile(String fileName, bool keepFile)
{
if(fileName == null || fileName.Length == 0)
{
throw new ArgumentException
(S._("ArgRange_StringNonEmpty"), "fileName");
}
if(files.Contains(fileName))
{
throw new ArgumentException
(S._("Arg_DuplicateTempFilename"), "fileName");
}
files.Add(fileName, keepFile);
}
// Copy the contents of this collection to an array.
public void CopyTo(String[] fileNames, int index)
{
files.Keys.CopyTo(fileNames, index);
}
// Delete the temporary files in this collection.
public void Delete()
{
IDictionaryEnumerator e = files.GetEnumerator();
while(e.MoveNext())
{
if(!((bool)(e.Value)))
{
try
{
File.Delete((String)(e.Key));
}
catch
{
// Ignore exceptions when deleting files.
}
}
}
files.Clear();
}
// Dispose this collection.
protected virtual void Dispose(bool disposing)
{
Delete();
}
}; // class TempFileCollection
#endif // CONFIG_CODEDOM
}; // namespace System.CodeDom.Compiler
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using NLog.Config;
using NLog.Filters;
namespace NLog.UnitTests.Layouts
{
using NLog.LayoutRenderers;
using NLog.LayoutRenderers.Wrappers;
using NLog.Layouts;
using NLog.Targets;
using System;
using Xunit;
using static Config.TargetConfigurationTests;
public class SimpleLayoutParserTests : NLogTestBase
{
[Fact]
public void SimpleTest()
{
SimpleLayout l = "${message}";
Assert.Single(l.Renderers);
Assert.IsType<MessageLayoutRenderer>(l.Renderers[0]);
}
[Fact]
public void UnclosedTest()
{
new SimpleLayout("${message");
}
[Fact]
public void SingleParamTest()
{
SimpleLayout l = "${mdc:item=AAA}";
Assert.Single(l.Renderers);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA", mdc.Item);
}
[Fact]
public void ValueWithColonTest()
{
SimpleLayout l = "${mdc:item=AAA\\:}";
Assert.Single(l.Renderers);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA:", mdc.Item);
}
[Fact]
public void ValueWithBracketTest()
{
SimpleLayout l = "${mdc:item=AAA\\}\\:}";
Assert.Equal("${mdc:item=AAA\\}\\:}", l.Text);
Assert.Single(l.Renderers);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA}:", mdc.Item);
}
[Fact]
public void DefaultValueTest()
{
SimpleLayout l = "${mdc:BBB}";
Assert.Single(l.Renderers);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("BBB", mdc.Item);
}
[Fact]
public void DefaultValueWithBracketTest()
{
SimpleLayout l = "${mdc:AAA\\}\\:}";
Assert.Equal("${mdc:AAA\\}\\:}", l.Text);
Assert.Single(l.Renderers);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("AAA}:", mdc.Item);
}
[Fact]
public void DefaultValueWithOtherParametersTest()
{
SimpleLayout l = "${exception:message,type:separator=x}";
Assert.Single(l.Renderers);
ExceptionLayoutRenderer elr = l.Renderers[0] as ExceptionLayoutRenderer;
Assert.NotNull(elr);
Assert.Equal("message,type", elr.Format);
Assert.Equal("x", elr.Separator);
}
[Fact]
public void EmptyValueTest()
{
SimpleLayout l = "${mdc:item=}";
Assert.Single(l.Renderers);
MdcLayoutRenderer mdc = l.Renderers[0] as MdcLayoutRenderer;
Assert.NotNull(mdc);
Assert.Equal("", mdc.Item);
}
[Fact]
public void NestedLayoutTest()
{
SimpleLayout l = "${rot13:inner=${ndc:topFrames=3:separator=x}}";
Assert.Single(l.Renderers);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Single(nestedLayout.Renderers);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.NotNull(ndcLayoutRenderer);
Assert.Equal(3, ndcLayoutRenderer.TopFrames);
Assert.Equal("x", ndcLayoutRenderer.Separator);
}
[Fact]
public void DoubleNestedLayoutTest()
{
SimpleLayout l = "${rot13:inner=${rot13:inner=${ndc:topFrames=3:separator=x}}}";
Assert.Single(l.Renderers);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout0 = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout0);
Assert.Equal("${rot13:inner=${ndc:topFrames=3:separator=x}}", nestedLayout0.Text);
var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
var nestedLayout = innerRot13.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Single(nestedLayout.Renderers);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.NotNull(ndcLayoutRenderer);
Assert.Equal(3, ndcLayoutRenderer.TopFrames);
Assert.Equal("x", ndcLayoutRenderer.Separator);
}
[Fact]
public void DoubleNestedLayoutWithDefaultLayoutParametersTest()
{
SimpleLayout l = "${rot13:${rot13:${ndc:topFrames=3:separator=x}}}";
Assert.Single(l.Renderers);
var lr = l.Renderers[0] as Rot13LayoutRendererWrapper;
Assert.NotNull(lr);
var nestedLayout0 = lr.Inner as SimpleLayout;
Assert.NotNull(nestedLayout0);
Assert.Equal("${rot13:${ndc:topFrames=3:separator=x}}", nestedLayout0.Text);
var innerRot13 = nestedLayout0.Renderers[0] as Rot13LayoutRendererWrapper;
var nestedLayout = innerRot13.Inner as SimpleLayout;
Assert.NotNull(nestedLayout);
Assert.Equal("${ndc:topFrames=3:separator=x}", nestedLayout.Text);
Assert.Single(nestedLayout.Renderers);
var ndcLayoutRenderer = nestedLayout.Renderers[0] as NdcLayoutRenderer;
Assert.NotNull(ndcLayoutRenderer);
Assert.Equal(3, ndcLayoutRenderer.TopFrames);
Assert.Equal("x", ndcLayoutRenderer.Separator);
}
[Fact]
public void AmbientPropertyTest()
{
SimpleLayout l = "${message:padding=10}";
Assert.Single(l.Renderers);
var pad = l.Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void MissingLayoutRendererTest()
{
LogManager.ThrowConfigExceptions = true;
Assert.Throws<NLogConfigurationException>(() =>
{
SimpleLayout l = "${rot13:${foobar}}";
});
}
[Fact]
public void DoubleAmbientPropertyTest()
{
SimpleLayout l = "${message:uppercase=true:padding=10}";
Assert.Single(l.Renderers);
var upperCase = l.Renderers[0] as UppercaseLayoutRendererWrapper;
Assert.NotNull(upperCase);
var pad = ((SimpleLayout)upperCase.Inner).Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var message = ((SimpleLayout)pad.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void ReverseDoubleAmbientPropertyTest()
{
SimpleLayout l = "${message:padding=10:uppercase=true}";
Assert.Single(l.Renderers);
var pad = ((SimpleLayout)l).Renderers[0] as PaddingLayoutRendererWrapper;
Assert.NotNull(pad);
var upperCase = ((SimpleLayout)pad.Inner).Renderers[0] as UppercaseLayoutRendererWrapper;
Assert.NotNull(upperCase);
var message = ((SimpleLayout)upperCase.Inner).Renderers[0] as MessageLayoutRenderer;
Assert.NotNull(message);
}
[Fact]
public void EscapeTest()
{
AssertEscapeRoundTrips(string.Empty);
AssertEscapeRoundTrips("hello ${${}} world!");
AssertEscapeRoundTrips("hello $");
AssertEscapeRoundTrips("hello ${");
AssertEscapeRoundTrips("hello $${{");
AssertEscapeRoundTrips("hello ${message}");
AssertEscapeRoundTrips("hello ${${level}}");
AssertEscapeRoundTrips("hello ${${level}${message}}");
}
[Fact]
public void EvaluateTest()
{
var logEventInfo = LogEventInfo.CreateNullEvent();
logEventInfo.Level = LogLevel.Warn;
Assert.Equal("Warn", SimpleLayout.Evaluate("${level}", logEventInfo));
}
[Fact]
public void EvaluateTest2()
{
Assert.Equal("Off", SimpleLayout.Evaluate("${level}"));
Assert.Equal(string.Empty, SimpleLayout.Evaluate("${message}"));
Assert.Equal(string.Empty, SimpleLayout.Evaluate("${logger}"));
}
private static void AssertEscapeRoundTrips(string originalString)
{
string escapedString = SimpleLayout.Escape(originalString);
SimpleLayout l = escapedString;
string renderedString = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal(originalString, renderedString);
}
[Fact]
public void LayoutParserEscapeCodesForRegExTestV1()
{
MappedDiagnosticsContext.Clear();
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name=""searchExp""
value=""(?<!\\d[ -]*)(?\u003a(?<digits>\\d)[ -]*)\u007b8,16\u007d(?=(\\d[ -]*)\u007b3\u007d(\\d)(?![ -]\\d))""
/>
<variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" />
<targets>
<target name=""d1"" type=""Debug"" layout=""${message1}"" />
</targets>
<rules>
<logger name=""*"" minlevel=""Trace"" writeTo=""d1"" />
</rules>
</nlog>");
var d1 = configuration.FindTargetByName("d1") as DebugTarget;
Assert.NotNull(d1);
var layout = d1.Layout as SimpleLayout;
Assert.NotNull(layout);
var c = layout.Renderers.Count;
Assert.Equal(1, c);
var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper;
Assert.NotNull(l1);
Assert.True(l1.Regex);
Assert.True(l1.IgnoreCase);
Assert.Equal(@"::", l1.ReplaceWith);
Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor);
}
[Fact]
public void LayoutParserEscapeCodesForRegExTestV2()
{
MappedDiagnosticsContext.Clear();
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name=""searchExp""
value=""(?<!\\d[ -]*)(?\:(?<digits>\\d)[ -]*)\{8,16\}(?=(\\d[ -]*)\{3\}(\\d)(?![ -]\\d))""
/>
<variable name=""message1"" value=""${replace:inner=${message}:searchFor=${searchExp}:replaceWith=\u003a\u003a:regex=true:ignorecase=true}"" />
<targets>
<target name=""d1"" type=""Debug"" layout=""${message1}"" />
</targets>
<rules>
<logger name=""*"" minlevel=""Trace"" writeTo=""d1"" />
</rules>
</nlog>");
var d1 = configuration.FindTargetByName("d1") as DebugTarget;
Assert.NotNull(d1);
var layout = d1.Layout as SimpleLayout;
Assert.NotNull(layout);
var c = layout.Renderers.Count;
Assert.Equal(1, c);
var l1 = layout.Renderers[0] as ReplaceLayoutRendererWrapper;
Assert.NotNull(l1);
Assert.True(l1.Regex);
Assert.True(l1.IgnoreCase);
Assert.Equal(@"::", l1.ReplaceWith);
Assert.Equal(@"(?<!\d[ -]*)(?:(?<digits>\d)[ -]*){8,16}(?=(\d[ -]*){3}(\d)(?![ -]\d))", l1.SearchFor);
}
[Fact]
public void InnerLayoutWithColonTest_with_workaround()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test${literal:text=\:} Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test: Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithColonTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\: Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test: Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithSlashSingleTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test\\Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithSlashTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test\Hello}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test\\Hello", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest2()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello\\}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal(@"Test{Hello\}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_reverse()
{
SimpleLayout l = @"${when:Inner=Test{Hello\}:when=1 == 1}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_no_escape()
{
SimpleLayout l = @"${when:when=1 == 1:Inner=Test{Hello}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Test{Hello}", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest()
{
SimpleLayout l = @"${when:when=1 == 1:inner=Log_{#\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("Log_{#}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest_need_escape()
{
SimpleLayout l = @"${when:when=1 == 1:inner=L\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("L}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape()
{
SimpleLayout l = @"${when:when=1 == 1:inner=\}{.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("}{.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape2()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}{.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}{.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape3()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape4()
{
SimpleLayout l = @"${when:when=1 == 1:inner={\}\}\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("{}}}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithBracketsTest_needEscape5()
{
SimpleLayout l = @"${when:when=1 == 1:inner=\}{a\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("}{a}.log", l.Render(le));
}
[Fact]
public void InnerLayoutWithHashTest_and_layoutrender()
{
SimpleLayout l = @"${when:when=1 == 1:inner=${counter}/Log_{#\}.log}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("1/Log_{#}.log", l.Render(le));
}
[Fact]
public void InvalidLayoutWillParsePartly()
{
using (new NoThrowNLogExceptions())
{
SimpleLayout l = @"aaa ${iDontExist} bbb";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
Assert.Equal("aaa bbb", l.Render(le));
}
}
[Fact]
public void InvalidLayoutWillThrowIfExceptionThrowingIsOn()
{
LogManager.ThrowConfigExceptions = true;
Assert.Throws<ArgumentException>(() =>
{
SimpleLayout l = @"aaa ${iDontExist} bbb";
});
}
/// <summary>
///
/// Test layout with Generic List type. - is the separator
///
///
/// </summary>
/// <remarks>
/// comma escape is backtick (cannot use backslash due to layout parse)
/// </remarks>
/// <param name="input"></param>
/// <param name="propname"></param>
/// <param name="expected"></param>
[Theory]
[InlineData("2,3,4", "numbers", "2-3-4")]
[InlineData("a,b,c", "Strings", "a-b-c")]
[InlineData("a,b,c", "Objects", "a-b-c")]
[InlineData("a,,b,c", "Strings", "a--b-c")]
[InlineData("a`b,c", "Strings", "a`b-c")]
[InlineData("a\'b,c", "Strings", "a'b-c")]
[InlineData("'a,b',c", "Strings", "a,b-c")]
[InlineData("2.0,3.0,4.0", "doubles", "2-3-4")]
[InlineData("2.1,3.2,4.3", "doubles", "2.1-3.2-4.3")]
[InlineData("Ignore,Neutral,Ignore", "enums", "Ignore-Neutral-Ignore")]
[InlineData("ASCII,ISO-8859-1, UTF-8", "encodings", "us-ascii-iso-8859-1-utf-8")]
[InlineData("ASCII,ISO-8859-1,UTF-8", "encodings", "us-ascii-iso-8859-1-utf-8")]
[InlineData("Value1,Value3,Value2", "FlagEnums", "Value1-Value3-Value2")]
[InlineData("2,3,4", "IEnumerableNumber", "2-3-4")]
[InlineData("2,3,4", "IListNumber", "2-3-4")]
[InlineData("2,3,4", "HashsetNumber", "2-3-4")]
#if !NET3_5
[InlineData("2,3,4", "ISetNumber", "2-3-4")]
#endif
[InlineData("a,b,c", "IEnumerableString", "a-b-c")]
[InlineData("a,b,c", "IListString", "a-b-c")]
[InlineData("a,b,c", "HashSetString", "a-b-c")]
#if !NET3_5
[InlineData("a,b,c", "ISetString", "a-b-c")]
#endif
public void LayoutWithListParamTest(string input, string propname, string expected)
{
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("layoutrenderer-with-list", typeof(LayoutRendererWithListParam));
SimpleLayout l = $@"${{layoutrenderer-with-list:{propname}={input}}}";
var le = LogEventInfo.Create(LogLevel.Info, "logger", "message");
var actual = l.Render(le);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData("2,,3,4", "numbers")]
[InlineData("a,bc", "numbers")]
[InlineData("value1,value10", "FlagEnums")]
public void LayoutWithListParamTest_incorrect(string input, string propname)
{
//note flags enum already supported
//can;t convert empty to int
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("layoutrenderer-with-list", typeof(LayoutRendererWithListParam));
Assert.Throws<NLogConfigurationException>(() =>
{
SimpleLayout l = $@"${{layoutrenderer-with-list:{propname}={input}}}";
});
}
[Theory]
[InlineData(@" ${literal:text={0\} {1\}}")]
[InlineData(@" ${cached:${literal:text={0\} {1\}}}")]
[InlineData(@" ${cached:${cached:${literal:text={0\} {1\}}}}")]
[InlineData(@" ${cached:${cached:${cached:${literal:text={0\} {1\}}}}}")]
[InlineData(@"${cached:${cached:${cached:${cached:${literal:text={0\} {1\}}}}}}")]
public void Render_EscapedBrackets_ShouldRenderAllBrackets(string input)
{
SimpleLayout simple = input.Trim();
var result = simple.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("{0} {1}", result);
}
[Fact]
void FuncLayoutRendererRegisterTest1()
{
LayoutRenderer.Register("the-answer", (info) => "42");
Layout l = "${the-answer}";
var result = l.Render(LogEventInfo.CreateNullEvent());
Assert.Equal("42", result);
}
[Fact]
void FuncLayoutRendererFluentMethod_ThreadSafe_Test()
{
// Arrange
var layout = Layout.FromMethod(l => "42", LayoutRenderOptions.ThreadSafe);
// Act
var result = layout.Render(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal("42", result);
Assert.True(layout.ThreadSafe);
Assert.False(layout.ThreadAgnostic);
}
[Fact]
void FuncLayoutRendererFluentMethod_ThreadAgnostic_Test()
{
// Arrange
var layout = Layout.FromMethod(l => "42", LayoutRenderOptions.ThreadAgnostic);
// Act
var result = layout.Render(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal("42", result);
Assert.True(layout.ThreadSafe);
Assert.True(layout.ThreadAgnostic);
}
[Fact]
void FuncLayoutRendererFluentMethod_ThreadUnsafe_Test()
{
// Arrange
var layout = Layout.FromMethod(l => "42", LayoutRenderOptions.None);
// Act
var result = layout.Render(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal("42", result);
Assert.False(layout.ThreadSafe);
Assert.False(layout.ThreadAgnostic);
}
[Fact]
void FuncLayoutRendererFluentMethod_NullThrows_Test()
{
// Arrange
Assert.Throws<ArgumentNullException>(() => Layout.FromMethod(null));
}
[Fact]
void FuncLayoutRendererRegisterTest1WithXML()
{
LayoutRenderer.Register("the-answer", (info) => 42);
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<targets>
<target name='debug' type='Debug' layout= 'TheAnswer=${the-answer:Format=D3}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
var logger = LogManager.GetCurrentClassLogger();
logger.Debug("test1");
AssertDebugLastMessage("debug", "TheAnswer=042");
}
[Fact]
void FuncLayoutRendererRegisterTest2()
{
LayoutRenderer.Register("message-length", (info) => info.Message.Length);
Layout l = "${message-length}";
var result = l.Render(LogEventInfo.Create(LogLevel.Error, "logger-adhoc", "1234567890"));
Assert.Equal("10", result);
}
[Fact]
void SimpleLayout_FromString_ThrowConfigExceptions()
{
Assert.Throws<NLogConfigurationException>(() => Layout.FromString("${evil}", true));
}
[Fact]
void SimpleLayout_FromString_NoThrowConfigExceptions()
{
Assert.NotNull(Layout.FromString("${evil}", false));
}
[Theory]
[InlineData("", true)]
[InlineData(null, true)]
[InlineData("'a'", true)]
[InlineData("${gdc:a}", false)]
public void FromString_isFixedText(string input, bool expected)
{
// Act
var layout = (SimpleLayout)Layout.FromString(input);
layout.Initialize(null);
// Assert
Assert.Equal(expected, layout.IsFixedText);
}
[Theory]
[InlineData("", true)]
[InlineData(null, true)]
[InlineData("'a'", true)]
[InlineData("${gdc:a}", true)]
public void FromString_isThreadSafe(string input, bool expected)
{
// Act
var layout = (SimpleLayout)Layout.FromString(input);
layout.Initialize(null);
// Assert
Assert.Equal(expected, layout.ThreadSafe);
}
[Theory]
[InlineData("", "")]
[InlineData(null, "")]
[InlineData("'a'", "'a'")]
[InlineData("${gdc:a}", "")]
public void Render(string input, string expected)
{
var layout = (SimpleLayout)Layout.FromString(input);
// Act
var result = layout.Render(LogEventInfo.CreateNullEvent());
// Assert
Assert.Equal(expected, result);
}
private class LayoutRendererWithListParam : LayoutRenderer
{
public List<double> Doubles { get; set; }
public List<FilterResult> Enums { get; set; }
public List<MyFlagsEnum> FlagEnums { get; set; }
public List<int> Numbers { get; set; }
public List<string> Strings { get; set; }
public List<object> Objects { get; set; }
public List<Encoding> Encodings { get; set; }
public IEnumerable<string> IEnumerableString { get; set; }
public IEnumerable<int> IEnumerableNumber { get; set; }
public IList<string> IListString { get; set; }
public IList<int> IListNumber { get; set; }
#if !NET3_5
public ISet<string> ISetString { get; set; }
public ISet<int> ISetNumber { get; set; }
#endif
public HashSet<int> HashSetNumber { get; set; }
public HashSet<string> HashSetString { get; set; }
/// <summary>
/// Renders the specified environmental information and appends it to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
Append(builder, Strings);
AppendFormattable(builder, Numbers);
AppendFormattable(builder, Enums);
AppendFormattable(builder, FlagEnums);
AppendFormattable(builder, Doubles);
Append(builder, Encodings?.Select(e => e.BodyName).ToList());
Append(builder, Objects);
Append(builder, IEnumerableString);
AppendFormattable(builder, IEnumerableNumber);
Append(builder, IListString);
AppendFormattable(builder, IListNumber);
#if !NET3_5
Append(builder, ISetString);
AppendFormattable(builder, ISetNumber);
#endif
Append(builder, HashSetString);
AppendFormattable(builder, HashSetNumber);
}
private void Append<T>(StringBuilder builder, IEnumerable<T> items)
{
if (items != null) builder.Append(string.Join("-", items.ToArray()));
}
private void AppendFormattable<T>(StringBuilder builder, IEnumerable<T> items)
where T : IFormattable
{
if (items != null) builder.Append(string.Join("-", items.Select(it => it.ToString(null, CultureInfo.InvariantCulture)).ToArray()));
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////
//File: ViewSystemSelector.cs
//
//Description: Contains the MyClasses.MetaViewWrappers.ViewSystemSelector class,
// which is used to determine whether the Virindi View Service is enabled.
// As with all the VVS wrappers, the VVS_REFERENCED compilation symbol must be
// defined for the VVS code to be compiled. Otherwise, only Decal views are used.
//
//References required:
// VirindiViewService (if VVS_REFERENCED is defined)
// Decal.Adapter
// Decal.Interop.Core
//
//This file is Copyright (c) 2009 VirindiPlugins
//
//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.Text;
using System.Reflection;
#if METAVIEW_PUBLIC_NS
namespace MetaViewWrappers
#else
namespace MyClasses.MetaViewWrappers
#endif
{
internal static class ViewSystemSelector
{
public enum eViewSystem
{
DecalInject,
VirindiViewService,
}
///////////////////////////////System presence detection///////////////////////////////
public static bool IsPresent(Decal.Adapter.Wrappers.PluginHost pHost, eViewSystem VSystem)
{
switch (VSystem)
{
case eViewSystem.DecalInject:
return true;
case eViewSystem.VirindiViewService:
return VirindiViewsPresent(pHost);
default:
return false;
}
}
static bool VirindiViewsPresent(Decal.Adapter.Wrappers.PluginHost pHost)
{
#if VVS_REFERENCED
System.Reflection.Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
foreach (System.Reflection.Assembly a in asms)
{
AssemblyName nmm = a.GetName();
if ((nmm.Name == "VirindiViewService") && (nmm.Version >= new System.Version("1.0.0.18")))
{
try
{
return Curtain_VVS_Running();
}
catch
{
return false;
}
}
}
return false;
#else
return false;
#endif
}
public static bool VirindiViewsPresent(Decal.Adapter.Wrappers.PluginHost pHost, Version minver)
{
#if VVS_REFERENCED
System.Reflection.Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
foreach (System.Reflection.Assembly a in asms)
{
AssemblyName nm = a.GetName();
if ((nm.Name == "VirindiViewService") && (nm.Version >= minver))
{
try
{
return Curtain_VVS_Running();
}
catch
{
return false;
}
}
}
return false;
#else
return false;
#endif
}
#if VVS_REFERENCED
static bool Curtain_VVS_Running()
{
return VirindiViewService.Service.Running;
}
#endif
///////////////////////////////CreateViewResource///////////////////////////////
public static IView CreateViewResource(Decal.Adapter.Wrappers.PluginHost pHost, string pXMLResource)
{
#if VVS_REFERENCED
if (IsPresent(pHost, eViewSystem.VirindiViewService))
return CreateViewResource(pHost, pXMLResource, eViewSystem.VirindiViewService);
else
#endif
return CreateViewResource(pHost, pXMLResource, eViewSystem.DecalInject);
}
public static IView CreateViewResource(Decal.Adapter.Wrappers.PluginHost pHost, string pXMLResource, eViewSystem VSystem)
{
if (!IsPresent(pHost, VSystem)) return null;
switch (VSystem)
{
case eViewSystem.DecalInject:
return CreateDecalViewResource(pHost, pXMLResource);
case eViewSystem.VirindiViewService:
#if VVS_REFERENCED
return CreateMyHudViewResource(pHost, pXMLResource);
#else
break;
#endif
}
return null;
}
static IView CreateDecalViewResource(Decal.Adapter.Wrappers.PluginHost pHost, string pXMLResource)
{
IView ret = new DecalControls.View();
ret.Initialize(pHost, pXMLResource);
return ret;
}
#if VVS_REFERENCED
static IView CreateMyHudViewResource(Decal.Adapter.Wrappers.PluginHost pHost, string pXMLResource)
{
IView ret = new VirindiViewServiceHudControls.View();
ret.Initialize(pHost, pXMLResource);
return ret;
}
#endif
///////////////////////////////CreateViewXML///////////////////////////////
public static IView CreateViewXML(Decal.Adapter.Wrappers.PluginHost pHost, string pXML)
{
#if VVS_REFERENCED
if (IsPresent(pHost, eViewSystem.VirindiViewService))
return CreateViewXML(pHost, pXML, eViewSystem.VirindiViewService);
else
#endif
return CreateViewXML(pHost, pXML, eViewSystem.DecalInject);
}
public static IView CreateViewXML(Decal.Adapter.Wrappers.PluginHost pHost, string pXML, eViewSystem VSystem)
{
if (!IsPresent(pHost, VSystem)) return null;
switch (VSystem)
{
case eViewSystem.DecalInject:
return CreateDecalViewXML(pHost, pXML);
case eViewSystem.VirindiViewService:
#if VVS_REFERENCED
return CreateMyHudViewXML(pHost, pXML);
#else
break;
#endif
}
return null;
}
static IView CreateDecalViewXML(Decal.Adapter.Wrappers.PluginHost pHost, string pXML)
{
IView ret = new DecalControls.View();
ret.InitializeRawXML(pHost, pXML);
return ret;
}
#if VVS_REFERENCED
static IView CreateMyHudViewXML(Decal.Adapter.Wrappers.PluginHost pHost, string pXML)
{
IView ret = new VirindiViewServiceHudControls.View();
ret.InitializeRawXML(pHost, pXML);
return ret;
}
#endif
///////////////////////////////HasChatOpen///////////////////////////////
public static bool AnySystemHasChatOpen(Decal.Adapter.Wrappers.PluginHost pHost)
{
if (IsPresent(pHost, eViewSystem.VirindiViewService))
if (HasChatOpen_VirindiViews()) return true;
if (pHost.Actions.ChatState) return true;
return false;
}
static bool HasChatOpen_VirindiViews()
{
#if VVS_REFERENCED
if (VirindiViewService.HudView.FocusControl != null)
{
if (VirindiViewService.HudView.FocusControl.GetType() == typeof(VirindiViewService.Controls.HudTextBox))
return true;
}
return false;
#else
return false;
#endif
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace NDoc.Gui
{
/// <summary>
/// TraceWindow is a class that will connect to trace events and display trace outputs in a text box
/// </summary>
public class TraceWindowControl : System.Windows.Forms.UserControl
{
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.Button closeButton;
private System.Windows.Forms.Label captionLabel;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem clearMenuItem;
private System.Windows.Forms.MenuItem copyAllMenuItem;
private System.Windows.Forms.MenuItem copySelectionMenuItem;
private System.Windows.Forms.MenuItem menuItem1;
private System.ComponentModel.IContainer components;
/// <summary>
/// Creates a new instance of the TraceWindowControl class
/// </summary>
public TraceWindowControl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
}
/// <summary>
/// Gets/Set the window caption
/// </summary>
[Category("Appearance")]
[Browsable(true)]
public override string Text
{
get{ return captionLabel.Text; }
set{ captionLabel.Text = value; }
}
/// <summary>
/// Gets/Sets the test displayed in the trace window
/// </summary>
public string TraceText
{
get{ return richTextBox1.Text; }
set{ richTextBox1.Text = value; }
}
private bool _AutoConnect = false;
/// <summary>
/// Determines whether the control will connect to trace events when it becomes visible, and disconnect when it is hidden
/// </summary>
[Category("Behavior")]
[Browsable(true)]
[DefaultValue(false)]
[Description("Determines whether the control will connect to trace events when it becomes visible, and disconnect when it is hidden")]
public bool AutoConnect
{
get{ return _AutoConnect; }
set{ _AutoConnect = value; }
}
/// <summary>
/// Clears the contents of the window
/// </summary>
public void Clear()
{
this.richTextBox1.Clear();
}
#region Disposer
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
Disconnect();
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.closeButton = new System.Windows.Forms.Button();
this.captionLabel = new System.Windows.Forms.Label();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.clearMenuItem = new System.Windows.Forms.MenuItem();
this.copyAllMenuItem = new System.Windows.Forms.MenuItem();
this.copySelectionMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.richTextBox1.AutoWordSelection = true;
this.richTextBox1.CausesValidation = false;
this.richTextBox1.ContextMenu = this.contextMenu1;
this.richTextBox1.DetectUrls = false;
this.richTextBox1.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.richTextBox1.HideSelection = false;
this.richTextBox1.Location = new System.Drawing.Point(0, 16);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.ReadOnly = true;
this.richTextBox1.Size = new System.Drawing.Size(328, 224);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
this.richTextBox1.WordWrap = false;
this.richTextBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.richTextBox1_MouseDown);
//
// closeButton
//
this.closeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.closeButton.BackColor = System.Drawing.SystemColors.Control;
this.closeButton.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.closeButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 6F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.closeButton.Location = new System.Drawing.Point(312, 1);
this.closeButton.Name = "closeButton";
this.closeButton.Size = new System.Drawing.Size(14, 14);
this.closeButton.TabIndex = 1;
this.closeButton.TabStop = false;
this.closeButton.Text = "x";
this.toolTip1.SetToolTip(this.closeButton, "Close");
this.closeButton.Click += new System.EventHandler(this.closeButton_Click);
this.closeButton.MouseLeave += new System.EventHandler(this.closeButton_MouseLeave);
//
// captionLabel
//
this.captionLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.captionLabel.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.captionLabel.ForeColor = System.Drawing.SystemColors.ActiveCaptionText;
this.captionLabel.Location = new System.Drawing.Point(5, 0);
this.captionLabel.Name = "captionLabel";
this.captionLabel.Size = new System.Drawing.Size(323, 16);
this.captionLabel.TabIndex = 2;
this.captionLabel.Text = "Output";
//
// contextMenu1
//
this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.copyAllMenuItem,
this.copySelectionMenuItem,
this.menuItem1,
this.clearMenuItem});
//
// clearMenuItem
//
this.clearMenuItem.Index = 3;
this.clearMenuItem.Text = "Clear";
this.clearMenuItem.Click += new System.EventHandler(this.clearMenuItem_Click);
//
// copyAllMenuItem
//
this.copyAllMenuItem.Index = 0;
this.copyAllMenuItem.Text = "Copy All";
this.copyAllMenuItem.Click += new System.EventHandler(this.copyAllMenuItem_Click);
//
// copySelectionMenuItem
//
this.copySelectionMenuItem.Enabled = false;
this.copySelectionMenuItem.Index = 1;
this.copySelectionMenuItem.Text = "Copy Selection";
this.copySelectionMenuItem.Click += new System.EventHandler(this.copySelectionMenuItem_Click);
//
// menuItem1
//
this.menuItem1.Index = 2;
this.menuItem1.Text = "-";
//
// TraceWindowControl
//
this.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.Controls.Add(this.closeButton);
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.captionLabel);
this.Name = "TraceWindowControl";
this.Size = new System.Drawing.Size(328, 240);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// Raises the VisibleChanged event
/// </summary>
/// <param name="e">event arguments</param>
protected override void OnVisibleChanged(EventArgs e)
{
if ( AutoConnect )
{
if ( this.Visible )
Connect();
else
Disconnect();
}
base.OnVisibleChanged (e);
}
private TextWriterTraceListener listener = null;
/// <summary>
/// Connects the control to trace events
/// </summary>
public void Connect()
{
listener = new TextWriterTraceListener( new TextBoxWriter( this.richTextBox1 ) );
Trace.Listeners.Add( listener );
}
/// <summary>
/// Disconnects the control from trace events
/// </summary>
public void Disconnect()
{
if ( listener != null )
{
Trace.Listeners.Remove( listener );
listener.Flush();
listener.Close();
listener = null;
}
}
/// <summary>
/// Raised when the close button is clicked
/// </summary>
public event EventHandler CloseClick;
/// <summary>
/// Raises the <see cref="CloseClick"/> event
/// </summary>
protected virtual void OnCloseClick()
{
if ( CloseClick != null )
CloseClick( this, EventArgs.Empty );
}
private void closeButton_Click(object sender, System.EventArgs e)
{
this.Visible = false;
OnCloseClick();
}
private void closeButton_MouseLeave(object sender, System.EventArgs e)
{
if ( this.Focused )
this.Parent.Focus();
}
private void copySelectionMenuItem_Click(object sender, System.EventArgs e)
{
Clipboard.SetDataObject( this.richTextBox1.SelectedText, true );
}
private void copyAllMenuItem_Click(object sender, System.EventArgs e)
{
Clipboard.SetDataObject( this.richTextBox1.Text, true );
}
private void clearMenuItem_Click(object sender, System.EventArgs e)
{
this.richTextBox1.Clear();
}
private void richTextBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if ( e.Button == MouseButtons.Right )
{
this.clearMenuItem.Enabled = this.richTextBox1.Text.Length > 0;
this.copyAllMenuItem.Enabled = this.richTextBox1.Text.Length > 0;
this.copySelectionMenuItem.Enabled = this.richTextBox1.SelectedText.Length > 0;
}
}
}
}
| |
// 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 Xunit;
#if false
namespace Roslyn.Services.Editor.UnitTests.CodeGeneration
{
public class ExpressionPrecedenceGenerationTests : AbstractCodeGenerationTests
{
[WpfFact]
public void TestAddMultiplyPrecedence1()
{
TestExpression(
f => f.CreateMultiplyExpression(
f.CreateAddExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateConstantExpression(3)),
cs: "(1 + 2) * 3",
vb: "(1 + 2) * 3");
}
[WpfFact]
public void TestAddMultiplyPrecedence2()
{
TestExpression(
f => f.CreateAddExpression(
f.CreateMultiplyExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateConstantExpression(3)),
cs: "1 * 2 + 3",
vb: "1 * 2 + 3");
}
[WpfFact]
public void TestAddMultiplyPrecedence3()
{
TestExpression(
f => f.CreateMultiplyExpression(
f.CreateConstantExpression(1),
f.CreateAddExpression(
f.CreateConstantExpression(2),
f.CreateConstantExpression(3))),
cs: "1 * (2 + 3)",
vb: "1 * (2 + 3)");
}
[WpfFact]
public void TestAddMultiplyPrecedence4()
{
TestExpression(
f => f.CreateAddExpression(
f.CreateConstantExpression(1),
f.CreateMultiplyExpression(
f.CreateConstantExpression(2),
f.CreateConstantExpression(3))),
cs: "1 + 2 * 3",
vb: "1 + 2 * 3");
}
[WpfFact]
public void TestBinaryAndOrPrecedence1()
{
TestExpression(
f => f.CreateBinaryAndExpression(
f.CreateBinaryOrExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateConstantExpression(3)),
cs: "(1 | 2) & 3",
vb: "(1 Or 2) And 3");
}
[WpfFact]
public void TestBinaryAndOrPrecedence2()
{
TestExpression(
f => f.CreateBinaryOrExpression(
f.CreateBinaryAndExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateConstantExpression(3)),
cs: "1 & 2 | 3",
vb: "1 And 2 Or 3");
}
[WpfFact]
public void TestBinaryAndOrPrecedence3()
{
TestExpression(
f => f.CreateBinaryAndExpression(
f.CreateConstantExpression(1),
f.CreateBinaryOrExpression(
f.CreateConstantExpression(2),
f.CreateConstantExpression(3))),
cs: "1 & (2 | 3)",
vb: "1 And (2 Or 3)");
}
[WpfFact]
public void TestBinaryAndOrPrecedence4()
{
TestExpression(
f => f.CreateBinaryOrExpression(
f.CreateConstantExpression(1),
f.CreateBinaryAndExpression(
f.CreateConstantExpression(2),
f.CreateConstantExpression(3))),
cs: "1 | 2 & 3",
vb: "1 Or 2 And 3");
}
[WpfFact]
public void TestLogicalAndOrPrecedence1()
{
TestExpression(
f => f.CreateLogicalAndExpression(
f.CreateLogicalOrExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateConstantExpression(3)),
cs: "(1 || 2) && 3",
vb: "(1 OrElse 2) AndAlso 3");
}
[WpfFact]
public void TestLogicalAndOrPrecedence2()
{
TestExpression(
f => f.CreateLogicalOrExpression(
f.CreateLogicalAndExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateConstantExpression(3)),
cs: "1 && 2 || 3",
vb: "1 AndAlso 2 OrElse 3");
}
[WpfFact]
public void TestLogicalAndOrPrecedence3()
{
TestExpression(
f => f.CreateLogicalAndExpression(
f.CreateConstantExpression(1),
f.CreateLogicalOrExpression(
f.CreateConstantExpression(2),
f.CreateConstantExpression(3))),
cs: "1 && (2 || 3)",
vb: "1 AndAlso (2 OrElse 3)");
}
[WpfFact]
public void TestLogicalAndOrPrecedence4()
{
TestExpression(
f => f.CreateLogicalOrExpression(
f.CreateConstantExpression(1),
f.CreateLogicalAndExpression(
f.CreateConstantExpression(2),
f.CreateConstantExpression(3))),
cs: "1 || 2 && 3",
vb: "1 OrElse 2 AndAlso 3");
}
[WpfFact]
public void TestMemberAccessOffOfAdd1()
{
TestExpression(
f => f.CreateMemberAccessExpression(
f.CreateAddExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateIdentifierName("M")),
cs: "(1 + 2).M",
vb: "(1 + 2).M");
}
[WpfFact]
public void TestConditionalExpression1()
{
TestExpression(
f => f.CreateConditionalExpression(
f.CreateAssignExpression(
f.CreateIdentifierName("E1"),
f.CreateIdentifierName("E2")),
f.CreateIdentifierName("T"),
f.CreateIdentifierName("F")),
cs: "(E1 = E2) ? T : F");
}
[WpfFact]
public void TestConditionalExpression2()
{
TestExpression(
f => f.CreateAddExpression(
f.CreateConditionalExpression(
f.CreateIdentifierName("E1"),
f.CreateIdentifierName("T1"),
f.CreateIdentifierName("F1")),
f.CreateConditionalExpression(
f.CreateIdentifierName("E2"),
f.CreateIdentifierName("T2"),
f.CreateIdentifierName("F2"))),
cs: "(E1 ? T1 : F1) + (E2 ? T2 : F2)");
}
[WpfFact]
public void TestMemberAccessOffOfElementAccess()
{
TestExpression(
f => f.CreateElementAccessExpression(
f.CreateAddExpression(
f.CreateConstantExpression(1),
f.CreateConstantExpression(2)),
f.CreateArgument(f.CreateIdentifierName("M"))),
cs: "(1 + 2)[M]",
vb: "(1 + 2)(M)");
}
[WpfFact]
public void TestMemberAccessOffOfIsExpression()
{
TestExpression(
f => f.CreateMemberAccessExpression(
f.CreateIsExpression(
f.CreateIdentifierName("a"),
CreateClass("SomeType")),
f.CreateIdentifierName("M")),
cs: "(a is SomeType).M",
vb: "(TypeOf a Is SomeType).M");
}
[WpfFact]
public void TestIsOfMemberAccessExpression()
{
TestExpression(
f => f.CreateIsExpression(
f.CreateMemberAccessExpression(
f.CreateIdentifierName("a"),
f.CreateIdentifierName("M")),
CreateClass("SomeType")),
cs: "a.M is SomeType",
vb: "TypeOf a.M Is SomeType");
}
[WpfFact]
public void TestMemberAccessOffOfAsExpression()
{
TestExpression(
f => f.CreateMemberAccessExpression(
f.CreateAsExpression(
f.CreateIdentifierName("a"),
CreateClass("SomeType")),
f.CreateIdentifierName("M")),
cs: "(a as SomeType).M",
vb: "TryCast(a, SomeType).M");
}
[WpfFact]
public void TestAsOfMemberAccessExpression()
{
TestExpression(
f => f.CreateAsExpression(
f.CreateMemberAccessExpression(
f.CreateIdentifierName("a"),
f.CreateIdentifierName("M")),
CreateClass("SomeType")),
cs: "a.M as SomeType",
vb: "TryCast(a.M, SomeType)");
}
[WpfFact]
public void TestMemberAccessOffOfNotExpression()
{
TestExpression(
f => f.CreateMemberAccessExpression(
f.CreateLogicalNotExpression(
f.CreateIdentifierName("a")),
f.CreateIdentifierName("M")),
cs: "(!a).M",
vb: "(Not a).M");
}
[WpfFact]
public void TestNotOfMemberAccessExpression()
{
TestExpression(
f => f.CreateLogicalNotExpression(
f.CreateMemberAccessExpression(
f.CreateIdentifierName("a"),
f.CreateIdentifierName("M"))),
cs: "!a.M",
vb: "Not a.M");
}
[WpfFact]
public void TestMemberAccessOffOfCastExpression()
{
TestExpression(
f => f.CreateMemberAccessExpression(
f.CreateCastExpression(
CreateClass("SomeType"),
f.CreateIdentifierName("a")),
f.CreateIdentifierName("M")),
cs: "((SomeType)a).M",
vb: "DirectCast(a, SomeType).M");
}
[WpfFact]
public void TestCastOfAddExpression()
{
TestExpression(
f => f.CreateCastExpression(
CreateClass("SomeType"),
f.CreateAddExpression(
f.CreateIdentifierName("a"),
f.CreateIdentifierName("b"))),
cs: "(SomeType)(a + b)",
vb: "DirectCast(a + b, SomeType)");
}
[WpfFact]
public void TestNegateOfAddExpression()
{
TestExpression(
f => f.CreateNegateExpression(
f.CreateAddExpression(
f.CreateIdentifierName("a"),
f.CreateIdentifierName("b"))),
cs: "-(a + b)",
vb: "-(a + b)");
}
[WpfFact]
public void TestMemberAccessOffOfNegate()
{
TestExpression(
f => f.CreateMemberAccessExpression(
f.CreateNegateExpression(
f.CreateIdentifierName("a")),
f.CreateIdentifierName("M")),
cs: "(-a).M",
vb: "(-a).M");
}
[WpfFact]
public void TestNegateOfMemberAccess()
{
TestExpression(f =>
f.CreateNegateExpression(
f.CreateMemberAccessExpression(
f.CreateIdentifierName("a"),
f.CreateIdentifierName("M"))),
cs: "-a.M",
vb: "-a.M");
}
}
}
#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.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Internal.Runtime;
namespace System.Runtime
{
public enum RhFailFastReason
{
Unknown = 0,
InternalError = 1, // "Runtime internal error"
UnhandledException_ExceptionDispatchNotAllowed = 2, // "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope."
UnhandledException_CallerDidNotHandle = 3, // "Unhandled exception: no handler found in calling method."
ClassLibDidNotTranslateExceptionID = 4, // "Unable to translate failure into a classlib-specific exception object."
IllegalNativeCallableEntry = 5, // "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code."
PN_UnhandledException = 6, // ProjectN: "unhandled exception"
PN_UnhandledExceptionFromPInvoke = 7, // ProjectN: "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition."
Max
}
// Keep this synchronized with the duplicate definition in DebugEventSource.cpp
[Flags]
internal enum ExceptionEventKind
{
Thrown = 1,
CatchHandlerFound = 2,
Unhandled = 4,
FirstPassFrameEntered = 8
}
internal static unsafe class DebuggerNotify
{
// We cache the events a debugger is interested on the C# side to avoid p/invokes when the
// debugger isn't attached.
//
// Ideally we would like the managed debugger to start toggling this directly so that
// it stays perfectly up-to-date. However as a reasonable approximation we fetch
// the value from native code at the beginning of each exception dispatch. If the debugger
// attempts to enroll in more events mid-exception handling we aren't going to see it.
private static ExceptionEventKind s_cachedEventMask;
internal static void BeginFirstPass(object exceptionObj, byte* faultingIP, UIntPtr faultingFrameSP)
{
s_cachedEventMask = InternalCalls.RhpGetRequestedExceptionEvents();
if ((s_cachedEventMask & ExceptionEventKind.Thrown) == 0)
return;
InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.Thrown, faultingIP, faultingFrameSP);
}
internal static void FirstPassFrameEntered(object exceptionObj, byte* enteredFrameIP, UIntPtr enteredFrameSP)
{
s_cachedEventMask = InternalCalls.RhpGetRequestedExceptionEvents();
if ((s_cachedEventMask & ExceptionEventKind.FirstPassFrameEntered) == 0)
return;
InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.FirstPassFrameEntered, enteredFrameIP, enteredFrameSP);
}
internal static void EndFirstPass(object exceptionObj, byte* handlerIP, UIntPtr handlingFrameSP)
{
if (handlerIP == null)
{
if ((s_cachedEventMask & ExceptionEventKind.Unhandled) == 0)
return;
InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.Unhandled, null, UIntPtr.Zero);
}
else
{
if ((s_cachedEventMask & ExceptionEventKind.CatchHandlerFound) == 0)
return;
InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.CatchHandlerFound, handlerIP, handlingFrameSP);
}
}
internal static void BeginSecondPass()
{
//desktop debugging has an unwind begin event, however it appears that is unneeded for now, and possibly
// will never be needed?
}
}
internal static unsafe class EH
{
internal static UIntPtr MaxSP
{
get
{
return (UIntPtr)(void*)(-1);
}
}
private enum RhEHClauseKind
{
RH_EH_CLAUSE_TYPED = 0,
RH_EH_CLAUSE_FAULT = 1,
RH_EH_CLAUSE_FILTER = 2,
RH_EH_CLAUSE_UNUSED = 3,
}
private struct RhEHClause
{
internal RhEHClauseKind _clauseKind;
internal uint _tryStartOffset;
internal uint _tryEndOffset;
internal byte* _filterAddress;
internal byte* _handlerAddress;
internal void* _pTargetType;
///<summary>
/// We expect the stackwalker to adjust return addresses to point at 'return address - 1' so that we
/// can use an interval here that is closed at the start and open at the end. When a hardware fault
/// occurs, the IP is pointing at the start of the instruction and will not be adjusted by the
/// stackwalker. Therefore, it will naturally work with an interval that has a closed start and open
/// end.
///</summary>
public bool ContainsCodeOffset(uint codeOffset)
{
return ((codeOffset >= _tryStartOffset) &&
(codeOffset < _tryEndOffset));
}
}
[StructLayout(LayoutKind.Explicit, Size = AsmOffsets.SIZEOF__EHEnum)]
private struct EHEnum
{
[FieldOffset(0)]
private IntPtr _dummy; // For alignment
}
// This is a fail-fast function used by the runtime as a last resort that will terminate the process with
// as little effort as possible. No guarantee is made about the semantics of this fail-fast.
internal static void FallbackFailFast(RhFailFastReason reason, object unhandledException)
{
InternalCalls.RhpFallbackFailFast();
}
// Constants used with RhpGetClasslibFunction, to indicate which classlib function
// we are interested in.
// Note: make sure you change the def in EHHelpers.cpp if you change this!
internal enum ClassLibFunctionId
{
GetRuntimeException = 0,
FailFast = 1,
// UnhandledExceptionHandler = 2, // unused
AppendExceptionStackFrame = 3,
CheckStaticClassConstruction = 4,
GetSystemArrayEEType = 5,
OnFirstChance = 6,
}
// Given an address pointing somewhere into a managed module, get the classlib-defined fail-fast
// function and invoke it. Any failure to find and invoke the function, or if it returns, results in
// MRT-defined fail-fast behavior.
internal static void FailFastViaClasslib(RhFailFastReason reason, object unhandledException,
IntPtr classlibAddress)
{
// Find the classlib function that will fail fast. This is a RuntimeExport function from the
// classlib module, and is therefore managed-callable.
IntPtr pFailFastFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(classlibAddress,
ClassLibFunctionId.FailFast);
if (pFailFastFunction == IntPtr.Zero)
{
// The classlib didn't provide a function, so we fail our way...
FallbackFailFast(reason, unhandledException);
}
try
{
// Invoke the classlib fail fast function.
CalliIntrinsics.CallVoid(pFailFastFunction, reason, unhandledException, IntPtr.Zero, IntPtr.Zero);
}
catch
{
// disallow all exceptions leaking out of callbacks
}
// The classlib's function should never return and should not throw. If it does, then we fail our way...
FallbackFailFast(reason, unhandledException);
}
#if AMD64
[StructLayout(LayoutKind.Explicit, Size = 0x4d0)]
#elif ARM
[StructLayout(LayoutKind.Explicit, Size=0x1a0)]
#elif X86
[StructLayout(LayoutKind.Explicit, Size=0x2cc)]
#else
[StructLayout(LayoutKind.Explicit, Size = 0x10)] // this is small enough that it should trip an assert in RhpCopyContextFromExInfo
#endif
private struct OSCONTEXT
{
}
internal static unsafe void* PointerAlign(void* ptr, int alignmentInBytes)
{
int alignMask = alignmentInBytes - 1;
#if BIT64
return (void*)((((long)ptr) + alignMask) & ~alignMask);
#else
return (void*)((((int)ptr) + alignMask) & ~alignMask);
#endif
}
private static void OnFirstChanceExceptionViaClassLib(object exception)
{
IntPtr pOnFirstChanceFunction =
(IntPtr)InternalCalls.RhpGetClasslibFunctionFromEEType((IntPtr)exception.m_pEEType, ClassLibFunctionId.OnFirstChance);
if (pOnFirstChanceFunction == IntPtr.Zero)
{
return;
}
try
{
CalliIntrinsics.CallVoid(pOnFirstChanceFunction, exception);
}
catch
{
// disallow all exceptions leaking out of callbacks
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static unsafe void UnhandledExceptionFailFastViaClasslib(
RhFailFastReason reason, object unhandledException, IntPtr classlibAddress, ref ExInfo exInfo)
{
IntPtr pFailFastFunction =
(IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(classlibAddress, ClassLibFunctionId.FailFast);
if (pFailFastFunction == IntPtr.Zero)
{
FailFastViaClasslib(
reason,
unhandledException,
classlibAddress);
}
// 16-byte align the context. This is overkill on x86 and ARM, but simplifies things slightly.
const int contextAlignment = 16;
byte* pbBuffer = stackalloc byte[sizeof(OSCONTEXT) + contextAlignment];
void* pContext = PointerAlign(pbBuffer, contextAlignment);
InternalCalls.RhpCopyContextFromExInfo(pContext, sizeof(OSCONTEXT), exInfo._pExContext);
try
{
CalliIntrinsics.CallVoid(pFailFastFunction, reason, unhandledException, exInfo._pExContext->IP, (IntPtr)pContext);
}
catch
{
// disallow all exceptions leaking out of callbacks
}
// The classlib's funciton should never return and should not throw. If it does, then we fail our way...
FallbackFailFast(reason, unhandledException);
}
private enum RhEHFrameType
{
RH_EH_FIRST_FRAME = 1,
RH_EH_FIRST_RETHROW_FRAME = 2,
}
private static void AppendExceptionStackFrameViaClasslib(object exception, IntPtr IP,
ref bool isFirstRethrowFrame, ref bool isFirstFrame)
{
IntPtr pAppendStackFrame = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(IP,
ClassLibFunctionId.AppendExceptionStackFrame);
if (pAppendStackFrame != IntPtr.Zero)
{
int flags = (isFirstFrame ? (int)RhEHFrameType.RH_EH_FIRST_FRAME : 0) |
(isFirstRethrowFrame ? (int)RhEHFrameType.RH_EH_FIRST_RETHROW_FRAME : 0);
try
{
CalliIntrinsics.CallVoid(pAppendStackFrame, exception, IP, flags);
}
catch
{
// disallow all exceptions leaking out of callbacks
}
// Clear flags only if we called the function
isFirstRethrowFrame = false;
isFirstFrame = false;
}
}
// Given an ExceptionID and an address pointing somewhere into a managed module, get
// an exception object of a type that the module containing the given address will understand.
// This finds the classlib-defined GetRuntimeException function and asks it for the exception object.
internal static Exception GetClasslibException(ExceptionIDs id, IntPtr address)
{
// Find the classlib function that will give us the exception object we want to throw. This
// is a RuntimeExport function from the classlib module, and is therefore managed-callable.
IntPtr pGetRuntimeExceptionFunction =
(IntPtr)InternalCalls.RhpGetClasslibFunctionFromCodeAddress(address, ClassLibFunctionId.GetRuntimeException);
// Return the exception object we get from the classlib.
Exception e = null;
try
{
e = CalliIntrinsics.Call<Exception>(pGetRuntimeExceptionFunction, id);
}
catch
{
// disallow all exceptions leaking out of callbacks
}
// If the helper fails to yield an object, then we fail-fast.
if (e == null)
{
FailFastViaClasslib(
RhFailFastReason.ClassLibDidNotTranslateExceptionID,
null,
address);
}
return e;
}
// Given an ExceptionID and an EEType address, get an exception object of a type that the module containing
// the given address will understand. This finds the classlib-defined GetRuntimeException function and asks
// it for the exception object.
internal static Exception GetClasslibExceptionFromEEType(ExceptionIDs id, IntPtr pEEType)
{
// Find the classlib function that will give us the exception object we want to throw. This
// is a RuntimeExport function from the classlib module, and is therefore managed-callable.
IntPtr pGetRuntimeExceptionFunction = IntPtr.Zero;
if (pEEType != IntPtr.Zero)
{
pGetRuntimeExceptionFunction = (IntPtr)InternalCalls.RhpGetClasslibFunctionFromEEType(pEEType, ClassLibFunctionId.GetRuntimeException);
}
// Return the exception object we get from the classlib.
Exception e = null;
try
{
e = CalliIntrinsics.Call<Exception>(pGetRuntimeExceptionFunction, id);
}
catch
{
// disallow all exceptions leaking out of callbacks
}
// If the helper fails to yield an object, then we fail-fast.
if (e == null)
{
FailFastViaClasslib(
RhFailFastReason.ClassLibDidNotTranslateExceptionID,
null,
pEEType);
}
return e;
}
// RhExceptionHandling_ functions are used to throw exceptions out of our asm helpers. We tail-call from
// the asm helpers to these functions, which performs the throw. The tail-call is important: it ensures that
// the stack is crawlable from within these functions.
[RuntimeExport("RhExceptionHandling_ThrowClasslibOverflowException")]
public static void ThrowClasslibOverflowException(IntPtr address)
{
// Throw the overflow exception defined by the classlib, using the return address of the asm helper
// to find the correct classlib.
throw GetClasslibException(ExceptionIDs.Overflow, address);
}
[RuntimeExport("RhExceptionHandling_ThrowClasslibDivideByZeroException")]
public static void ThrowClasslibDivideByZeroException(IntPtr address)
{
// Throw the divide by zero exception defined by the classlib, using the return address of the asm helper
// to find the correct classlib.
throw GetClasslibException(ExceptionIDs.DivideByZero, address);
}
[RuntimeExport("RhExceptionHandling_FailedAllocation")]
public static void FailedAllocation(EETypePtr pEEType, bool fIsOverflow)
{
ExceptionIDs exID = fIsOverflow ? ExceptionIDs.Overflow : ExceptionIDs.OutOfMemory;
// Throw the out of memory exception defined by the classlib, using the input EEType*
// to find the correct classlib.
throw pEEType.ToPointer()->GetClasslibException(exID);
}
#if !INPLACE_RUNTIME
private static OutOfMemoryException s_theOOMException = new OutOfMemoryException();
// MRT exports GetRuntimeException for the few cases where we have a helper that throws an exception
// and may be called by either MRT or other classlibs and that helper needs to throw an exception.
// There are only a few cases where this happens now (the fast allocation helpers), so we limit the
// exception types that MRT will return.
[RuntimeExport("GetRuntimeException")]
public static Exception GetRuntimeException(ExceptionIDs id)
{
switch (id)
{
case ExceptionIDs.OutOfMemory:
// Throw a preallocated exception to avoid infinite recursion.
return s_theOOMException;
case ExceptionIDs.Overflow:
return new OverflowException();
case ExceptionIDs.InvalidCast:
return new InvalidCastException();
default:
Debug.Assert(false, "unexpected ExceptionID");
FallbackFailFast(RhFailFastReason.InternalError, null);
return null;
}
}
#endif
private enum HwExceptionCode : uint
{
STATUS_REDHAWK_NULL_REFERENCE = 0x00000000u,
STATUS_REDHAWK_WRITE_BARRIER_NULL_REFERENCE = 0x00000042u,
STATUS_REDHAWK_THREAD_ABORT = 0x00000043u,
STATUS_DATATYPE_MISALIGNMENT = 0x80000002u,
STATUS_ACCESS_VIOLATION = 0xC0000005u,
STATUS_INTEGER_DIVIDE_BY_ZERO = 0xC0000094u,
STATUS_INTEGER_OVERFLOW = 0xC0000095u,
}
[StructLayout(LayoutKind.Explicit, Size = AsmOffsets.SIZEOF__PAL_LIMITED_CONTEXT)]
public struct PAL_LIMITED_CONTEXT
{
[FieldOffset(AsmOffsets.OFFSETOF__PAL_LIMITED_CONTEXT__IP)]
internal IntPtr IP;
// the rest of the struct is left unspecified.
}
// N.B. -- These values are burned into the throw helper assembly code and are also known the the
// StackFrameIterator code.
[Flags]
internal enum ExKind : byte
{
None = 0,
Throw = 1,
HardwareFault = 2,
KindMask = 3,
RethrowFlag = 4,
SupersededFlag = 8,
InstructionFaultFlag = 0x10
}
[IsByRefLike]
[StructLayout(LayoutKind.Explicit)]
public struct ExInfo
{
internal void Init(object exceptionObj, bool instructionFault = false)
{
// _pPrevExInfo -- set by asm helper
// _pExContext -- set by asm helper
// _passNumber -- set by asm helper
// _kind -- set by asm helper
// _idxCurClause -- set by asm helper
// _frameIter -- initialized explicitly during dispatch
_exception = exceptionObj;
if (instructionFault)
_kind |= ExKind.InstructionFaultFlag;
_notifyDebuggerSP = UIntPtr.Zero;
}
internal void Init(object exceptionObj, ref ExInfo rethrownExInfo)
{
// _pPrevExInfo -- set by asm helper
// _pExContext -- set by asm helper
// _passNumber -- set by asm helper
// _idxCurClause -- set by asm helper
// _frameIter -- initialized explicitly during dispatch
_exception = exceptionObj;
_kind = rethrownExInfo._kind | ExKind.RethrowFlag;
_notifyDebuggerSP = UIntPtr.Zero;
}
internal object ThrownException
{
get
{
return _exception;
}
}
[FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_pPrevExInfo)]
internal void* _pPrevExInfo;
[FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_pExContext)]
internal PAL_LIMITED_CONTEXT* _pExContext;
[FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_exception)]
private object _exception; // actual object reference, specially reported by GcScanRootsWorker
[FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_kind)]
internal ExKind _kind;
[FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_passNumber)]
internal byte _passNumber;
// BEWARE: This field is used by the stackwalker to know if the dispatch code has reached the
// point at which a handler is called. In other words, it serves as an "is a handler
// active" state where '_idxCurClause == MaxTryRegionIdx' means 'no'.
[FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_idxCurClause)]
internal uint _idxCurClause;
[FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_frameIter)]
internal StackFrameIterator _frameIter;
[FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_notifyDebuggerSP)]
volatile internal UIntPtr _notifyDebuggerSP;
}
//
// Called by RhpThrowHwEx
//
[RuntimeExport("RhThrowHwEx")]
public static void RhThrowHwEx(uint exceptionCode, ref ExInfo exInfo)
{
// trigger a GC (only if gcstress) to ensure we can stackwalk at this point
GCStress.TriggerGC();
InternalCalls.RhpValidateExInfoStack();
IntPtr faultingCodeAddress = exInfo._pExContext->IP;
bool instructionFault = true;
ExceptionIDs exceptionId = default(ExceptionIDs);
Exception exceptionToThrow = null;
switch (exceptionCode)
{
case (uint)HwExceptionCode.STATUS_REDHAWK_NULL_REFERENCE:
exceptionId = ExceptionIDs.NullReference;
break;
case (uint)HwExceptionCode.STATUS_REDHAWK_WRITE_BARRIER_NULL_REFERENCE:
// The write barrier where the actual fault happened has been unwound already.
// The IP of this fault needs to be treated as return address, not as IP of
// faulting instruction.
instructionFault = false;
exceptionId = ExceptionIDs.NullReference;
break;
case (uint)HwExceptionCode.STATUS_REDHAWK_THREAD_ABORT:
exceptionToThrow = InternalCalls.RhpGetThreadAbortException();
break;
case (uint)HwExceptionCode.STATUS_DATATYPE_MISALIGNMENT:
exceptionId = ExceptionIDs.DataMisaligned;
break;
// N.B. -- AVs that have a read/write address lower than 64k are already transformed to
// HwExceptionCode.REDHAWK_NULL_REFERENCE prior to calling this routine.
case (uint)HwExceptionCode.STATUS_ACCESS_VIOLATION:
exceptionId = ExceptionIDs.AccessViolation;
break;
case (uint)HwExceptionCode.STATUS_INTEGER_DIVIDE_BY_ZERO:
exceptionId = ExceptionIDs.DivideByZero;
break;
case (uint)HwExceptionCode.STATUS_INTEGER_OVERFLOW:
exceptionId = ExceptionIDs.Overflow;
break;
default:
// We don't wrap SEH exceptions from foreign code like CLR does, so we believe that we
// know the complete set of HW faults generated by managed code and do not need to handle
// this case.
FailFastViaClasslib(RhFailFastReason.InternalError, null, faultingCodeAddress);
break;
}
if (exceptionId != default(ExceptionIDs))
{
exceptionToThrow = GetClasslibException(exceptionId, faultingCodeAddress);
}
exInfo.Init(exceptionToThrow, instructionFault);
DispatchEx(ref exInfo._frameIter, ref exInfo, MaxTryRegionIdx);
FallbackFailFast(RhFailFastReason.InternalError, null);
}
private const uint MaxTryRegionIdx = 0xFFFFFFFFu;
[RuntimeExport("RhThrowEx")]
public static void RhThrowEx(object exceptionObj, ref ExInfo exInfo)
{
// trigger a GC (only if gcstress) to ensure we can stackwalk at this point
GCStress.TriggerGC();
InternalCalls.RhpValidateExInfoStack();
// Transform attempted throws of null to a throw of NullReferenceException.
if (exceptionObj == null)
{
IntPtr faultingCodeAddress = exInfo._pExContext->IP;
exceptionObj = GetClasslibException(ExceptionIDs.NullReference, faultingCodeAddress);
}
exInfo.Init(exceptionObj);
DispatchEx(ref exInfo._frameIter, ref exInfo, MaxTryRegionIdx);
FallbackFailFast(RhFailFastReason.InternalError, null);
}
[RuntimeExport("RhRethrow")]
public static void RhRethrow(ref ExInfo activeExInfo, ref ExInfo exInfo)
{
// trigger a GC (only if gcstress) to ensure we can stackwalk at this point
GCStress.TriggerGC();
InternalCalls.RhpValidateExInfoStack();
// We need to copy the exception object to this stack location because collided unwinds
// will cause the original stack location to go dead.
object rethrownException = activeExInfo.ThrownException;
exInfo.Init(rethrownException, ref activeExInfo);
DispatchEx(ref exInfo._frameIter, ref exInfo, activeExInfo._idxCurClause);
FallbackFailFast(RhFailFastReason.InternalError, null);
}
private static void DispatchEx(ref StackFrameIterator frameIter, ref ExInfo exInfo, uint startIdx)
{
Debug.Assert(exInfo._passNumber == 1, "expected asm throw routine to set the pass");
object exceptionObj = exInfo.ThrownException;
// ------------------------------------------------
//
// First pass
//
// ------------------------------------------------
UIntPtr handlingFrameSP = MaxSP;
byte* pCatchHandler = null;
uint catchingTryRegionIdx = MaxTryRegionIdx;
bool isFirstRethrowFrame = (startIdx != MaxTryRegionIdx);
bool isFirstFrame = true;
byte* prevControlPC = null;
UIntPtr prevFramePtr = UIntPtr.Zero;
bool unwoundReversePInvoke = false;
bool isValid = frameIter.Init(exInfo._pExContext, (exInfo._kind & ExKind.InstructionFaultFlag) != 0);
Debug.Assert(isValid, "RhThrowEx called with an unexpected context");
OnFirstChanceExceptionViaClassLib(exceptionObj);
DebuggerNotify.BeginFirstPass(exceptionObj, frameIter.ControlPC, frameIter.SP);
for (; isValid; isValid = frameIter.Next(out startIdx, out unwoundReversePInvoke))
{
// For GC stackwalking, we'll happily walk across native code blocks, but for EH dispatch, we
// disallow dispatching exceptions across native code.
if (unwoundReversePInvoke)
break;
prevControlPC = frameIter.ControlPC;
DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP);
// A debugger can subscribe to get callbacks at a specific frame of exception dispatch
// exInfo._notifyDebuggerSP can be populated by the debugger from out of process
// at any time.
if (exInfo._notifyDebuggerSP == frameIter.SP)
DebuggerNotify.FirstPassFrameEntered(exceptionObj, frameIter.ControlPC, frameIter.SP);
UpdateStackTrace(exceptionObj, ref exInfo, ref isFirstRethrowFrame, ref prevFramePtr, ref isFirstFrame);
byte* pHandler;
if (FindFirstPassHandler(exceptionObj, startIdx, ref frameIter,
out catchingTryRegionIdx, out pHandler))
{
handlingFrameSP = frameIter.SP;
pCatchHandler = pHandler;
DebugVerifyHandlingFrame(handlingFrameSP);
break;
}
}
DebuggerNotify.EndFirstPass(exceptionObj, pCatchHandler, handlingFrameSP);
if (pCatchHandler == null)
{
UnhandledExceptionFailFastViaClasslib(
RhFailFastReason.PN_UnhandledException,
exceptionObj,
(IntPtr)prevControlPC, // IP of the last frame that did not handle the exception
ref exInfo);
}
// We FailFast above if the exception goes unhandled. Therefore, we cannot run the second pass
// without a catch handler.
Debug.Assert(pCatchHandler != null, "We should have a handler if we're starting the second pass");
DebuggerNotify.BeginSecondPass();
// ------------------------------------------------
//
// Second pass
//
// ------------------------------------------------
// Due to the stackwalker logic, we cannot tolerate triggering a GC from the dispatch code once we
// are in the 2nd pass. This is because the stackwalker applies a particular unwind semantic to
// 'collapse' funclets which gets confused when we walk out of the dispatch code and encounter the
// 'main body' without first encountering the funclet. The thunks used to invoke 2nd-pass
// funclets will always toggle this mode off before invoking them.
InternalCalls.RhpSetThreadDoNotTriggerGC();
exInfo._passNumber = 2;
startIdx = MaxTryRegionIdx;
isValid = frameIter.Init(exInfo._pExContext, (exInfo._kind & ExKind.InstructionFaultFlag) != 0);
for (; isValid && ((byte*)frameIter.SP <= (byte*)handlingFrameSP); isValid = frameIter.Next(out startIdx))
{
Debug.Assert(isValid, "second-pass EH unwind failed unexpectedly");
DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP);
if (frameIter.SP == handlingFrameSP)
{
// invoke only a partial second-pass here...
InvokeSecondPass(ref exInfo, startIdx, catchingTryRegionIdx);
break;
}
InvokeSecondPass(ref exInfo, startIdx);
}
// ------------------------------------------------
//
// Call the handler and resume execution
//
// ------------------------------------------------
exInfo._idxCurClause = catchingTryRegionIdx;
InternalCalls.RhpCallCatchFunclet(
exceptionObj, pCatchHandler, frameIter.RegisterSet, ref exInfo);
// currently, RhpCallCatchFunclet will resume after the catch
Debug.Assert(false, "unreachable");
FallbackFailFast(RhFailFastReason.InternalError, null);
}
[System.Diagnostics.Conditional("DEBUG")]
private static void DebugScanCallFrame(int passNumber, byte* ip, UIntPtr sp)
{
Debug.Assert(ip != null, "IP address must not be null");
}
[System.Diagnostics.Conditional("DEBUG")]
private static void DebugVerifyHandlingFrame(UIntPtr handlingFrameSP)
{
Debug.Assert(handlingFrameSP != MaxSP, "Handling frame must have an SP value");
Debug.Assert(((UIntPtr*)handlingFrameSP) > &handlingFrameSP,
"Handling frame must have a valid stack frame pointer");
}
private static void UpdateStackTrace(object exceptionObj, ref ExInfo exInfo,
ref bool isFirstRethrowFrame, ref UIntPtr prevFramePtr, ref bool isFirstFrame)
{
// We use the fact that all funclet stack frames belonging to the same logical method activation
// will have the same FramePointer value. Additionally, the stackwalker will return a sequence of
// callbacks for all the funclet stack frames, one right after the other. The classlib doesn't
// want to know about funclets, so we strip them out by only reporting the first frame of a
// sequence of funclets. This is correct because the leafmost funclet is first in the sequence
// and corresponds to the current 'IP state' of the method.
UIntPtr curFramePtr = exInfo._frameIter.FramePointer;
if ((prevFramePtr == UIntPtr.Zero) || (curFramePtr != prevFramePtr))
{
AppendExceptionStackFrameViaClasslib(exceptionObj, (IntPtr)exInfo._frameIter.ControlPC,
ref isFirstRethrowFrame, ref isFirstFrame);
}
prevFramePtr = curFramePtr;
}
private static bool FindFirstPassHandler(object exception, uint idxStart,
ref StackFrameIterator frameIter, out uint tryRegionIdx, out byte* pHandler)
{
pHandler = null;
tryRegionIdx = MaxTryRegionIdx;
EHEnum ehEnum;
byte* pbMethodStartAddress;
if (!InternalCalls.RhpEHEnumInitFromStackFrameIterator(ref frameIter, &pbMethodStartAddress, &ehEnum))
return false;
byte* pbControlPC = frameIter.ControlPC;
uint codeOffset = (uint)(pbControlPC - pbMethodStartAddress);
uint lastTryStart = 0, lastTryEnd = 0;
// Search the clauses for one that contains the current offset.
RhEHClause ehClause;
for (uint curIdx = 0; InternalCalls.RhpEHEnumNext(&ehEnum, &ehClause); curIdx++)
{
//
// Skip to the starting try region. This is used by collided unwinds and rethrows to pickup where
// the previous dispatch left off.
//
if (idxStart != MaxTryRegionIdx)
{
if (curIdx <= idxStart)
{
lastTryStart = ehClause._tryStartOffset; lastTryEnd = ehClause._tryEndOffset;
continue;
}
// Now, we continue skipping while the try region is identical to the one that invoked the
// previous dispatch.
if ((ehClause._tryStartOffset == lastTryStart) && (ehClause._tryEndOffset == lastTryEnd))
continue;
// We are done skipping. This is required to handle empty finally block markers that are used
// to separate runs of different try blocks with same native code offsets.
idxStart = MaxTryRegionIdx;
}
RhEHClauseKind clauseKind = ehClause._clauseKind;
if (((clauseKind != RhEHClauseKind.RH_EH_CLAUSE_TYPED) &&
(clauseKind != RhEHClauseKind.RH_EH_CLAUSE_FILTER))
|| !ehClause.ContainsCodeOffset(codeOffset))
{
continue;
}
// Found a containing clause. Because of the order of the clauses, we know this is the
// most containing.
if (clauseKind == RhEHClauseKind.RH_EH_CLAUSE_TYPED)
{
if (ShouldTypedClauseCatchThisException(exception, (EEType*)ehClause._pTargetType))
{
pHandler = ehClause._handlerAddress;
tryRegionIdx = curIdx;
return true;
}
}
else
{
byte* pFilterFunclet = ehClause._filterAddress;
bool shouldInvokeHandler =
InternalCalls.RhpCallFilterFunclet(exception, pFilterFunclet, frameIter.RegisterSet);
if (shouldInvokeHandler)
{
pHandler = ehClause._handlerAddress;
tryRegionIdx = curIdx;
return true;
}
}
}
return false;
}
private static EEType* s_pLowLevelObjectType;
private static bool ShouldTypedClauseCatchThisException(object exception, EEType* pClauseType)
{
if (TypeCast.IsInstanceOfClass(exception, pClauseType) != null)
return true;
if (s_pLowLevelObjectType == null)
{
// TODO: Avoid allocating here as that may fail
s_pLowLevelObjectType = new System.Object().EEType;
}
// This allows the typical try { } catch { }--which expands to a typed catch of System.Object--to work on
// all objects when the clause is in the low level runtime code. This special case is needed because
// objects from foreign type systems are sometimes throw back up at runtime code and this is the only way
// to catch them outside of having a filter with no type check in it, which isn't currently possible to
// write in C#. See https://github.com/dotnet/roslyn/issues/4388
if (pClauseType->IsEquivalentTo(s_pLowLevelObjectType))
return true;
return false;
}
private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart)
{
InvokeSecondPass(ref exInfo, idxStart, MaxTryRegionIdx);
}
private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart, uint idxLimit)
{
EHEnum ehEnum;
byte* pbMethodStartAddress;
if (!InternalCalls.RhpEHEnumInitFromStackFrameIterator(ref exInfo._frameIter, &pbMethodStartAddress, &ehEnum))
return;
byte* pbControlPC = exInfo._frameIter.ControlPC;
uint codeOffset = (uint)(pbControlPC - pbMethodStartAddress);
uint lastTryStart = 0, lastTryEnd = 0;
// Search the clauses for one that contains the current offset.
RhEHClause ehClause;
for (uint curIdx = 0; InternalCalls.RhpEHEnumNext(&ehEnum, &ehClause) && curIdx < idxLimit; curIdx++)
{
//
// Skip to the starting try region. This is used by collided unwinds and rethrows to pickup where
// the previous dispatch left off.
//
if (idxStart != MaxTryRegionIdx)
{
if (curIdx <= idxStart)
{
lastTryStart = ehClause._tryStartOffset; lastTryEnd = ehClause._tryEndOffset;
continue;
}
// Now, we continue skipping while the try region is identical to the one that invoked the
// previous dispatch.
if ((ehClause._tryStartOffset == lastTryStart) && (ehClause._tryEndOffset == lastTryEnd))
continue;
// We are done skipping. This is required to handle empty finally block markers that are used
// to separate runs of different try blocks with same native code offsets.
idxStart = MaxTryRegionIdx;
}
RhEHClauseKind clauseKind = ehClause._clauseKind;
if ((clauseKind != RhEHClauseKind.RH_EH_CLAUSE_FAULT)
|| !ehClause.ContainsCodeOffset(codeOffset))
{
continue;
}
// Found a containing clause. Because of the order of the clauses, we know this is the
// most containing.
// N.B. -- We need to suppress GC "in-between" calls to finallys in this loop because we do
// not have the correct next-execution point live on the stack and, therefore, may cause a GC
// hole if we allow a GC between invocation of finally funclets (i.e. after one has returned
// here to the dispatcher, but before the next one is invoked). Once they are running, it's
// fine for them to trigger a GC, obviously.
//
// As a result, RhpCallFinallyFunclet will set this state in the runtime upon return from the
// funclet, and we need to reset it if/when we fall out of the loop and we know that the
// method will no longer get any more GC callbacks.
byte* pFinallyHandler = ehClause._handlerAddress;
exInfo._idxCurClause = curIdx;
InternalCalls.RhpCallFinallyFunclet(pFinallyHandler, exInfo._frameIter.RegisterSet);
exInfo._idxCurClause = MaxTryRegionIdx;
}
}
[NativeCallable(EntryPoint = "RhpFailFastForPInvokeExceptionPreemp", CallingConvention = CallingConvention.Cdecl)]
public static void RhpFailFastForPInvokeExceptionPreemp(IntPtr PInvokeCallsiteReturnAddr, void* pExceptionRecord, void* pContextRecord)
{
FailFastViaClasslib(RhFailFastReason.PN_UnhandledExceptionFromPInvoke, null, PInvokeCallsiteReturnAddr);
}
[RuntimeExport("RhpFailFastForPInvokeExceptionCoop")]
public static void RhpFailFastForPInvokeExceptionCoop(IntPtr classlibBreadcrumb, void* pExceptionRecord, void* pContextRecord)
{
FailFastViaClasslib(RhFailFastReason.PN_UnhandledExceptionFromPInvoke, null, classlibBreadcrumb);
}
} // static class EH
}
| |
// 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.Runtime.InteropServices;
using System.Transactions.Distributed;
namespace System.Transactions
{
[ComImport]
[Guid("0fb15084-af41-11ce-bd2b-204c4f4f5020")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IDtcTransaction
{
void Commit(int retaining, [MarshalAs(UnmanagedType.I4)] int commitType, int reserved);
void Abort(IntPtr reason, int retaining, int async);
void GetTransactionInfo(IntPtr transactionInformation);
}
public static class TransactionInterop
{
internal static DistributedTransaction ConvertToDistributedTransaction(Transaction transaction)
{
if (null == transaction)
{
throw new ArgumentNullException(nameof(transaction));
}
if (transaction.Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (transaction._complete)
{
throw TransactionException.CreateTransactionCompletedException(transaction.DistributedTxId);
}
DistributedTransaction distributedTx = transaction.Promote();
if (distributedTx == null)
{
throw DistributedTransaction.NotSupported();
}
return distributedTx;
}
/// <summary>
/// This is the PromoterType value that indicates that the transaction is promoting to MSDTC.
///
/// If using the variation of Transaction.EnlistPromotableSinglePhase that takes a PromoterType and the
/// ITransactionPromoter being used promotes to MSDTC, then this is the value that should be
/// specified for the PromoterType parameter to EnlistPromotableSinglePhase.
///
/// If using the variation of Transaction.EnlistPromotableSinglePhase that assumes promotion to MSDTC and
/// it that returns false, the caller can compare this value with Transaction.PromoterType to
/// verify that the transaction promoted, or will promote, to MSDTC. If the Transaction.PromoterType
/// matches this value, then the caller can continue with its enlistment with MSDTC. But if it
/// does not match, the caller will not be able to enlist with MSDTC.
/// </summary>
public static readonly Guid PromoterTypeDtc = new Guid("14229753-FFE1-428D-82B7-DF73045CB8DA");
public static byte[] GetExportCookie(Transaction transaction, byte[] whereabouts)
{
if (null == transaction)
{
throw new ArgumentNullException(nameof(transaction));
}
if (null == whereabouts)
{
throw new ArgumentNullException(nameof(whereabouts));
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetExportCookie");
}
// Copy the whereabouts so that it cannot be modified later.
var whereaboutsCopy = new byte[whereabouts.Length];
Buffer.BlockCopy(whereabouts, 0, whereaboutsCopy, 0, whereabouts.Length);
DistributedTransaction dTx = ConvertToDistributedTransaction(transaction);
byte[] cookie = dTx.GetExportCookie(whereaboutsCopy);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetExportCookie");
}
return cookie;
}
public static Transaction GetTransactionFromExportCookie(byte[] cookie)
{
if (null == cookie)
{
throw new ArgumentNullException(nameof(cookie));
}
if (cookie.Length < 32)
{
throw new ArgumentException(SR.InvalidArgument, nameof(cookie));
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransactionFromExportCookie");
}
var cookieCopy = new byte[cookie.Length];
Buffer.BlockCopy(cookie, 0, cookieCopy, 0, cookie.Length);
cookie = cookieCopy;
// Extract the transaction guid from the propagation token to see if we already have a
// transaction object for the transaction.
byte[] guidByteArray = new byte[16];
for (int i = 0; i < guidByteArray.Length; i++)
{
// In a cookie, the transaction guid is preceeded by a signature guid.
guidByteArray[i] = cookie[i + 16];
}
Guid txId = new Guid(guidByteArray);
// First check to see if there is a promoted LTM transaction with the same ID. If there
// is, just return that.
Transaction transaction = TransactionManager.FindPromotedTransaction(txId);
if (transaction != null)
{
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransactionFromExportCookie");
}
return transaction;
}
// Find or create the promoted transaction.
DistributedTransaction dTx = DistributedTransactionManager.GetTransactionFromExportCookie(cookieCopy, txId);
transaction = TransactionManager.FindOrCreatePromotedTransaction(txId, dTx);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransactionFromExportCookie");
}
return transaction;
}
public static byte[] GetTransmitterPropagationToken(Transaction transaction)
{
if (null == transaction)
{
throw new ArgumentNullException(nameof(transaction));
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransmitterPropagationToken");
}
DistributedTransaction dTx = ConvertToDistributedTransaction(transaction);
byte[] token = dTx.GetTransmitterPropagationToken();
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransmitterPropagationToken");
}
return token;
}
public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken)
{
if (null == propagationToken)
{
throw new ArgumentNullException(nameof(propagationToken));
}
if (propagationToken.Length < 24)
{
throw new ArgumentException(SR.InvalidArgument, nameof(propagationToken));
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransactionFromTransmitterPropagationToken");
}
// Extract the transaction guid from the propagation token to see if we already have a
// transaction object for the transaction.
byte[] guidByteArray = new byte[16];
for (int i = 0; i < guidByteArray.Length; i++)
{
// In a propagation token, the transaction guid is preceeded by two version DWORDs.
guidByteArray[i] = propagationToken[i + 8];
}
var txId = new Guid(guidByteArray);
// First check to see if there is a promoted LTM transaction with the same ID. If there is, just return that.
Transaction tx = TransactionManager.FindPromotedTransaction(txId);
if (null != tx)
{
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransactionFromTransmitterPropagationToken");
}
return tx;
}
DistributedTransaction dTx = GetDistributedTransactionFromTransmitterPropagationToken(propagationToken);
// If a transaction is found then FindOrCreate will Dispose the distributed transaction created.
Transaction returnValue = TransactionManager.FindOrCreatePromotedTransaction(txId, dTx);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransactionFromTransmitterPropagationToken");
}
return returnValue;
}
public static IDtcTransaction GetDtcTransaction(Transaction transaction)
{
if (null == transaction)
{
throw new ArgumentNullException(nameof(transaction));
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetDtcTransaction");
}
DistributedTransaction dTx = ConvertToDistributedTransaction(transaction);
IDtcTransaction transactionNative = dTx.GetDtcTransaction();
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetDtcTransaction");
}
return transactionNative;
}
public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction transactionNative)
{
if (null == transactionNative)
{
throw new ArgumentNullException(nameof(transactionNative));
}
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransactionFromDtcTransaction");
}
Transaction transaction = DistributedTransactionManager.GetTransactionFromDtcTransaction(transactionNative);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransactionFromDtcTransaction");
}
return transaction;
}
public static byte[] GetWhereabouts()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetWhereabouts");
}
DistributedTransactionManager dTm = TransactionManager.DistributedTransactionManager;
byte[] returnValue = dTm.GetWhereabouts();
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetWhereabouts");
}
return returnValue;
}
internal static DistributedTransaction GetDistributedTransactionFromTransmitterPropagationToken(byte[] propagationToken)
{
if (null == propagationToken)
{
throw new ArgumentNullException(nameof(propagationToken));
}
if (propagationToken.Length < 24)
{
throw new ArgumentException(SR.InvalidArgument, nameof(propagationToken));
}
byte[] propagationTokenCopy = new byte[propagationToken.Length];
Array.Copy(propagationToken, propagationTokenCopy, propagationToken.Length);
return DistributedTransactionManager.GetDistributedTransactionFromTransmitterPropagationToken(propagationTokenCopy);
}
}
}
| |
//Engine r73
using System;
using System.Collections;
using Server.Network;
using Server.Gumps;
using System.Collections.Generic;
namespace Server.Mobiles
{
public class PremiumSpawnerGump : Gump
{
private PremiumSpawner m_Spawner;
public void AddBlackAlpha( int x, int y, int width, int height )
{
AddImageTiled( x, y, width, height, 2624 );
AddAlphaRegion( x, y, width, height );
}
public PremiumSpawnerGump( PremiumSpawner spawner ) : base( 50, 50 )
{
m_Spawner = spawner;
AddPage( 1 );
AddBackground( 0, 0, 350, 360, 5054 );
AddLabel( 80, 1, 52, "Creatures List 1" );
AddLabel( 215, 3, 52, "PREMIUM SPAWNER" );
AddBlackAlpha( 213, 23, 125, 270 );
AddButton( 260, 40, 0xFB7, 0xFB9, 1001, GumpButtonType.Reply, 0 );
AddLabel( 260, 60, 52, "Okay" );
AddButton( 260, 90, 0xFB4, 0xFB6, 200, GumpButtonType.Reply, 0 );
AddLabel( 232, 110, 52, "Bring to Home" );
AddButton( 260, 140, 0xFA8, 0xFAA, 300, GumpButtonType.Reply, 0 );
AddLabel( 232, 160, 52, "Total Respawn" );
AddButton( 260, 190, 0xFAB, 0xFAD, 400, GumpButtonType.Reply, 0 );
AddLabel( 245, 210, 52, "Properties" );
AddButton( 260, 240, 0xFB1, 0xFB3, 500, GumpButtonType.Reply, 0 );
AddLabel( 256, 260, 52, "Cancel" );
AddButton( 230, 320, 5603, 5607, 0, GumpButtonType.Page, 6 );
AddButton( 302, 320, 5601, 5605, 0, GumpButtonType.Page, 2 );
AddLabel( 258, 320, 52, "- 1 -" );
for ( int i = 0; i < 15; i++ )
{
// AddButton ( x, y, image, imageOnClick, ButtonID )
AddButton( 5, ( 22 * i ) + 20, 0xFA5, 0xFA7, (1 + i), GumpButtonType.Reply, 0 ); // > (spawn this creature)
AddButton( 38, ( 22 * i ) + 20, 0xFA2, 0xFA4, (91 + i), GumpButtonType.Reply, 0 ); // X (remove this creature)
AddImageTiled( 71, ( 22 * i ) + 20, 119, 23, 0xA40 );
AddImageTiled( 72, ( 22 * i ) + 21, 117, 21, 0xBBC );
string str = "";
if ( i < spawner.CreaturesName.Count )
{
str = (string)spawner.CreaturesName[i];
int count = m_Spawner.CountCreatures( str );
AddLabel( 192, ( 22 * i ) + 20, 0, count.ToString() );
}
AddTextEntry( 75, ( 22 * i ) + 21, 114, 21, 0, 101 + i, str );
}
AddPage( 2 );
AddBackground( 0, 0, 350, 360, 5054 );
AddLabel( 80, 1, 52, "Creatures List 2" );
AddLabel( 215, 3, 52, "PREMIUM SPAWNER" );
AddBlackAlpha( 213, 23, 125, 270 );
AddButton( 260, 40, 0xFB7, 0xFB9, 1002, GumpButtonType.Reply, 0 );
AddLabel( 260, 60, 52, "Okay" );
AddButton( 260, 90, 0xFB4, 0xFB6, 200, GumpButtonType.Reply, 0 );
AddLabel( 232, 110, 52, "Bring to Home" );
AddButton( 260, 140, 0xFA8, 0xFAA, 300, GumpButtonType.Reply, 0 );
AddLabel( 232, 160, 52, "Total Respawn" );
AddButton( 260, 190, 0xFAB, 0xFAD, 400, GumpButtonType.Reply, 0 );
AddLabel( 245, 210, 52, "Properties" );
AddButton( 260, 240, 0xFB1, 0xFB3, 500, GumpButtonType.Reply, 0 );
AddLabel( 256, 260, 52, "Cancel" );
AddButton( 230, 320, 5603, 5607, 0, GumpButtonType.Page, 1 );
AddButton( 302, 320, 5601, 5605, 0, GumpButtonType.Page, 3 );
AddLabel( 258, 320, 52, "- 2 -" );
for ( int i = 0; i < 15; i++ )
{
AddButton( 5, ( 22 * i ) + 20, 0xFA5, 0xFA7, (16 + i), GumpButtonType.Reply, 0 );
AddButton( 38, ( 22 * i ) + 20, 0xFA2, 0xFA4, (106 + i), GumpButtonType.Reply, 0 );
AddImageTiled( 71, ( 22 * i ) + 20, 119, 23, 0xA40 );
AddImageTiled( 72, ( 22 * i ) + 21, 117, 21, 0xBBC );
string str = "";
if ( i < spawner.SubSpawnerA.Count )
{
str = (string)spawner.SubSpawnerA[i];
int count = m_Spawner.CountCreaturesA( str );
AddLabel( 192, ( 22 * i ) + 20, 0, count.ToString() );
}
AddTextEntry( 75, ( 22 * i ) + 21, 114, 21, 0, 201 + i, str );
}
AddPage( 3 );
AddBackground( 0, 0, 350, 360, 5054 );
AddLabel( 80, 1, 52, "Creatures List 3" );
AddLabel( 215, 3, 52, "PREMIUM SPAWNER" );
AddBlackAlpha( 213, 23, 125, 270 );
AddButton( 260, 40, 0xFB7, 0xFB9, 1003, GumpButtonType.Reply, 0 );
AddLabel( 260, 60, 52, "Okay" );
AddButton( 260, 90, 0xFB4, 0xFB6, 200, GumpButtonType.Reply, 0 );
AddLabel( 232, 110, 52, "Bring to Home" );
AddButton( 260, 140, 0xFA8, 0xFAA, 300, GumpButtonType.Reply, 0 );
AddLabel( 232, 160, 52, "Total Respawn" );
AddButton( 260, 190, 0xFAB, 0xFAD, 400, GumpButtonType.Reply, 0 );
AddLabel( 245, 210, 52, "Properties" );
AddButton( 260, 240, 0xFB1, 0xFB3, 500, GumpButtonType.Reply, 0 );
AddLabel( 256, 260, 52, "Cancel" );
AddButton( 230, 320, 5603, 5607, 0, GumpButtonType.Page, 2 );
AddButton( 302, 320, 5601, 5605, 0, GumpButtonType.Page, 4 );
AddLabel( 258, 320, 52, "- 3 -" );
for ( int i = 0; i < 15; i++ )
{
AddButton( 5, ( 22 * i ) + 20, 0xFA5, 0xFA7, (31 + i), GumpButtonType.Reply, 0 );
AddButton( 38, ( 22 * i ) + 20, 0xFA2, 0xFA4, (121 + i), GumpButtonType.Reply, 0 );
AddImageTiled( 71, ( 22 * i ) + 20, 119, 23, 0xA40 );
AddImageTiled( 72, ( 22 * i ) + 21, 117, 21, 0xBBC );
string str = "";
if ( i < spawner.SubSpawnerB.Count )
{
str = (string)spawner.SubSpawnerB[i];
int count = m_Spawner.CountCreaturesB( str );
AddLabel( 192, ( 22 * i ) + 20, 0, count.ToString() );
}
AddTextEntry( 75, ( 22 * i ) + 21, 114, 21, 0, 301 + i, str );
}
AddPage( 4 );
AddBackground( 0, 0, 350, 360, 5054 );
AddLabel( 80, 1, 52, "Creatures List 4" );
AddLabel( 215, 3, 52, "PREMIUM SPAWNER" );
AddBlackAlpha( 213, 23, 125, 270 );
AddButton( 260, 40, 0xFB7, 0xFB9, 1004, GumpButtonType.Reply, 0 );
AddLabel( 260, 60, 52, "Okay" );
AddButton( 260, 90, 0xFB4, 0xFB6, 200, GumpButtonType.Reply, 0 );
AddLabel( 232, 110, 52, "Bring to Home" );
AddButton( 260, 140, 0xFA8, 0xFAA, 300, GumpButtonType.Reply, 0 );
AddLabel( 232, 160, 52, "Total Respawn" );
AddButton( 260, 190, 0xFAB, 0xFAD, 400, GumpButtonType.Reply, 0 );
AddLabel( 245, 210, 52, "Properties" );
AddButton( 260, 240, 0xFB1, 0xFB3, 500, GumpButtonType.Reply, 0 );
AddLabel( 256, 260, 52, "Cancel" );
AddButton( 230, 320, 5603, 5607, 0, GumpButtonType.Page, 3 );
AddButton( 302, 320, 5601, 5605, 0, GumpButtonType.Page, 5 );
AddLabel( 258, 320, 52, "- 4 -" );
for ( int i = 0; i < 15; i++ )
{
AddButton( 5, ( 22 * i ) + 20, 0xFA5, 0xFA7, (46 + i), GumpButtonType.Reply, 0 );
AddButton( 38, ( 22 * i ) + 20, 0xFA2, 0xFA4, (136 + i), GumpButtonType.Reply, 0 );
AddImageTiled( 71, ( 22 * i ) + 20, 119, 23, 0xA40 );
AddImageTiled( 72, ( 22 * i ) + 21, 117, 21, 0xBBC );
string str = "";
if ( i < spawner.SubSpawnerC.Count )
{
str = (string)spawner.SubSpawnerC[i];
int count = m_Spawner.CountCreaturesC( str );
AddLabel( 192, ( 22 * i ) + 20, 0, count.ToString() );
}
AddTextEntry( 75, ( 22 * i ) + 21, 114, 21, 0, 401 + i, str );
}
AddPage( 5 );
AddBackground( 0, 0, 350, 360, 5054 );
AddLabel( 80, 1, 52, "Creatures List 5" );
AddLabel( 215, 3, 52, "PREMIUM SPAWNER" );
AddBlackAlpha( 213, 23, 125, 270 );
AddButton( 260, 40, 0xFB7, 0xFB9, 1005, GumpButtonType.Reply, 0 );
AddLabel( 260, 60, 52, "Okay" );
AddButton( 260, 90, 0xFB4, 0xFB6, 200, GumpButtonType.Reply, 0 );
AddLabel( 232, 110, 52, "Bring to Home" );
AddButton( 260, 140, 0xFA8, 0xFAA, 300, GumpButtonType.Reply, 0 );
AddLabel( 232, 160, 52, "Total Respawn" );
AddButton( 260, 190, 0xFAB, 0xFAD, 400, GumpButtonType.Reply, 0 );
AddLabel( 245, 210, 52, "Properties" );
AddButton( 260, 240, 0xFB1, 0xFB3, 500, GumpButtonType.Reply, 0 );
AddLabel( 256, 260, 52, "Cancel" );
AddButton( 230, 320, 5603, 5607, 0, GumpButtonType.Page, 4 );
AddButton( 302, 320, 5601, 5605, 0, GumpButtonType.Page, 6 );
AddLabel( 258, 320, 52, "- 5 -" );
for ( int i = 0; i < 15; i++ )
{
AddButton( 5, ( 22 * i ) + 20, 0xFA5, 0xFA7, (61 + i), GumpButtonType.Reply, 0 );
AddButton( 38, ( 22 * i ) + 20, 0xFA2, 0xFA4, (151 + i), GumpButtonType.Reply, 0 );
AddImageTiled( 71, ( 22 * i ) + 20, 119, 23, 0xA40 );
AddImageTiled( 72, ( 22 * i ) + 21, 117, 21, 0xBBC );
string str = "";
if ( i < spawner.SubSpawnerD.Count )
{
str = (string)spawner.SubSpawnerD[i];
int count = m_Spawner.CountCreaturesD( str );
AddLabel( 192, ( 22 * i ) + 20, 0, count.ToString() );
}
AddTextEntry( 75, ( 22 * i ) + 21, 114, 21, 0, 501 + i, str );
}
AddPage( 6 );
AddBackground( 0, 0, 350, 360, 5054 );
AddLabel( 80, 1, 52, "Creatures List 6" );
AddLabel( 215, 3, 52, "PREMIUM SPAWNER" );
AddBlackAlpha( 213, 23, 125, 270 );
AddButton( 260, 40, 0xFB7, 0xFB9, 1006, GumpButtonType.Reply, 0 );
AddLabel( 260, 60, 52, "Okay" );
AddButton( 260, 90, 0xFB4, 0xFB6, 200, GumpButtonType.Reply, 0 );
AddLabel( 232, 110, 52, "Bring to Home" );
AddButton( 260, 140, 0xFA8, 0xFAA, 300, GumpButtonType.Reply, 0 );
AddLabel( 232, 160, 52, "Total Respawn" );
AddButton( 260, 190, 0xFAB, 0xFAD, 400, GumpButtonType.Reply, 0 );
AddLabel( 245, 210, 52, "Properties" );
AddButton( 260, 240, 0xFB1, 0xFB3, 500, GumpButtonType.Reply, 0 );
AddLabel( 256, 260, 52, "Cancel" );
AddButton( 230, 320, 5603, 5607, 0, GumpButtonType.Page, 5 );
AddButton( 302, 320, 5601, 5605, 0, GumpButtonType.Page, 1 );
AddLabel( 258, 320, 52, "- 6 -" );
for ( int i = 0; i < 15; i++ )
{
AddButton( 5, ( 22 * i ) + 20, 0xFA5, 0xFA7, (76 + i), GumpButtonType.Reply, 0 );
AddButton( 38, ( 22 * i ) + 20, 0xFA2, 0xFA4, (166 + i), GumpButtonType.Reply, 0 );
AddImageTiled( 71, ( 22 * i ) + 20, 119, 23, 0xA40 );
AddImageTiled( 72, ( 22 * i ) + 21, 117, 21, 0xBBC );
string str = "";
if ( i < spawner.SubSpawnerE.Count )
{
str = (string)spawner.SubSpawnerE[i];
int count = m_Spawner.CountCreaturesE( str );
AddLabel( 192, ( 22 * i ) + 20, 0, count.ToString() );
}
AddTextEntry( 75, ( 22 * i ) + 21, 114, 21, 0, 601 + i, str );
}
}
public List<string> CreateArray( RelayInfo info, Mobile from, int TextIndex )
{
List<string> creaturesName = new List<string>();
for ( int i = 0; i < 15; i++ )
{
TextRelay te = info.GetTextEntry( TextIndex + i );
if ( te != null )
{
string str = te.Text;
if ( str.Length > 0 )
{
str = str.Trim();
string t = Spawner.ParseType( str );
Type type = ScriptCompiler.FindTypeByName( t );
if ( type != null )
creaturesName.Add( str );
else
from.SendMessage( "{0} is not a valid type name.", t );
}
}
}
return creaturesName;
}
public string GetEntry( int Type, RelayInfo info )
{
TextRelay entry = info.GetTextEntry( Type );
return entry.Text;
}
public override void OnResponse( NetState state, RelayInfo info )
{
if ( m_Spawner.Deleted )
return;
switch ( info.ButtonID )
{
case 0: // Cancel (mouse's right button click anywhere on the gump)
{
break;
}
case 200: // Bring everything home
{
m_Spawner.BringToHome();
break;
}
case 300: // Complete respawn
{
m_Spawner.Respawn();
break;
}
case 400: // Props
{
state.Mobile.SendGump( new PropertiesGump( state.Mobile, m_Spawner ) );
state.Mobile.SendGump( new PremiumSpawnerGump( m_Spawner ) );
break;
}
case 500: // Cancel (button "Cancel")
{
break;
}
case 1001: // Okay
{
m_Spawner.CreaturesName = CreateArray( info, state.Mobile, 100 );
break;
}
case 1002: // Okay
{
m_Spawner.SubSpawnerA = CreateArray( info, state.Mobile, 200 );
break;
}
case 1003: // Okay
{
m_Spawner.SubSpawnerB = CreateArray( info, state.Mobile, 300 );
break;
}
case 1004: // Okay
{
m_Spawner.SubSpawnerC = CreateArray( info, state.Mobile, 400 );
break;
}
case 1005: // Okay
{
m_Spawner.SubSpawnerD = CreateArray( info, state.Mobile, 500 );
break;
}
case 1006: // Okay
{
m_Spawner.SubSpawnerE = CreateArray( info, state.Mobile, 600 );
break;
}
default:
{ //ButtonID: 1-90 spawn; 91-180 remove
int ID = info.ButtonID;
int Type = 0;
// Spawn creature
if ( (ID >= 1) && (ID <= 15) )
{
Type += 100 + ID;
m_Spawner.Spawn( GetEntry(Type, info) );
}
else if ( (ID >= 16) && (ID <= 30) )
{
Type += 200 + ID - 15;
m_Spawner.SpawnA( GetEntry(Type, info) );
}
else if ( (ID >= 31) && (ID <= 45) )
{
Type += 300 + ID - 30;
m_Spawner.SpawnB( GetEntry(Type, info) );
}
else if ( (ID >= 46) && (ID <= 60) )
{
Type += 400 + ID - 45;
m_Spawner.SpawnC( GetEntry(Type, info) );
}
else if ( (ID >= 61) && (ID <= 75) )
{
Type += 500 + ID - 60;
m_Spawner.SpawnD( GetEntry(Type, info) );
}
else if ( (ID >= 76) && (ID <= 90) )
{
Type += 600 + ID - 75;
m_Spawner.SpawnE( GetEntry(Type, info) );
}
// Remove creature
else if ( (ID >= 91) && (ID <= 105) )
{
Type += 100 + ID - 90;
m_Spawner.RemoveCreatures( GetEntry(Type, info) );
}
else if ( (ID >= 106) && (ID <= 120) )
{
Type += 200 + ID - 105;
m_Spawner.RemoveCreaturesA( GetEntry(Type, info) );
}
else if ( (ID >= 121) && (ID <= 135) )
{
Type += 300 + ID - 120;
m_Spawner.RemoveCreaturesB( GetEntry(Type, info) );
}
else if ( (ID >= 136) && (ID <= 150) )
{
Type += 400 + ID - 135;
m_Spawner.RemoveCreaturesC( GetEntry(Type, info) );
}
else if ( (ID >= 151) && (ID <= 165) )
{
Type += 500 + ID - 150;
m_Spawner.RemoveCreaturesD( GetEntry(Type, info) );
}
else if ( (ID >= 166) && (ID <= 180) )
{
Type += 600 + ID - 165;
m_Spawner.RemoveCreaturesE( GetEntry(Type, info) );
}
string entry = GetEntry(Type, info);
if ( entry != null && entry.Length > 0 )
{
m_Spawner.CreaturesName = CreateArray( info, state.Mobile, 100 );
m_Spawner.SubSpawnerA = CreateArray( info, state.Mobile, 200 );
m_Spawner.SubSpawnerB = CreateArray( info, state.Mobile, 300 );
m_Spawner.SubSpawnerC = CreateArray( info, state.Mobile, 400 );
m_Spawner.SubSpawnerD = CreateArray( info, state.Mobile, 500 );
m_Spawner.SubSpawnerE = CreateArray( info, state.Mobile, 600 );
}
break;
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.