context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
namespace Meziantou.Framework;
public class DefaultConverter : IConverter
{
private const string HexaChars = "0123456789ABCDEF";
private static readonly MethodInfo s_enumTryParseMethodInfo = GetEnumTryParseMethodInfo();
public ByteArrayToStringFormat ByteArrayToStringFormat { get; set; } = ByteArrayToStringFormat.Base64;
private static MethodInfo GetEnumTryParseMethodInfo()
{
// Enum.TryParse<T>(string value, bool ignoreCase, out T value)
return typeof(Enum)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.First(m => string.Equals(m.Name, nameof(Enum.TryParse), StringComparison.Ordinal) && m.IsGenericMethod && m.GetParameters().Length == 3);
}
public virtual bool TryChangeType(object? input, Type conversionType, IFormatProvider? provider, out object? value)
{
return TryConvert(input, conversionType, provider, out value);
}
private static byte GetHexaByte(char c)
{
if ((c >= '0') && (c <= '9'))
return (byte)(c - '0');
if ((c >= 'A') && (c <= 'F'))
return (byte)(c - 'A' + 10);
if ((c >= 'a') && (c <= 'f'))
return (byte)(c - 'a' + 10);
return 0xFF;
}
private static bool NormalizeHexString(ref string? s)
{
if (s == null)
return false;
if (s.Length > 0)
{
if (s[0] == 'x' || s[0] == 'X')
{
s = s[1..];
return true;
}
if (s.Length > 1)
{
if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
{
s = s[2..];
return true;
}
}
}
return false;
}
private static void GetBytes(decimal d, IList<byte> buffer)
{
var ints = decimal.GetBits(d);
buffer[0] = (byte)ints[0];
buffer[1] = (byte)(ints[0] >> 8);
buffer[2] = (byte)(ints[0] >> 0x10);
buffer[3] = (byte)(ints[0] >> 0x18);
buffer[4] = (byte)ints[1];
buffer[5] = (byte)(ints[1] >> 8);
buffer[6] = (byte)(ints[1] >> 0x10);
buffer[7] = (byte)(ints[1] >> 0x18);
buffer[8] = (byte)ints[2];
buffer[9] = (byte)(ints[2] >> 8);
buffer[10] = (byte)(ints[2] >> 0x10);
buffer[11] = (byte)(ints[2] >> 0x18);
buffer[12] = (byte)ints[3];
buffer[13] = (byte)(ints[3] >> 8);
buffer[14] = (byte)(ints[3] >> 0x10);
buffer[15] = (byte)(ints[3] >> 0x18);
}
private static bool IsNumberType(Type type)
{
if (type == null)
return false;
return type == typeof(int) || type == typeof(long) || type == typeof(short) ||
type == typeof(uint) || type == typeof(ulong) || type == typeof(ushort) ||
type == typeof(bool) || type == typeof(double) || type == typeof(float) ||
type == typeof(decimal) || type == typeof(byte) || type == typeof(sbyte);
}
private static bool IsNullOrEmptyString(object? input)
{
if (input == null)
return true;
if (input is string s)
return string.IsNullOrWhiteSpace(s);
return false;
}
private static bool EnumTryParse(Type type, string? input, out object? value)
{
var mi = s_enumTryParseMethodInfo.MakeGenericMethod(type);
object?[] args = { input, true, Enum.ToObject(type, 0) };
var b = (bool)mi.Invoke(null, args)!;
value = args[2];
return b;
}
private static string ToHexa(byte[]? bytes)
{
if (bytes == null)
return string.Empty;
return ToHexa(bytes, 0, bytes.Length);
}
private static string ToHexa(byte[]? bytes, int offset, int count)
{
if (bytes == null)
return string.Empty;
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), offset, message: null);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), count, message: null);
if (offset >= bytes.Length)
return string.Empty;
count = Math.Min(count, bytes.Length - offset);
var sb = new StringBuilder(count * 2);
for (var i = offset; i < offset + count; i++)
{
sb.Append(HexaChars[bytes[i] / 16]);
sb.Append(HexaChars[bytes[i] % 16]);
}
return sb.ToString();
}
private static byte[]? FromHexa(string hex)
{
var list = new List<byte>();
var lo = false;
byte prev = 0;
var offset = IsHexPrefix(hex) ? 2 : 0; // handle 0x or 0X notation
for (var i = 0; i < hex.Length - offset; i++)
{
var c = hex[i + offset];
if (c == '-')
continue;
var b = GetHexaByte(c);
if (b == 0xFF)
return null;
if (lo)
{
list.Add((byte)((prev * 16) + b));
}
else
{
prev = b;
}
lo = !lo;
}
return list.ToArray();
}
protected virtual bool TryConvert(byte[] input, IFormatProvider? provider, [NotNullWhen(returnValue: true)] out string? value)
{
switch (ByteArrayToStringFormat)
{
case ByteArrayToStringFormat.Base16:
value = ToHexa(input);
return true;
case ByteArrayToStringFormat.Base16Prefixed:
value = "0x" + ToHexa(input);
return true;
case ByteArrayToStringFormat.Base64:
value = Convert.ToBase64String(input);
return true;
}
value = default;
return false;
}
protected virtual bool TryConvert(TimeSpan input, IFormatProvider? provider, [NotNullWhen(returnValue: true)] out byte[]? value)
{
value = BitConverter.GetBytes(input.Ticks);
return true;
}
protected virtual bool TryConvert(Guid input, IFormatProvider? provider, [NotNullWhen(returnValue: true)] out byte[]? value)
{
value = input.ToByteArray();
return true;
}
protected virtual bool TryConvert(DateTime input, IFormatProvider? provider, [NotNullWhen(returnValue: true)] out byte[]? value)
{
value = BitConverter.GetBytes(input.ToBinary());
return true;
}
protected virtual bool TryConvert(decimal input, IFormatProvider? provider, [NotNullWhen(returnValue: true)] out byte[]? value)
{
var decBytes = new byte[16];
GetBytes(input, decBytes);
value = decBytes;
return true;
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, [NotNullWhen(returnValue: true)] out byte[]? value)
{
byte[]? bytes;
if (input is Guid guid)
{
if (TryConvert(guid, provider, out bytes))
{
value = bytes;
return true;
}
value = null;
return false;
}
if (input is DateTimeOffset dateTimeOffset && TryConvert(dateTimeOffset.DateTime, provider, out var result))
{
value = result;
return true;
}
if (input is TimeSpan timeSpan)
{
if (TryConvert(timeSpan, provider, out bytes))
{
value = bytes;
return true;
}
value = null;
return false;
}
value = null;
return false;
}
protected virtual bool TryConvertEnum(object? input, Type conversionType, IFormatProvider? provider, out object? value)
{
return EnumTryParse(conversionType, Convert.ToString(input, provider), out value);
}
protected virtual bool TryConvert(string? text, IFormatProvider? provider, out byte[]? value)
{
if (text == null)
{
value = null;
return true;
}
if (!IsHexPrefix(text))
{
try
{
value = Convert.FromBase64String(text);
return true;
}
catch
{
// the value is invalid, continue with other methods
}
}
var bytes = FromHexa(text);
if (bytes != null)
{
value = bytes;
return true;
}
value = null;
return false;
}
private static bool IsHexPrefix(string text)
{
return text.Length >= 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X');
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out CultureInfo? value)
{
if (input == null)
{
value = null;
return true;
}
if (input is string name)
{
// On Linux any name seems to be valid. If the name is a LCID, skip it.
if (int.TryParse(name, NumberStyles.Integer, CultureInfo.InvariantCulture, out var i))
return TryConvert(i, provider, out value);
try
{
value = CultureInfo.GetCultureInfo(name);
return true;
}
catch (CultureNotFoundException)
{
}
}
if (input is int lcid)
{
if (TryConvert(lcid, provider, out value))
return true;
}
value = null;
return false;
}
protected virtual bool TryConvert(int lcid, IFormatProvider? provider, [NotNullWhen(returnValue: true)] out CultureInfo? value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
value = CultureInfo.GetCultureInfo(lcid);
return true;
}
catch (CultureNotFoundException)
{
}
}
value = null;
return false;
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out DateTimeOffset value)
{
if (DateTimeOffset.TryParse(Convert.ToString(input, provider), provider, DateTimeStyles.None, out value))
return true;
if (TryConvert(input, provider, out DateTime dt))
{
value = new DateTimeOffset(dt);
return true;
}
value = DateTimeOffset.MinValue;
return false;
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out TimeSpan value)
{
if (TimeSpan.TryParse(Convert.ToString(input, provider), provider, out value))
return true;
value = TimeSpan.Zero;
return false;
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out Guid value)
{
if (IsNullOrEmptyString(input))
{
value = Guid.Empty;
return false;
}
if (input is byte[] inputBytes)
{
if (inputBytes.Length != 16)
{
value = Guid.Empty;
return false;
}
value = new Guid(inputBytes);
return true;
}
return Guid.TryParse(Convert.ToString(input, provider), out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out ulong value)
{
if (IsNullOrEmptyString(input))
{
value = 0;
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToUInt64(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return ulong.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out ushort value)
{
if (IsNullOrEmptyString(input))
{
value = 0;
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToUInt16(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return ushort.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out decimal value)
{
if (IsNullOrEmptyString(input))
{
value = 0;
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToDecimal(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return decimal.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out float value)
{
if (IsNullOrEmptyString(input))
{
value = 0;
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToSingle(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return float.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out double value)
{
if (IsNullOrEmptyString(input))
{
value = 0d;
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToDouble(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return double.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out char value)
{
if (IsNullOrEmptyString(input))
{
value = '\0';
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToChar(provider);
return true;
}
catch
{
}
}
}
var s = Convert.ToString(input, provider);
return char.TryParse(s, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out DateTime value)
{
if (IsNullOrEmptyString(input))
{
value = DateTime.MinValue;
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToDateTime(provider);
return true;
}
catch
{
}
}
}
var s = Convert.ToString(input, provider);
return DateTime.TryParse(s, provider, DateTimeStyles.None, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out uint value)
{
if (IsNullOrEmptyString(input))
{
value = 0;
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToUInt32(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return uint.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out byte value)
{
if (IsNullOrEmptyString(input))
{
value = 0;
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToByte(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return byte.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out sbyte value)
{
if (IsNullOrEmptyString(input))
{
value = 0;
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToSByte(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return sbyte.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out short value)
{
if (IsNullOrEmptyString(input))
{
value = 0;
return false;
}
value = 0;
if (input is byte[] inputBytes)
{
if (inputBytes.Length == 2)
{
value = BitConverter.ToInt16(inputBytes, 0);
return true;
}
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToInt16(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return short.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out int value)
{
if (IsNullOrEmptyString(input))
{
value = 0;
return false;
}
value = 0;
if (input is byte[] inputBytes)
{
if (inputBytes.Length == 4)
{
value = BitConverter.ToInt32(inputBytes, 0);
return true;
}
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToInt32(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return int.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out long value)
{
if (IsNullOrEmptyString(input))
{
value = 0;
return false;
}
value = 0;
if (input is byte[] inputBytes)
{
if (inputBytes.Length == 8)
{
value = BitConverter.ToInt64(inputBytes, 0);
return true;
}
return false;
}
if (input is not string)
{
if (input is IConvertible ic)
{
try
{
value = ic.ToInt64(provider);
return true;
}
catch
{
}
}
}
var styles = NumberStyles.Integer;
var s = Convert.ToString(input, provider);
if (NormalizeHexString(ref s))
{
styles |= NumberStyles.AllowHexSpecifier;
}
return long.TryParse(s, styles, provider, out value);
}
protected virtual bool TryConvert(object? input, IFormatProvider? provider, out bool value)
{
value = false;
if (input is byte[] inputBytes)
{
if (inputBytes.Length == 1)
{
value = BitConverter.ToBoolean(inputBytes, 0);
return true;
}
return false;
}
if (TryConvert(input, typeof(long), provider, out var b))
{
value = (long)b! != 0;
return true;
}
var bools = Convert.ToString(input, provider);
if (bools == null)
return false; // arguable...
bools = bools.Trim().ToUpperInvariant();
if (string.Equals(bools, "Y", StringComparison.Ordinal) ||
string.Equals(bools, "YES", StringComparison.Ordinal) ||
string.Equals(bools, "T", StringComparison.Ordinal) ||
bools.StartsWith("TRUE", StringComparison.Ordinal))
{
value = true;
return true;
}
return string.Equals(bools, "N", StringComparison.Ordinal) ||
string.Equals(bools, "NO", StringComparison.Ordinal) ||
string.Equals(bools, "F", StringComparison.Ordinal) ||
bools.StartsWith("FALSE", StringComparison.Ordinal);
}
protected virtual bool TryConvert(object? input, Type conversionType!!, IFormatProvider? provider, out object? value)
{
if (conversionType == typeof(object))
{
value = input;
return true;
}
if (input == null || Convert.IsDBNull(input))
{
if (conversionType.IsNullableOfT())
{
value = null;
return true;
}
if (conversionType.IsValueType)
{
value = Activator.CreateInstance(conversionType);
return false;
}
value = null;
return true;
}
var inputType = input.GetType();
if (conversionType.IsAssignableFrom(inputType.GetTypeInfo()))
{
value = input;
return true;
}
if (conversionType.IsNullableOfT())
{
// en empty string is successfully converted into a nullable
var inps = input as string;
if (string.IsNullOrWhiteSpace(inps))
{
value = null;
return true;
}
var vtType = Nullable.GetUnderlyingType(conversionType);
if (vtType != null && TryConvert(input, vtType, provider, out var vtValue))
{
var nt = typeof(Nullable<>).MakeGenericType(vtType);
value = Activator.CreateInstance(nt, vtValue);
return true;
}
value = null;
return false;
}
// enum must be before integers
if (conversionType.IsEnum)
{
if (TryConvertEnum(input, conversionType, provider, out value))
return true;
}
var conversionCode = Type.GetTypeCode(conversionType);
switch (conversionCode)
{
case TypeCode.Boolean:
bool boolValue;
if (TryConvert(input, provider, out boolValue))
{
value = boolValue;
return true;
}
break;
case TypeCode.Byte:
byte byteValue;
if (TryConvert(input, provider, out byteValue))
{
value = byteValue;
return true;
}
break;
case TypeCode.Char:
char charValue;
if (TryConvert(input, provider, out charValue))
{
value = charValue;
return true;
}
break;
case TypeCode.DateTime:
DateTime dtValue;
if (TryConvert(input, provider, out dtValue))
{
value = dtValue;
return true;
}
break;
case TypeCode.Decimal:
decimal decValue;
if (TryConvert(input, provider, out decValue))
{
value = decValue;
return true;
}
break;
case TypeCode.Double:
double dblValue;
if (TryConvert(input, provider, out dblValue))
{
value = dblValue;
return true;
}
break;
case TypeCode.Int16:
short i16Value;
if (TryConvert(input, provider, out i16Value))
{
value = i16Value;
return true;
}
break;
case TypeCode.Int32:
int i32Value;
if (TryConvert(input, provider, out i32Value))
{
value = i32Value;
return true;
}
break;
case TypeCode.Int64:
long i64Value;
if (TryConvert(input, provider, out i64Value))
{
value = i64Value;
return true;
}
break;
case TypeCode.SByte:
sbyte sbyteValue;
if (TryConvert(input, provider, out sbyteValue))
{
value = sbyteValue;
return true;
}
break;
case TypeCode.Single:
float fltValue;
if (TryConvert(input, provider, out fltValue))
{
value = fltValue;
return true;
}
break;
case TypeCode.String:
if (input is byte[] inputBytes)
{
if (TryConvert(inputBytes, provider, out var str))
{
value = str;
return true;
}
value = null;
return false;
}
if (input is CultureInfo ci)
{
value = ci.Name;
return true;
}
var tc = TypeDescriptor.GetConverter(inputType);
if (tc != null && tc.CanConvertTo(typeof(string)))
{
value = (string?)tc.ConvertTo(input, typeof(string));
return true;
}
value = Convert.ToString(input, provider);
return true;
case TypeCode.UInt16:
ushort u16Value;
if (TryConvert(input, provider, out u16Value))
{
value = u16Value;
return true;
}
break;
case TypeCode.UInt32:
uint u32Value;
if (TryConvert(input, provider, out u32Value))
{
value = u32Value;
return true;
}
break;
case TypeCode.UInt64:
ulong u64Value;
if (TryConvert(input, provider, out u64Value))
{
value = u64Value;
return true;
}
break;
case TypeCode.Object:
if (conversionType == typeof(Guid))
{
if (TryConvert(input, provider, out Guid gValue))
{
value = gValue;
return true;
}
}
else if (conversionType == typeof(CultureInfo))
{
if (TryConvert(input, provider, out CultureInfo? cultureInfo))
{
value = cultureInfo;
return true;
}
value = null;
return false;
}
else if (conversionType == typeof(DateTimeOffset))
{
if (TryConvert(input, provider, out DateTimeOffset dto))
{
value = dto;
return true;
}
}
else if (conversionType == typeof(TimeSpan))
{
if (TryConvert(input, provider, out TimeSpan ts))
{
value = ts;
return true;
}
}
else if (conversionType == typeof(byte[]))
{
byte[]? bytes;
var inputCode = Type.GetTypeCode(inputType);
switch (inputCode)
{
case TypeCode.DBNull:
value = null;
return true;
case TypeCode.Boolean:
value = BitConverter.GetBytes((bool)input);
return true;
case TypeCode.Char:
value = BitConverter.GetBytes((char)input);
return true;
case TypeCode.Double:
value = BitConverter.GetBytes((double)input);
return true;
case TypeCode.Int16:
value = BitConverter.GetBytes((short)input);
return true;
case TypeCode.Int32:
value = BitConverter.GetBytes((int)input);
return true;
case TypeCode.Int64:
value = BitConverter.GetBytes((long)input);
return true;
case TypeCode.Single:
value = BitConverter.GetBytes((float)input);
return true;
case TypeCode.UInt16:
value = BitConverter.GetBytes((ushort)input);
return true;
case TypeCode.UInt32:
value = BitConverter.GetBytes((uint)input);
return true;
case TypeCode.UInt64:
value = BitConverter.GetBytes((ulong)input);
return true;
case TypeCode.Byte:
value = new[] { (byte)input };
return true;
case TypeCode.DateTime:
if (TryConvert((DateTime)input, provider, out bytes))
{
value = bytes;
return true;
}
value = null;
return false;
case TypeCode.Decimal:
if (TryConvert((decimal)input, provider, out bytes))
{
value = bytes;
return true;
}
value = null;
return false;
case TypeCode.SByte:
value = new[] { unchecked((byte)input) };
return true;
case TypeCode.String:
if (TryConvert((string)input, provider, out bytes))
{
value = bytes;
return true;
}
value = null;
return false;
default:
if (TryConvert(input, provider, out bytes))
{
value = bytes;
return true;
}
break;
}
}
break;
}
// catch many exceptions before they happen
if (IsNumberType(conversionType) && IsNullOrEmptyString(input))
{
value = Activator.CreateInstance(conversionType);
return false;
}
TypeConverter? ctConverter = null;
try
{
ctConverter = TypeDescriptor.GetConverter(conversionType);
if (ctConverter != null && ctConverter.CanConvertFrom(inputType))
{
if (provider is CultureInfo cultureInfo)
{
value = ctConverter.ConvertFrom(context: null, cultureInfo, input);
}
else
{
value = ctConverter.ConvertFrom(input);
}
return true;
}
}
catch
{
// do nothing
}
try
{
var inputConverter = TypeDescriptor.GetConverter(inputType);
if (inputConverter != null && inputConverter.CanConvertTo(conversionType))
{
value = inputConverter.ConvertTo(context: null, provider as CultureInfo, input, conversionType);
return true;
}
}
catch
{
// do nothing
}
var defaultValue = conversionType.IsValueType ? Activator.CreateInstance(conversionType) : null;
try
{
if (ctConverter != null && input is not string && ctConverter.CanConvertFrom(typeof(string)))
{
value = ctConverter.ConvertFrom(context: null, provider as CultureInfo, Convert.ToString(input, provider)!);
return true;
}
}
catch
{
// do nothing
}
if (TryConvertUsingImplicitConverter(input, conversionType, provider, out value))
return true;
value = defaultValue;
return false;
}
protected virtual bool TryConvertUsingImplicitConverter(object? input, Type conversionType, IFormatProvider? provider, out object? value)
{
var op = ReflectionUtilities.GetImplicitConversion(input, conversionType);
if (op == null)
{
value = default;
return false;
}
value = op.Invoke(null, new object?[] { input });
return true;
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Orleans.Metadata;
using Orleans.Runtime;
using Orleans.Utilities;
namespace Orleans
{
/// <summary>
/// Associates <see cref="GrainInterfaceType"/>s with a compatible <see cref="GrainType"/>.
/// </summary>
/// <remarks>
/// This is primarily intended for end-users calling <see cref="IGrainFactory"/> methods without needing to be overly explicit.
/// </remarks>
public class GrainInterfaceTypeToGrainTypeResolver
{
private readonly object _lockObj = new object();
private readonly ConcurrentDictionary<GrainInterfaceType, GrainType> _genericMapping = new ConcurrentDictionary<GrainInterfaceType, GrainType>();
private readonly IClusterManifestProvider _clusterManifestProvider;
private Cache _cache;
public GrainInterfaceTypeToGrainTypeResolver(IClusterManifestProvider clusterManifestProvider)
{
_clusterManifestProvider = clusterManifestProvider;
}
/// <summary>
/// Returns the <see cref="GrainType"/> which supports the provided <see cref="GrainInterfaceType"/> and which has an implementing type name beginning with the provided prefix string.
/// </summary>
public GrainType GetGrainType(GrainInterfaceType interfaceType, string prefix)
{
if (string.IsNullOrWhiteSpace(prefix))
{
return GetGrainType(interfaceType);
}
GrainType result = default;
GrainInterfaceType lookupType;
if (GenericGrainInterfaceType.TryParse(interfaceType, out var genericInterface))
{
lookupType = genericInterface.GetGenericGrainType().Value;
}
else
{
lookupType = interfaceType;
}
var cache = GetCache();
if (cache.Map.TryGetValue(lookupType, out var entry))
{
var hasCandidate = false;
foreach (var impl in entry.Implementations)
{
if (impl.Prefix.StartsWith(prefix, StringComparison.Ordinal))
{
if (impl.Prefix.Length == prefix.Length)
{
// Exact matches take precedence
result = impl.GrainType;
break;
}
if (hasCandidate)
{
var candidates = string.Join(", ", entry.Implementations.Select(i => $"{i.GrainType} ({i.Prefix})"));
throw new ArgumentException($"Unable to identify a single appropriate grain type for interface {interfaceType} with implementation prefix \"{prefix}\". Candidates: {candidates}");
}
result = impl.GrainType;
hasCandidate = true;
}
}
}
if (result.IsDefault)
{
throw new ArgumentException($"Could not find an implementation matching prefix \"{prefix}\" for interface {interfaceType}");
}
if (GenericGrainType.TryParse(result, out var genericGrainType) && !genericGrainType.IsConstructed)
{
result = genericGrainType.GrainType.GetConstructed(genericInterface.Value);
}
return result;
}
/// <summary>
/// Returns a <see cref="GrainType"/> which implements the provided <see cref="GrainInterfaceType"/>.
/// </summary>
public GrainType GetGrainType(GrainInterfaceType interfaceType)
{
GrainType result = default;
var cache = GetCache();
if (cache.Map.TryGetValue(interfaceType, out var entry))
{
if (!entry.PrimaryImplementation.IsDefault)
{
result = entry.PrimaryImplementation;
}
else if (entry.Implementations.Count == 1)
{
result = entry.Implementations[0].GrainType;
}
else if (entry.Implementations.Count > 1)
{
var candidates = string.Join(", ", entry.Implementations.Select(i => $"{i.GrainType} ({i.Prefix})"));
throw new ArgumentException($"Unable to identify a single appropriate grain type for interface {interfaceType}. Candidates: {candidates}");
}
else
{
// No implementations
}
}
else if (_genericMapping.TryGetValue(interfaceType, out result))
{
}
else if (GenericGrainInterfaceType.TryParse(interfaceType, out var genericInterface))
{
var unconstructedInterface = genericInterface.GetGenericGrainType();
var unconstructed = GetGrainType(unconstructedInterface.Value);
if (GenericGrainType.TryParse(unconstructed, out var genericGrainType))
{
if (genericGrainType.IsConstructed)
{
result = genericGrainType.GrainType;
}
else
{
result = genericGrainType.GrainType.GetConstructed(genericInterface.Value);
}
}
else
{
result = unconstructed;
}
_genericMapping[interfaceType] = result;
}
if (result.IsDefault)
{
throw new ArgumentException($"Could not find an implementation for interface {interfaceType}");
}
return result;
}
private Cache GetCache()
{
if (_cache is Cache cache && cache.Version == _clusterManifestProvider.Current.Version)
{
return cache;
}
lock (_lockObj)
{
var manifest = _clusterManifestProvider.Current;
cache = _cache;
if (cache is object && cache.Version == manifest.Version)
{
return cache;
}
return _cache = BuildCache(manifest);
}
}
private static Cache BuildCache(ClusterManifest clusterManifest)
{
var result = new Dictionary<GrainInterfaceType, CacheEntry>();
foreach (var manifest in clusterManifest.AllGrainManifests)
{
GrainType knownPrimary = default;
foreach (var grainInterface in manifest.Interfaces)
{
var id = grainInterface.Key;
if (grainInterface.Value.Properties.TryGetValue(WellKnownGrainInterfaceProperties.DefaultGrainType, out var defaultTypeString))
{
knownPrimary = GrainType.Create(defaultTypeString);
continue;
}
}
foreach (var grainType in manifest.Grains)
{
var id = grainType.Key;
grainType.Value.Properties.TryGetValue(WellKnownGrainTypeProperties.TypeName, out var typeName);
grainType.Value.Properties.TryGetValue(WellKnownGrainTypeProperties.FullTypeName, out var fullTypeName);
foreach (var property in grainType.Value.Properties)
{
if (!property.Key.StartsWith(WellKnownGrainTypeProperties.ImplementedInterfacePrefix, StringComparison.Ordinal)) continue;
var implemented = GrainInterfaceType.Create(property.Value);
string interfaceTypeName;
if (manifest.Interfaces.TryGetValue(implemented, out var interfaceProperties))
{
interfaceProperties.Properties.TryGetValue(WellKnownGrainInterfaceProperties.TypeName, out interfaceTypeName);
}
else
{
interfaceTypeName = null;
}
// Try to work out the best primary implementation
result.TryGetValue(implemented, out var entry);
GrainType primaryImplementation;
if (!knownPrimary.IsDefault)
{
primaryImplementation = knownPrimary;
}
else if (!entry.PrimaryImplementation.IsDefault)
{
primaryImplementation = entry.PrimaryImplementation;
}
else if (string.Equals(interfaceTypeName?.Substring(1), typeName, StringComparison.Ordinal))
{
primaryImplementation = id;
}
else
{
primaryImplementation = default;
}
var implementations = entry.Implementations ?? new List<(string Prefix, GrainType GrainType)>();
if (!implementations.Contains((fullTypeName, id))) implementations.Add((fullTypeName, id));
result[implemented] = new CacheEntry(primaryImplementation, implementations);
}
}
}
return new Cache(clusterManifest.Version, result);
}
private class Cache
{
public Cache(MajorMinorVersion version, Dictionary<GrainInterfaceType, CacheEntry> map)
{
this.Version = version;
this.Map = map;
}
public MajorMinorVersion Version { get; }
public Dictionary<GrainInterfaceType, CacheEntry> Map { get; }
}
private readonly struct CacheEntry
{
public CacheEntry(GrainType primaryImplementation, List<(string Prefix, GrainType GrainType)> implementations)
{
this.PrimaryImplementation = primaryImplementation;
this.Implementations = implementations;
}
public GrainType PrimaryImplementation { get; }
public List<(string Prefix, GrainType GrainType)> Implementations { get; }
}
}
}
| |
// 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.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
using static System.Linq.Expressions.Expression;
namespace System.Linq.Expressions.Tests
{
public class UnaryQuoteTests
{
[Theory, ClassData(typeof(CompilationTypes))]
public void QuotePreservesTypingOfBlock(bool useInterpreter)
{
ParameterExpression x = Parameter(typeof(int));
Expression<Func<int, Type>> f1 =
Lambda<Func<int, Type>>(
Call(
typeof(UnaryQuoteTests).GetMethod(nameof(Quote1)),
Lambda(
Block(typeof(void), x)
)
),
x
);
Assert.Equal(typeof(void), f1.Compile(useInterpreter)(42));
ParameterExpression s = Parameter(typeof(string));
Expression<Func<string, Type>> f2 =
Lambda<Func<string, Type>>(
Call(
typeof(UnaryQuoteTests).GetMethod(nameof(Quote2)),
Lambda(
Block(typeof(object), s)
)
),
s
);
Assert.Equal(typeof(object), f2.Compile(useInterpreter)("bar"));
}
public static Type Quote1(Expression<Action> e) => e.Body.Type;
public static Type Quote2(Expression<Func<object>> e) => e.Body.Type;
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_Lambda_Action(bool useInterpreter)
{
Expression<Func<LambdaExpression>> f = () => GetQuote<Action>(() => Nop());
var quote = f.Compile(useInterpreter)();
Assert.Equal(0, quote.Parameters.Count);
Assert.Equal(ExpressionType.Call, quote.Body.NodeType);
var call = (MethodCallExpression)quote.Body;
Assert.Equal(typeof(UnaryQuoteTests).GetMethod(nameof(Nop)), call.Method);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_Lambda_Action_MakeUnary(bool useInterpreter)
{
Expression<Action> e = () => Nop();
UnaryExpression q = MakeUnary(ExpressionType.Quote, e, null);
Expression<Func<LambdaExpression>> f = Lambda<Func<LambdaExpression>>(q);
var quote = f.Compile(useInterpreter)();
Assert.Equal(0, quote.Parameters.Count);
Assert.Equal(ExpressionType.Call, quote.Body.NodeType);
var call = (MethodCallExpression)quote.Body;
Assert.Equal(typeof(UnaryQuoteTests).GetMethod(nameof(Nop)), call.Method);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_Lambda_IdentityFunc(bool useInterpreter)
{
Expression<Func<LambdaExpression>> f = () => GetQuote<Func<int, int>>(x => x);
var quote = f.Compile(useInterpreter)();
Assert.Equal(1, quote.Parameters.Count);
Assert.Same(quote.Body, quote.Parameters[0]);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_Lambda_Closure1(bool useInterpreter)
{
Expression<Func<int, LambdaExpression>> f = x => GetQuote<Func<int>>(() => x);
var quote = f.Compile(useInterpreter)(42);
Assert.Equal(0, quote.Parameters.Count);
AssertIsBox(quote.Body, 42, useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_Lambda_Closure2(bool useInterpreter)
{
// Using an unchecked addition to ensure that an Add expression is used (and not AddChecked)
Expression<Func<int, Func<int, LambdaExpression>>> f = x => y => GetQuote<Func<int>>(() => unchecked(x + y));
var quote = f.Compile(useInterpreter)(1)(2);
Assert.Equal(0, quote.Parameters.Count);
Assert.Equal(ExpressionType.Add, quote.Body.NodeType);
var add = (BinaryExpression)quote.Body;
AssertIsBox(add.Left, 1, useInterpreter);
AssertIsBox(add.Right, 2, useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_Block_Action(bool useInterpreter)
{
var expr =
Block(
Call(typeof(UnaryQuoteTests).GetMethod(nameof(Nop)))
);
var f = BuildQuote<Func<LambdaExpression>, Action>(expr);
var quote = f.Compile(useInterpreter)();
Assert.Equal(0, quote.Parameters.Count);
Assert.Same(expr, quote.Body);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_Block_Local(bool useInterpreter)
{
var x = Parameter(typeof(int));
var expr =
Block(
new[] { x },
Assign(x, Constant(42)),
x
);
var f = BuildQuote<Func<LambdaExpression>, Func<int>>(expr);
var quote = f.Compile(useInterpreter)();
Assert.Equal(0, quote.Parameters.Count);
Assert.Same(expr, quote.Body);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_Block_Local_Shadow(bool useInterpreter)
{
var x = Parameter(typeof(int));
var expr =
Block(
new[] { x },
Assign(x, Constant(42)),
x
);
var f = BuildQuote<Func<int, LambdaExpression>, Func<int>>(expr, x);
var quote = f.Compile(useInterpreter)(43);
Assert.Equal(0, quote.Parameters.Count);
Assert.Same(expr, quote.Body);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_Block_Closure(bool useInterpreter)
{
var x = Parameter(typeof(int));
var expr =
Block(
x
);
var f = BuildQuote<Func<int, LambdaExpression>, Func<int>>(expr, x);
var quote = f.Compile(useInterpreter)(42);
Assert.Equal(0, quote.Parameters.Count);
var block = quote.Body as BlockExpression;
Assert.NotNull(block);
Assert.Equal(0, block.Variables.Count);
Assert.Equal(1, block.Expressions.Count);
AssertIsBox(block.Expressions[0], 42, useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_Block_LocalAndClosure(bool useInterpreter)
{
var x = Parameter(typeof(int));
var y = Parameter(typeof(int));
var expr =
Block(
new[] { y },
Assign(y, Constant(2)),
Add(
x,
y
)
);
var f = BuildQuote<Func<int, LambdaExpression>, Func<int>>(expr, x);
var quote = f.Compile(useInterpreter)(1);
Assert.Equal(0, quote.Parameters.Count);
var block = quote.Body as BlockExpression;
Assert.NotNull(block);
Assert.Equal(1, block.Variables.Count);
Assert.Same(y, block.Variables[0]);
Assert.Equal(2, block.Expressions.Count);
Assert.Same(block.Expressions[0], expr.Expressions[0]);
var expr1 = block.Expressions[1];
Assert.Equal(ExpressionType.Add, expr1.NodeType);
var add = (BinaryExpression)expr1;
AssertIsBox(add.Left, 1, useInterpreter);
Assert.Same(y, add.Right);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_CatchBlock_Local(bool useInterpreter)
{
var ex = Parameter(typeof(Exception));
var expr =
TryCatch(
Empty(),
Catch(
ex,
Empty()
)
);
var f = BuildQuote<Func<LambdaExpression>, Action>(expr);
var quote = f.Compile(useInterpreter)();
Assert.Equal(0, quote.Parameters.Count);
Assert.Same(expr, quote.Body);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_CatchBlock_Variable_Closure1(bool useInterpreter)
{
var x = Parameter(typeof(int));
var ex = Parameter(typeof(Exception));
var expr =
TryCatch(
x,
Catch(
ex,
Constant(0)
)
);
var f = BuildQuote<Func<int, LambdaExpression>, Func<int>>(expr, x);
var quote = f.Compile(useInterpreter)(42);
Assert.Equal(0, quote.Parameters.Count);
var @try = quote.Body as TryExpression;
Assert.NotNull(@try);
AssertIsBox(@try.Body, 42, useInterpreter);
Assert.Null(@try.Fault);
Assert.Null(@try.Finally);
Assert.NotNull(@try.Handlers);
Assert.Equal(1, @try.Handlers.Count);
var handler = @try.Handlers[0];
Assert.Same(expr.Handlers[0], handler);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_CatchBlock_Variable_Closure2(bool useInterpreter)
{
var x = Parameter(typeof(int));
var ex = Parameter(typeof(Exception));
var expr =
TryCatch(
Constant(0),
Catch(
ex,
x
)
);
var f = BuildQuote<Func<int, LambdaExpression>, Func<int>>(expr, x);
var quote = f.Compile(useInterpreter)(42);
Assert.Equal(0, quote.Parameters.Count);
var @try = quote.Body as TryExpression;
Assert.NotNull(@try);
Assert.Same(expr.Body, @try.Body);
Assert.Null(@try.Fault);
Assert.Null(@try.Finally);
Assert.NotNull(@try.Handlers);
Assert.Equal(1, @try.Handlers.Count);
var handler = @try.Handlers[0];
Assert.Null(handler.Filter);
Assert.Same(ex, handler.Variable);
AssertIsBox(@handler.Body, 42, useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_CatchBlock_NoVariable_Closure1(bool useInterpreter)
{
var x = Parameter(typeof(int));
var expr =
TryCatch(
x,
Catch(
typeof(Exception),
Constant(0)
)
);
var f = BuildQuote<Func<int, LambdaExpression>, Func<int>>(expr, x);
var quote = f.Compile(useInterpreter)(42);
Assert.Equal(0, quote.Parameters.Count);
var @try = quote.Body as TryExpression;
Assert.NotNull(@try);
AssertIsBox(@try.Body, 42, useInterpreter);
Assert.Null(@try.Fault);
Assert.Null(@try.Finally);
Assert.NotNull(@try.Handlers);
Assert.Equal(1, @try.Handlers.Count);
var handler = @try.Handlers[0];
Assert.Same(expr.Handlers[0], handler);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_CatchBlock_NoVariable_Closure2(bool useInterpreter)
{
var x = Parameter(typeof(int));
var expr =
TryCatch(
Constant(0),
Catch(
typeof(Exception),
x
)
);
var f = BuildQuote<Func<int, LambdaExpression>, Func<int>>(expr, x);
var quote = f.Compile(useInterpreter)(42);
Assert.Equal(0, quote.Parameters.Count);
var @try = quote.Body as TryExpression;
Assert.NotNull(@try);
Assert.Same(expr.Body, @try.Body);
Assert.Null(@try.Fault);
Assert.Null(@try.Finally);
Assert.NotNull(@try.Handlers);
Assert.Equal(1, @try.Handlers.Count);
var handler = @try.Handlers[0];
Assert.Null(handler.Filter);
Assert.Null(handler.Variable);
AssertIsBox(@handler.Body, 42, useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_RuntimeVariables_Closure(bool useInterpreter)
{
var x = Parameter(typeof(int));
var expr =
RuntimeVariables(
x
);
var f = BuildQuote<Func<int, Expression<Func<IRuntimeVariables>>>, Func<IRuntimeVariables>>(expr, x);
var quote = f.Compile(useInterpreter)(42);
var vars = quote.Compile(useInterpreter)();
Assert.Equal(1, vars.Count);
Assert.Equal(42, vars[0]);
vars[0] = 43;
Assert.Equal(43, vars[0]);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_RuntimeVariables_Local(bool useInterpreter)
{
var x = Parameter(typeof(int));
var expr =
Block(
new[] { x },
Assign(x, Constant(42)),
RuntimeVariables(
x
)
);
var f = BuildQuote<Func<Expression<Func<IRuntimeVariables>>>, Func<IRuntimeVariables>>(expr);
var quote = f.Compile(useInterpreter)();
var vars = quote.Compile(useInterpreter)();
Assert.Equal(1, vars.Count);
Assert.Equal(42, vars[0]);
vars[0] = 43;
Assert.Equal(43, vars[0]);
}
[Theory, ClassData(typeof(CompilationTypes))]
public void Quote_RuntimeVariables_ClosureAndLocal(bool useInterpreter)
{
var x = Parameter(typeof(int));
var y = Parameter(typeof(int));
var expr =
Block(
new[] { y },
Assign(y, Constant(2)),
RuntimeVariables(
x,
y
)
);
var f = BuildQuote<Func<int, Expression<Func<IRuntimeVariables>>>, Func<IRuntimeVariables>>(expr, x);
var quote = f.Compile(useInterpreter)(1);
var vars = quote.Compile(useInterpreter)();
Assert.Equal(2, vars.Count);
Assert.Equal(1, vars[0]);
Assert.Equal(2, vars[1]);
vars[0] = 3;
vars[1] = 4;
Assert.Equal(3, vars[0]);
Assert.Equal(4, vars[1]);
}
[Fact]
public void NullLambda()
{
AssertExtensions.Throws<ArgumentNullException>("expression", () => Quote(null));
}
[Fact]
public void QuoteNonLamdba()
{
Func<int> zero = () => 0;
Expression funcConst = Constant(zero);
AssertExtensions.Throws<ArgumentException>("expression", () => Quote(funcConst));
}
[Fact]
public void CannotReduce()
{
Expression<Func<int>> exp = () => 2;
Expression q = Expression.Quote(exp);
Assert.False(q.CanReduce);
Assert.Same(q, q.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => q.ReduceAndCheck());
}
[Fact]
public void TypeExplicitWithGeneralLambdaArgument()
{
LambdaExpression lambda = Lambda(Constant(2));
Expression q = Quote(lambda);
Assert.Equal(typeof(Expression<Func<int>>), q.Type);
}
private void AssertIsBox<T>(Expression expression, T value, bool isInterpreted)
{
if (isInterpreted)
{
// See https://github.com/dotnet/corefx/issues/11097 for the difference between
// runtime expression quoting in the compiler and the interpreter.
Assert.Equal(ExpressionType.Convert, expression.NodeType);
var convert = (UnaryExpression)expression;
Assert.Equal(typeof(T), convert.Type);
AssertBox<object>(convert.Operand, value);
}
else
{
AssertBox(expression, value);
}
}
private void AssertBox<T>(Expression expression, T value)
{
Assert.Equal(ExpressionType.MemberAccess, expression.NodeType);
var member = (MemberExpression)expression;
var field = member.Member as FieldInfo;
Assert.NotNull(field);
Assert.Equal(typeof(StrongBox<T>).GetField(nameof(StrongBox<T>.Value)), field);
var constant = member.Expression as ConstantExpression;
Assert.NotNull(constant);
var box = constant.Value as StrongBox<T>;
Assert.NotNull(box);
Assert.Equal(value, box.Value);
}
private static Expression<TDelegate> BuildQuote<TDelegate, TQuoteType>(Expression body, params ParameterExpression[] parameters)
{
var expr =
Lambda<TDelegate>(
Call(
typeof(UnaryQuoteTests).GetMethod(nameof(GetQuote)).MakeGenericMethod(typeof(TQuoteType)),
Quote(
Lambda<TQuoteType>(body)
)
),
parameters
);
return expr;
}
public static Expression<T> GetQuote<T>(Expression<T> e) => e;
#pragma warning disable xUnit1013 // needs to be public for reflection-based test
public static void Nop() { }
#pragma warning restore xUnit1013
}
}
| |
// 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 System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public partial class NetworkStreamTest
{
[Fact]
public async Task ReadWrite_Span_Success()
{
await RunWithConnectedNetworkStreamsAsync((server, client) =>
{
var clientData = new byte[] { 42 };
client.Write((ReadOnlySpan<byte>)clientData);
var serverData = new byte[clientData.Length];
Assert.Equal(serverData.Length, server.Read((Span<byte>)serverData));
Assert.Equal(clientData, serverData);
return Task.CompletedTask;
});
}
[Fact]
public async Task ReadWrite_Memory_Success()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
var clientData = new byte[] { 42 };
await client.WriteAsync((ReadOnlyMemory<byte>)clientData);
var serverData = new byte[clientData.Length];
Assert.Equal(serverData.Length, await server.ReadAsync((Memory<byte>)serverData));
Assert.Equal(clientData, serverData);
});
}
[Fact]
public async Task ReadWrite_Memory_LargeWrite_Success()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
var writeBuffer = new byte[10 * 1024 * 1024];
var readBuffer = new byte[writeBuffer.Length];
RandomNumberGenerator.Fill(writeBuffer);
ValueTask writeTask = client.WriteAsync((ReadOnlyMemory<byte>)writeBuffer);
int totalRead = 0;
while (totalRead < readBuffer.Length)
{
int bytesRead = await server.ReadAsync(new Memory<byte>(readBuffer).Slice(totalRead));
Assert.InRange(bytesRead, 0, int.MaxValue);
if (bytesRead == 0)
{
break;
}
totalRead += bytesRead;
}
Assert.Equal(readBuffer.Length, totalRead);
Assert.Equal<byte>(writeBuffer, readBuffer);
await writeTask;
});
}
[Fact]
public async Task ReadWrite_Precanceled_Throws()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await server.WriteAsync((ArraySegment<byte>)new byte[0], new CancellationToken(true)));
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await server.ReadAsync((ArraySegment<byte>)new byte[0], new CancellationToken(true)));
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await server.WriteAsync((ReadOnlyMemory<byte>)new byte[0], new CancellationToken(true)));
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await server.ReadAsync((Memory<byte>)new byte[0], new CancellationToken(true)));
});
}
[Fact]
public async Task ReadAsync_AwaitMultipleTimes_Throws()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
var b = new byte[1];
ValueTask<int> r = server.ReadAsync(b);
await client.WriteAsync(new byte[] { 42 });
Assert.Equal(1, await r);
Assert.Equal(42, b[0]);
await Assert.ThrowsAsync<InvalidOperationException>(async () => await r);
Assert.Throws<InvalidOperationException>(() => r.GetAwaiter().IsCompleted);
Assert.Throws<InvalidOperationException>(() => r.GetAwaiter().OnCompleted(() => { }));
Assert.Throws<InvalidOperationException>(() => r.GetAwaiter().GetResult());
});
}
[Fact]
public async Task ReadAsync_MultipleContinuations_Throws()
{
await RunWithConnectedNetworkStreamsAsync((server, client) =>
{
var b = new byte[1];
ValueTask<int> r = server.ReadAsync(b);
r.GetAwaiter().OnCompleted(() => { });
Assert.Throws<InvalidOperationException>(() => r.GetAwaiter().OnCompleted(() => { }));
return Task.CompletedTask;
});
}
[Fact]
public async Task ReadAsync_MultipleConcurrentValueTaskReads_Success()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
// Technically this isn't supported behavior, but it happens to work because it's supported on socket.
// So validate it to alert us to any potential future breaks.
byte[] b1 = new byte[1], b2 = new byte[1], b3 = new byte[1];
ValueTask<int> r1 = server.ReadAsync(b1);
ValueTask<int> r2 = server.ReadAsync(b2);
ValueTask<int> r3 = server.ReadAsync(b3);
await client.WriteAsync(new byte[] { 42, 43, 44 });
Assert.Equal(3, await r1 + await r2 + await r3);
Assert.Equal(42 + 43 + 44, b1[0] + b2[0] + b3[0]);
});
}
[Fact]
public async Task ReadAsync_MultipleConcurrentValueTaskReads_AsTask_Success()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
// Technically this isn't supported behavior, but it happens to work because it's supported on socket.
// So validate it to alert us to any potential future breaks.
byte[] b1 = new byte[1], b2 = new byte[1], b3 = new byte[1];
Task<int> r1 = server.ReadAsync((Memory<byte>)b1).AsTask();
Task<int> r2 = server.ReadAsync((Memory<byte>)b2).AsTask();
Task<int> r3 = server.ReadAsync((Memory<byte>)b3).AsTask();
await client.WriteAsync(new byte[] { 42, 43, 44 });
Assert.Equal(3, await r1 + await r2 + await r3);
Assert.Equal(42 + 43 + 44, b1[0] + b2[0] + b3[0]);
});
}
[Fact]
public async Task WriteAsync_MultipleConcurrentValueTaskWrites_Success()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
// Technically this isn't supported behavior, but it happens to work because it's supported on socket.
// So validate it to alert us to any potential future breaks.
ValueTask s1 = server.WriteAsync(new ReadOnlyMemory<byte>(new byte[] { 42 }));
ValueTask s2 = server.WriteAsync(new ReadOnlyMemory<byte>(new byte[] { 43 }));
ValueTask s3 = server.WriteAsync(new ReadOnlyMemory<byte>(new byte[] { 44 }));
byte[] b1 = new byte[1], b2 = new byte[1], b3 = new byte[1];
Assert.Equal(3,
await client.ReadAsync((Memory<byte>)b1) +
await client.ReadAsync((Memory<byte>)b2) +
await client.ReadAsync((Memory<byte>)b3));
await s1;
await s2;
await s3;
Assert.Equal(42 + 43 + 44, b1[0] + b2[0] + b3[0]);
});
}
[Fact]
public async Task WriteAsync_MultipleConcurrentValueTaskWrites_AsTask_Success()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
// Technically this isn't supported behavior, but it happens to work because it's supported on socket.
// So validate it to alert us to any potential future breaks.
Task s1 = server.WriteAsync(new ReadOnlyMemory<byte>(new byte[] { 42 })).AsTask();
Task s2 = server.WriteAsync(new ReadOnlyMemory<byte>(new byte[] { 43 })).AsTask();
Task s3 = server.WriteAsync(new ReadOnlyMemory<byte>(new byte[] { 44 })).AsTask();
byte[] b1 = new byte[1], b2 = new byte[1], b3 = new byte[1];
Task<int> r1 = client.ReadAsync((Memory<byte>)b1).AsTask();
Task<int> r2 = client.ReadAsync((Memory<byte>)b2).AsTask();
Task<int> r3 = client.ReadAsync((Memory<byte>)b3).AsTask();
await Task.WhenAll(s1, s2, s3, r1, r2, r3);
Assert.Equal(3, await r1 + await r2 + await r3);
Assert.Equal(42 + 43 + 44, b1[0] + b2[0] + b3[0]);
});
}
public static IEnumerable<object[]> ReadAsync_ContinuesOnCurrentContextIfDesired_MemberData() =>
from flowExecutionContext in new[] { true, false }
from continueOnCapturedContext in new bool?[] { null, false, true }
select new object[] { flowExecutionContext, continueOnCapturedContext };
[Theory]
[MemberData(nameof(ReadAsync_ContinuesOnCurrentContextIfDesired_MemberData))]
public async Task ReadAsync_ContinuesOnCurrentSynchronizationContextIfDesired(
bool flowExecutionContext, bool? continueOnCapturedContext)
{
await Task.Run(async () => // escape xunit sync ctx
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
Assert.Null(SynchronizationContext.Current);
var continuationRan = new TaskCompletionSource<bool>();
var asyncLocal = new AsyncLocal<int>();
bool schedulerWasFlowed = false;
bool executionContextWasFlowed = false;
Action continuation = () =>
{
schedulerWasFlowed = SynchronizationContext.Current is CustomSynchronizationContext;
executionContextWasFlowed = 42 == asyncLocal.Value;
continuationRan.SetResult(true);
};
var readBuffer = new byte[1];
ValueTask<int> readValueTask = client.ReadAsync((Memory<byte>)new byte[1]);
SynchronizationContext.SetSynchronizationContext(new CustomSynchronizationContext());
asyncLocal.Value = 42;
switch (continueOnCapturedContext)
{
case null:
if (flowExecutionContext)
{
readValueTask.GetAwaiter().OnCompleted(continuation);
}
else
{
readValueTask.GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
default:
if (flowExecutionContext)
{
readValueTask.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(continuation);
}
else
{
readValueTask.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
}
asyncLocal.Value = 0;
SynchronizationContext.SetSynchronizationContext(null);
Assert.False(readValueTask.IsCompleted);
Assert.False(readValueTask.IsCompletedSuccessfully);
await server.WriteAsync(new byte[] { 42 });
await continuationRan.Task;
Assert.True(readValueTask.IsCompleted);
Assert.True(readValueTask.IsCompletedSuccessfully);
Assert.Equal(continueOnCapturedContext != false, schedulerWasFlowed);
Assert.Equal(flowExecutionContext, executionContextWasFlowed);
});
});
}
[Theory]
[MemberData(nameof(ReadAsync_ContinuesOnCurrentContextIfDesired_MemberData))]
public async Task ReadAsync_ContinuesOnCurrentTaskSchedulerIfDesired(
bool flowExecutionContext, bool? continueOnCapturedContext)
{
await Task.Run(async () => // escape xunit sync ctx
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
Assert.Null(SynchronizationContext.Current);
var continuationRan = new TaskCompletionSource<bool>();
var asyncLocal = new AsyncLocal<int>();
bool schedulerWasFlowed = false;
bool executionContextWasFlowed = false;
Action continuation = () =>
{
schedulerWasFlowed = TaskScheduler.Current is CustomTaskScheduler;
executionContextWasFlowed = 42 == asyncLocal.Value;
continuationRan.SetResult(true);
};
var readBuffer = new byte[1];
ValueTask<int> readValueTask = client.ReadAsync((Memory<byte>)new byte[1]);
await Task.Factory.StartNew(() =>
{
Assert.IsType<CustomTaskScheduler>(TaskScheduler.Current);
asyncLocal.Value = 42;
switch (continueOnCapturedContext)
{
case null:
if (flowExecutionContext)
{
readValueTask.GetAwaiter().OnCompleted(continuation);
}
else
{
readValueTask.GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
default:
if (flowExecutionContext)
{
readValueTask.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(continuation);
}
else
{
readValueTask.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().UnsafeOnCompleted(continuation);
}
break;
}
asyncLocal.Value = 0;
}, CancellationToken.None, TaskCreationOptions.None, new CustomTaskScheduler());
Assert.False(readValueTask.IsCompleted);
Assert.False(readValueTask.IsCompletedSuccessfully);
await server.WriteAsync(new byte[] { 42 });
await continuationRan.Task;
Assert.True(readValueTask.IsCompleted);
Assert.True(readValueTask.IsCompletedSuccessfully);
Assert.Equal(continueOnCapturedContext != false, schedulerWasFlowed);
Assert.Equal(flowExecutionContext, executionContextWasFlowed);
});
});
}
[Fact]
public async Task DisposeAsync_ClosesStream()
{
await RunWithConnectedNetworkStreamsAsync(async (server, client) =>
{
Assert.True(client.DisposeAsync().IsCompletedSuccessfully);
Assert.True(server.DisposeAsync().IsCompletedSuccessfully);
await client.DisposeAsync();
await server.DisposeAsync();
Assert.False(server.CanRead);
Assert.False(server.CanWrite);
Assert.False(client.CanRead);
Assert.False(client.CanWrite);
});
}
private sealed class CustomSynchronizationContext : SynchronizationContext
{
public override void Post(SendOrPostCallback d, object state)
{
ThreadPool.QueueUserWorkItem(delegate
{
SetSynchronizationContext(this);
try
{
d(state);
}
finally
{
SetSynchronizationContext(null);
}
}, null);
}
}
private sealed class CustomTaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task) => ThreadPool.QueueUserWorkItem(_ => TryExecuteTask(task));
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => false;
protected override IEnumerable<Task> GetScheduledTasks() => null;
}
}
}
| |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2013, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*/
using System;
using System.Web;
using System.Xml;
using System.Globalization;
using System.Collections;
using System.Text.RegularExpressions;
namespace CKFinder.Connector.CommandHandlers
{
internal class CopyFilesCommandHandler : XmlCommandHandlerBase
{
private XmlNode ErrorsNode;
public CopyFilesCommandHandler()
: base()
{
}
private void appendErrorNode( int errorCode, string name, string type, string path )
{
if ( this.ErrorsNode == null )
this.ErrorsNode = XmlUtil.AppendElement( this.ConnectorNode, "Errors" );
XmlNode Error = XmlUtil.AppendElement( this.ErrorsNode, "Error" );
XmlUtil.SetAttribute( Error, "code", errorCode.ToString() );
XmlUtil.SetAttribute( Error, "name", name );
XmlUtil.SetAttribute( Error, "type", type );
XmlUtil.SetAttribute( Error, "folder", path );
}
protected override void BuildXml()
{
if ( Request.Form["CKFinderCommand"] != "true" )
{
ConnectorException.Throw( Errors.InvalidRequest );
}
if ( !this.CurrentFolder.CheckAcl( AccessControlRules.FileRename | AccessControlRules.FileUpload | AccessControlRules.FileDelete ) )
{
ConnectorException.Throw( Errors.Unauthorized );
}
if ( Request.Form["files[0][type]"] == null )
{
ConnectorException.Throw( Errors.InvalidRequest );
}
int copied = 0;
int copiedAll = 0;
if ( Request.Form["copied"] != null )
{
copiedAll = Int32.Parse(Request.Form["copied"]);
}
Settings.ResourceType resourceType;
Hashtable resourceTypeConfig = new Hashtable();
Hashtable checkedPaths = new Hashtable();
int iFileNum = 0;
while ( Request.Form["files[" + iFileNum.ToString() + "][type]"] != null && Request.Form["files[" + iFileNum.ToString() + "][type]"].Length > 0 )
{
string name = Request.Form["files[" + iFileNum.ToString() + "][name]"];
string type = Request.Form["files[" + iFileNum.ToString() + "][type]"];
string path = Request.Form["files[" + iFileNum.ToString() + "][folder]"];
string options = "";
if ( name == null || name.Length < 1 || type == null || type.Length < 1 || path == null || path.Length < 1 )
{
ConnectorException.Throw( Errors.InvalidRequest );
return;
}
if ( Request.Form["files[" + iFileNum.ToString() + "][options]"] != null )
{
options = Request.Form["files[" + iFileNum.ToString() + "][options]"];
}
iFileNum++;
// check #1 (path)
if ( !Connector.CheckFileName( name ) || Regex.IsMatch( path, @"(/\.)|(\.\.)|(//)|([\\:\*\?""\<\>\|])" ) )
{
ConnectorException.Throw( Errors.InvalidRequest );
return;
}
// get resource type config for current file
if ( !resourceTypeConfig.ContainsKey( type ) )
{
resourceTypeConfig[type] = Config.Current.GetResourceTypeConfig( type );
}
// check #2 (resource type)
if ( resourceTypeConfig[type] == null )
{
ConnectorException.Throw( Errors.InvalidRequest );
return;
}
resourceType = (Settings.ResourceType)resourceTypeConfig[type];
FolderHandler folder = new FolderHandler( type, path );
string sourceFilePath = System.IO.Path.Combine( folder.ServerPath, name );
// check #3 (extension)
if ( !resourceType.CheckExtension( System.IO.Path.GetExtension( name ) ) )
{
this.appendErrorNode( Errors.InvalidExtension, name, type, path );
continue;
}
// check #4 (extension) - when moving to another resource type, double check extension
if ( this.CurrentFolder.ResourceTypeName != type )
{
if ( !this.CurrentFolder.ResourceTypeInfo.CheckExtension( System.IO.Path.GetExtension( name ) ) )
{
this.appendErrorNode( Errors.InvalidExtension, name, type, path );
continue;
}
}
// check #5 (hidden folders)
if ( !checkedPaths.ContainsKey( path ) )
{
checkedPaths[path] = true;
if ( Config.Current.CheckIsHidenPath( path ) )
{
ConnectorException.Throw( Errors.InvalidRequest );
return;
}
}
// check #6 (hidden file name)
if ( Config.Current.CheckIsHiddenFile( name ) )
{
ConnectorException.Throw( Errors.InvalidRequest );
return;
}
// check #7 (Access Control, need file view permission to source files)
if ( !folder.CheckAcl( AccessControlRules.FileView ) )
{
ConnectorException.Throw( Errors.Unauthorized );
return;
}
// check #8 (invalid file name)
if ( !System.IO.File.Exists( sourceFilePath ) || System.IO.Directory.Exists( sourceFilePath ) )
{
this.appendErrorNode( Errors.FileNotFound, name, type, path );
continue;
}
// check #9 (max size)
if ( this.CurrentFolder.ResourceTypeName != type )
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo( sourceFilePath );
if ( this.CurrentFolder.ResourceTypeInfo.MaxSize > 0 && fileInfo.Length > this.CurrentFolder.ResourceTypeInfo.MaxSize )
{
this.appendErrorNode( Errors.UploadedTooBig, name, type, path );
continue;
}
}
string destinationFilePath = System.IO.Path.Combine( this.CurrentFolder.ServerPath, name );
// finally, no errors so far, we may attempt to copy a file
// protection against copying files to itself
if ( sourceFilePath == destinationFilePath )
{
this.appendErrorNode( Errors.SourceAndTargetPathEqual, name, type, path );
continue;
}
// check if file exists if we don't force overwriting
else if ( System.IO.File.Exists( destinationFilePath ) && !options.Contains( "overwrite" ) )
{
if ( options.Contains( "autorename" ) )
{
int iCounter = 1;
string fileName;
string sFileNameNoExt = CKFinder.Connector.Util.GetFileNameWithoutExtension( name );
string sFullExtension = CKFinder.Connector.Util.GetExtension( name );
while ( true )
{
fileName = sFileNameNoExt + "(" + iCounter.ToString() + ")" + sFullExtension;
destinationFilePath = System.IO.Path.Combine( this.CurrentFolder.ServerPath, fileName );
if ( !System.IO.File.Exists( destinationFilePath ) )
break;
else
iCounter++;
}
try
{
System.IO.File.Copy( sourceFilePath, destinationFilePath );
copied++;
}
catch ( ArgumentException )
{
this.appendErrorNode( Errors.InvalidName, name, type, path );
continue;
}
catch ( System.IO.PathTooLongException )
{
this.appendErrorNode( Errors.InvalidName, name, type, path );
continue;
}
catch ( Exception )
{
#if DEBUG
throw;
#else
this.appendErrorNode( Errors.AccessDenied, name, type, path );
continue;
#endif
}
}
else
{
this.appendErrorNode( Errors.AlreadyExist, name, type, path );
continue;
}
}
else {
try
{
// overwrite without warning
System.IO.File.Copy( sourceFilePath, destinationFilePath, true );
copied++;
}
catch ( ArgumentException )
{
this.appendErrorNode( Errors.InvalidName, name, type, path );
continue;
}
catch ( System.IO.PathTooLongException )
{
this.appendErrorNode( Errors.InvalidName, name, type, path );
continue;
}
catch ( Exception )
{
#if DEBUG
throw;
#else
this.appendErrorNode( Errors.AccessDenied, name, type, path );
continue;
#endif
}
}
}
XmlNode copyFilesNode = XmlUtil.AppendElement( this.ConnectorNode, "CopyFiles" );
XmlUtil.SetAttribute( copyFilesNode, "copied", copied.ToString() );
XmlUtil.SetAttribute( copyFilesNode, "copiedTotal", (copiedAll + copied).ToString() );
if ( this.ErrorsNode != null )
{
ConnectorException.Throw( Errors.CopyFailed );
return;
}
}
}
}
| |
// 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.CompilerServices;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
[Trait("connection", "tcp")]
public static class WeakRefTest
{
private const string COMMAND_TEXT_1 = "SELECT au_id, au_lname, au_fname, phone, address, city, state, zip, contract from authors";
private const string COMMAND_TEXT_2 = "SELECT au_lname from authors";
private const string COLUMN_NAME_2 = "au_lname";
private const string DATABASE_NAME = "Northwind";
private enum ReaderTestType
{
ReaderClose,
ReaderDispose,
ReaderGC,
ConnectionClose,
ReaderGCConnectionClose,
}
private enum ReaderVerificationType
{
ExecuteReader,
ChangeDatabase,
BeginTransaction,
EnlistDistributedTransaction,
}
private enum TransactionTestType
{
TransactionRollback,
TransactionDispose,
TransactionGC,
ConnectionClose,
TransactionGCConnectionClose,
}
[CheckConnStrSetupFact]
public static void TestReaderNonMars()
{
string connString =
(new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
{
MaxPoolSize = 1,
InitialCatalog = "pubs"
}
).ConnectionString;
TestReaderNonMarsCase("Case 1: ExecuteReader, Close, ExecuteReader.", connString, ReaderTestType.ReaderClose, ReaderVerificationType.ExecuteReader);
TestReaderNonMarsCase("Case 2: ExecuteReader, Dispose, ExecuteReader.", connString, ReaderTestType.ReaderDispose, ReaderVerificationType.ExecuteReader);
TestReaderNonMarsCase("Case 3: ExecuteReader, GC, ExecuteReader.", connString, ReaderTestType.ReaderGC, ReaderVerificationType.ExecuteReader);
TestReaderNonMarsCase("Case 4: ExecuteReader, Connection Close, ExecuteReader.", connString, ReaderTestType.ConnectionClose, ReaderVerificationType.ExecuteReader);
TestReaderNonMarsCase("Case 5: ExecuteReader, GC, Connection Close, ExecuteReader.", connString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.ExecuteReader);
TestReaderNonMarsCase("Case 6: ExecuteReader, Close, ChangeDatabase.", connString, ReaderTestType.ReaderClose, ReaderVerificationType.ChangeDatabase);
TestReaderNonMarsCase("Case 7: ExecuteReader, Dispose, ChangeDatabase.", connString, ReaderTestType.ReaderDispose, ReaderVerificationType.ChangeDatabase);
TestReaderNonMarsCase("Case 8: ExecuteReader, GC, ChangeDatabase.", connString, ReaderTestType.ReaderGC, ReaderVerificationType.ChangeDatabase);
TestReaderNonMarsCase("Case 9: ExecuteReader, Connection Close, ChangeDatabase.", connString, ReaderTestType.ConnectionClose, ReaderVerificationType.ChangeDatabase);
TestReaderNonMarsCase("Case 10: ExecuteReader, GC, Connection Close, ChangeDatabase.", connString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.ChangeDatabase);
TestReaderNonMarsCase("Case 11: ExecuteReader, Close, BeginTransaction.", connString, ReaderTestType.ReaderClose, ReaderVerificationType.BeginTransaction);
TestReaderNonMarsCase("Case 12: ExecuteReader, Dispose, BeginTransaction.", connString, ReaderTestType.ReaderDispose, ReaderVerificationType.BeginTransaction);
TestReaderNonMarsCase("Case 13: ExecuteReader, GC, BeginTransaction.", connString, ReaderTestType.ReaderGC, ReaderVerificationType.BeginTransaction);
TestReaderNonMarsCase("Case 14: ExecuteReader, Connection Close, BeginTransaction.", connString, ReaderTestType.ConnectionClose, ReaderVerificationType.BeginTransaction);
TestReaderNonMarsCase("Case 15: ExecuteReader, GC, Connection Close, BeginTransaction.", connString, ReaderTestType.ReaderGCConnectionClose, ReaderVerificationType.BeginTransaction);
}
[CheckConnStrSetupFact]
public static void TestTransactionSingle()
{
string connString =
(new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr)
{
MaxPoolSize = 1
}).ConnectionString;
TestTransactionSingleCase("Case 1: BeginTransaction, Rollback.", connString, TransactionTestType.TransactionRollback);
TestTransactionSingleCase("Case 2: BeginTransaction, Dispose.", connString, TransactionTestType.TransactionDispose);
TestTransactionSingleCase("Case 3: BeginTransaction, GC.", connString, TransactionTestType.TransactionGC);
TestTransactionSingleCase("Case 4: BeginTransaction, Connection Close.", connString, TransactionTestType.ConnectionClose);
TestTransactionSingleCase("Case 5: BeginTransaction, GC, Connection Close.", connString, TransactionTestType.TransactionGCConnectionClose);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void TestReaderNonMarsCase(string caseName, string connectionString, ReaderTestType testType, ReaderVerificationType verificationType)
{
WeakReference weak = null;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = COMMAND_TEXT_1;
SqlDataReader gch = null;
if ((testType != ReaderTestType.ReaderGC) && (testType != ReaderTestType.ReaderGCConnectionClose))
gch = cmd.ExecuteReader();
switch (testType)
{
case ReaderTestType.ReaderClose:
gch.Dispose();
break;
case ReaderTestType.ReaderDispose:
gch.Dispose();
break;
case ReaderTestType.ReaderGC:
weak = OpenNullifyReader(cmd);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Reader is still alive!");
break;
case ReaderTestType.ConnectionClose:
GC.SuppressFinalize(gch);
con.Close();
con.Open();
break;
case ReaderTestType.ReaderGCConnectionClose:
weak = OpenNullifyReader(cmd);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Reader is still alive!");
con.Close();
con.Open();
break;
}
switch (verificationType)
{
case ReaderVerificationType.ExecuteReader:
cmd.CommandText = COMMAND_TEXT_2;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
Assert.Equal(rdr.FieldCount, 1);
Assert.Equal(rdr.GetName(0), COLUMN_NAME_2);
}
break;
case ReaderVerificationType.ChangeDatabase:
con.ChangeDatabase(DATABASE_NAME);
Assert.Equal(con.Database, DATABASE_NAME);
break;
case ReaderVerificationType.BeginTransaction:
cmd.Transaction = con.BeginTransaction();
cmd.CommandText = "select @@trancount";
int tranCount = (int)cmd.ExecuteScalar();
Assert.Equal(tranCount, 1);
break;
}
}
}
}
private static WeakReference OpenNullifyReader(SqlCommand cmd)
{
SqlDataReader reader = cmd.ExecuteReader();
WeakReference weak = new WeakReference(reader);
reader = null;
return weak;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void TestTransactionSingleCase(string caseName, string connectionString, TransactionTestType testType)
{
WeakReference weak = null;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlTransaction gch = null;
if ((testType != TransactionTestType.TransactionGC) && (testType != TransactionTestType.TransactionGCConnectionClose))
gch = con.BeginTransaction();
switch (testType)
{
case TransactionTestType.TransactionRollback:
gch.Rollback();
break;
case TransactionTestType.TransactionDispose:
gch.Dispose();
break;
case TransactionTestType.TransactionGC:
weak = OpenNullifyTransaction(con);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Transaction is still alive!");
break;
case TransactionTestType.ConnectionClose:
GC.SuppressFinalize(gch);
con.Close();
con.Open();
break;
case TransactionTestType.TransactionGCConnectionClose:
weak = OpenNullifyTransaction(con);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.False(weak.IsAlive, "Transaction is still alive!");
con.Close();
con.Open();
break;
}
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select @@trancount";
int tranCount = (int)cmd.ExecuteScalar();
Assert.Equal(tranCount, 0);
}
}
}
private static WeakReference OpenNullifyTransaction(SqlConnection connection)
{
SqlTransaction transaction = connection.BeginTransaction();
WeakReference weak = new WeakReference(transaction);
transaction = null;
return weak;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
namespace Orleans.Runtime
{
internal class Message : IOutgoingMessage
{
public const int LENGTH_HEADER_SIZE = 8;
public const int LENGTH_META_HEADER = 4;
#region metadata
[NonSerialized]
private string _targetHistory;
[NonSerialized]
private DateTime? _queuedTime;
[NonSerialized]
private int? _retryCount;
[NonSerialized]
private int? _maxRetries;
public string TargetHistory
{
get { return _targetHistory; }
set { _targetHistory = value; }
}
public DateTime? QueuedTime
{
get { return _queuedTime; }
set { _queuedTime = value; }
}
public int? RetryCount
{
get { return _retryCount; }
set { _retryCount = value; }
}
public int? MaxRetries
{
get { return _maxRetries; }
set { _maxRetries = value; }
}
#endregion
/// <summary>
/// NOTE: The contents of bodyBytes should never be modified
/// </summary>
private List<ArraySegment<byte>> bodyBytes;
private List<ArraySegment<byte>> headerBytes;
private object bodyObject;
// Cache values of TargetAddess and SendingAddress as they are used very frequently
private ActivationAddress targetAddress;
private ActivationAddress sendingAddress;
private static readonly Logger logger;
static Message()
{
logger = LogManager.GetLogger("Message", LoggerType.Runtime);
}
public enum Categories
{
Ping,
System,
Application,
}
public enum Directions
{
Request,
Response,
OneWay
}
public enum ResponseTypes
{
Success,
Error,
Rejection
}
public enum RejectionTypes
{
Transient,
Overloaded,
DuplicateRequest,
Unrecoverable,
GatewayTooBusy,
}
internal HeadersContainer Headers { get; set; } = new HeadersContainer();
public Categories Category
{
get { return Headers.Category; }
set { Headers.Category = value; }
}
public Directions Direction
{
get { return Headers.Direction ?? default(Directions); }
set { Headers.Direction = value; }
}
public bool HasDirection => Headers.Direction.HasValue;
public bool IsReadOnly
{
get { return Headers.IsReadOnly; }
set { Headers.IsReadOnly = value; }
}
public bool IsAlwaysInterleave
{
get { return Headers.IsAlwaysInterleave; }
set { Headers.IsAlwaysInterleave = value; }
}
public bool IsUnordered
{
get { return Headers.IsUnordered; }
set { Headers.IsUnordered = value; }
}
public bool IsReturnedFromRemoteCluster
{
get { return Headers.IsReturnedFromRemoteCluster; }
set { Headers.IsReturnedFromRemoteCluster = value; }
}
public CorrelationId Id
{
get { return Headers.Id; }
set { Headers.Id = value; }
}
public int ResendCount
{
get { return Headers.ResendCount; }
set { Headers.ResendCount = value; }
}
public int ForwardCount
{
get { return Headers.ForwardCount; }
set { Headers.ForwardCount = value; }
}
public SiloAddress TargetSilo
{
get { return Headers.TargetSilo; }
set
{
Headers.TargetSilo = value;
targetAddress = null;
}
}
public GrainId TargetGrain
{
get { return Headers.TargetGrain; }
set
{
Headers.TargetGrain = value;
targetAddress = null;
}
}
public ActivationId TargetActivation
{
get { return Headers.TargetActivation; }
set
{
Headers.TargetActivation = value;
targetAddress = null;
}
}
public ActivationAddress TargetAddress
{
get { return targetAddress ?? (targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation)); }
set
{
TargetGrain = value.Grain;
TargetActivation = value.Activation;
TargetSilo = value.Silo;
targetAddress = value;
}
}
public GuidId TargetObserverId
{
get { return Headers.TargetObserverId; }
set
{
Headers.TargetObserverId = value;
targetAddress = null;
}
}
public SiloAddress SendingSilo
{
get { return Headers.SendingSilo; }
set
{
Headers.SendingSilo = value;
sendingAddress = null;
}
}
public GrainId SendingGrain
{
get { return Headers.SendingGrain; }
set
{
Headers.SendingGrain = value;
sendingAddress = null;
}
}
public ActivationId SendingActivation
{
get { return Headers.SendingActivation; }
set
{
Headers.SendingActivation = value;
sendingAddress = null;
}
}
public ActivationAddress SendingAddress
{
get { return sendingAddress ?? (sendingAddress = ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation)); }
set
{
SendingGrain = value.Grain;
SendingActivation = value.Activation;
SendingSilo = value.Silo;
sendingAddress = value;
}
}
public bool IsNewPlacement
{
get { return Headers.IsNewPlacement; }
set
{
Headers.IsNewPlacement = value;
}
}
public bool IsUsingInterfaceVersions
{
get { return Headers.IsUsingIfaceVersion; }
set
{
Headers.IsUsingIfaceVersion = value;
}
}
public ResponseTypes Result
{
get { return Headers.Result; }
set { Headers.Result = value; }
}
public TimeSpan? TimeToLive
{
get { return Headers.TimeToLive; }
set { Headers.TimeToLive = value; }
}
public bool IsExpired
{
get
{
if (!TimeToLive.HasValue)
return false;
return TimeToLive <= TimeSpan.Zero;
}
}
public bool IsExpirableMessage(IMessagingConfiguration config)
{
if (!config.DropExpiredMessages) return false;
GrainId id = TargetGrain;
if (id == null) return false;
// don't set expiration for one way, system target and system grain messages.
return Direction != Directions.OneWay && !id.IsSystemTarget && !Constants.IsSystemGrain(id);
}
public string DebugContext
{
get { return GetNotNullString(Headers.DebugContext); }
set { Headers.DebugContext = value; }
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return Headers.CacheInvalidationHeader; }
set { Headers.CacheInvalidationHeader = value; }
}
internal void AddToCacheInvalidationHeader(ActivationAddress address)
{
var list = new List<ActivationAddress>();
if (CacheInvalidationHeader != null)
{
list.AddRange(CacheInvalidationHeader);
}
list.Add(address);
CacheInvalidationHeader = list;
}
// Resends are used by the sender, usualy due to en error to send or due to a transient rejection.
public bool MayResend(IMessagingConfiguration config)
{
return ResendCount < config.MaxResendCount;
}
// Forwardings are used by the receiver, usualy when it cannot process the message and forwars it to another silo to perform the processing
// (got here due to outdated cache, silo is shutting down/overloaded, ...).
public bool MayForward(GlobalConfiguration config)
{
return ForwardCount < config.MaxForwardCount;
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return GetNotNullString(Headers.NewGrainType); }
set { Headers.NewGrainType = value; }
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return GetNotNullString(Headers.GenericGrainType); }
set { Headers.GenericGrainType = value; }
}
public RejectionTypes RejectionType
{
get { return Headers.RejectionType; }
set { Headers.RejectionType = value; }
}
public string RejectionInfo
{
get { return GetNotNullString(Headers.RejectionInfo); }
set { Headers.RejectionInfo = value; }
}
public Dictionary<string, object> RequestContextData
{
get { return Headers.RequestContextData; }
set { Headers.RequestContextData = value; }
}
public object GetDeserializedBody(SerializationManager serializationManager)
{
if (this.bodyObject != null) return this.bodyObject;
try
{
this.bodyObject = DeserializeBody(serializationManager, this.bodyBytes);
}
finally
{
if (this.bodyBytes != null)
{
BufferPool.GlobalPool.Release(bodyBytes);
this.bodyBytes = null;
}
}
return this.bodyObject;
}
public object BodyObject
{
set
{
bodyObject = value;
if (bodyBytes == null) return;
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
}
private static object DeserializeBody(SerializationManager serializationManager, List<ArraySegment<byte>> bytes)
{
if (bytes == null)
{
return null;
}
try
{
var stream = new BinaryTokenStreamReader(bytes);
return serializationManager.Deserialize(stream);
}
catch (Exception ex)
{
logger.Error(ErrorCode.Messaging_UnableToDeserializeBody, "Exception deserializing message body", ex);
throw;
}
}
public Message()
{
bodyObject = null;
bodyBytes = null;
headerBytes = null;
}
/// <summary>
/// Clears the current body and sets the serialized body contents to the provided value.
/// </summary>
/// <param name="body">The serialized body contents.</param>
public void SetBodyBytes(List<ArraySegment<byte>> body)
{
// Dispose of the current body.
this.BodyObject = null;
this.bodyBytes = body;
}
/// <summary>
/// Deserializes the provided value into this instance's <see cref="BodyObject"/>.
/// </summary>
/// <param name="serializationManager">The serialization manager.</param>
/// <param name="body">The serialized body contents.</param>
public void DeserializeBodyObject(SerializationManager serializationManager, List<ArraySegment<byte>> body)
{
this.BodyObject = DeserializeBody(serializationManager, body);
}
public void ClearTargetAddress()
{
targetAddress = null;
}
private static string GetNotNullString(string s)
{
return s ?? string.Empty;
}
/// <summary>
/// Tell whether two messages are duplicates of one another
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool IsDuplicate(Message other)
{
return Equals(SendingSilo, other.SendingSilo) && Equals(Id, other.Id);
}
#region Serialization
public List<ArraySegment<byte>> Serialize(SerializationManager serializationManager, out int headerLengthOut, out int bodyLengthOut)
{
var context = new SerializationContext(serializationManager)
{
StreamWriter = new BinaryTokenStreamWriter()
};
SerializationManager.SerializeMessageHeaders(Headers, context);
if (bodyBytes == null)
{
var bodyStream = new BinaryTokenStreamWriter();
serializationManager.Serialize(bodyObject, bodyStream);
// We don't bother to turn this into a byte array and save it in bodyBytes because Serialize only gets called on a message
// being sent off-box. In this case, the likelihood of needed to re-serialize is very low, and the cost of capturing the
// serialized bytes from the steam -- where they're a list of ArraySegment objects -- into an array of bytes is actually
// pretty high (an array allocation plus a bunch of copying).
bodyBytes = bodyStream.ToBytes();
}
if (headerBytes != null)
{
BufferPool.GlobalPool.Release(headerBytes);
}
headerBytes = context.StreamWriter.ToBytes();
int headerLength = context.StreamWriter.CurrentOffset;
int bodyLength = BufferLength(bodyBytes);
var bytes = new List<ArraySegment<byte>>();
bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(headerLength)));
bytes.Add(new ArraySegment<byte>(BitConverter.GetBytes(bodyLength)));
bytes.AddRange(headerBytes);
bytes.AddRange(bodyBytes);
headerLengthOut = headerLength;
bodyLengthOut = bodyLength;
return bytes;
}
public void ReleaseBodyAndHeaderBuffers()
{
ReleaseHeadersOnly();
ReleaseBodyOnly();
}
public void ReleaseHeadersOnly()
{
if (headerBytes == null) return;
BufferPool.GlobalPool.Release(headerBytes);
headerBytes = null;
}
public void ReleaseBodyOnly()
{
if (bodyBytes == null) return;
BufferPool.GlobalPool.Release(bodyBytes);
bodyBytes = null;
}
#endregion
// For testing and logging/tracing
public string ToLongString()
{
var sb = new StringBuilder();
string debugContex = DebugContext;
if (!string.IsNullOrEmpty(debugContex))
{
// if DebugContex is present, print it first.
sb.Append(debugContex).Append(".");
}
AppendIfExists(HeadersContainer.Headers.CACHE_INVALIDATION_HEADER, sb, (m) => m.CacheInvalidationHeader);
AppendIfExists(HeadersContainer.Headers.CATEGORY, sb, (m) => m.Category);
AppendIfExists(HeadersContainer.Headers.DIRECTION, sb, (m) => m.Direction);
AppendIfExists(HeadersContainer.Headers.TIME_TO_LIVE, sb, (m) => m.TimeToLive);
AppendIfExists(HeadersContainer.Headers.FORWARD_COUNT, sb, (m) => m.ForwardCount);
AppendIfExists(HeadersContainer.Headers.GENERIC_GRAIN_TYPE, sb, (m) => m.GenericGrainType);
AppendIfExists(HeadersContainer.Headers.CORRELATION_ID, sb, (m) => m.Id);
AppendIfExists(HeadersContainer.Headers.ALWAYS_INTERLEAVE, sb, (m) => m.IsAlwaysInterleave);
AppendIfExists(HeadersContainer.Headers.IS_NEW_PLACEMENT, sb, (m) => m.IsNewPlacement);
AppendIfExists(HeadersContainer.Headers.READ_ONLY, sb, (m) => m.IsReadOnly);
AppendIfExists(HeadersContainer.Headers.IS_UNORDERED, sb, (m) => m.IsUnordered);
AppendIfExists(HeadersContainer.Headers.IS_RETURNED_FROM_REMOTE_CLUSTER, sb, (m) => m.IsReturnedFromRemoteCluster);
AppendIfExists(HeadersContainer.Headers.NEW_GRAIN_TYPE, sb, (m) => m.NewGrainType);
AppendIfExists(HeadersContainer.Headers.REJECTION_INFO, sb, (m) => m.RejectionInfo);
AppendIfExists(HeadersContainer.Headers.REJECTION_TYPE, sb, (m) => m.RejectionType);
AppendIfExists(HeadersContainer.Headers.REQUEST_CONTEXT, sb, (m) => m.RequestContextData);
AppendIfExists(HeadersContainer.Headers.RESEND_COUNT, sb, (m) => m.ResendCount);
AppendIfExists(HeadersContainer.Headers.RESULT, sb, (m) => m.Result);
AppendIfExists(HeadersContainer.Headers.SENDING_ACTIVATION, sb, (m) => m.SendingActivation);
AppendIfExists(HeadersContainer.Headers.SENDING_GRAIN, sb, (m) => m.SendingGrain);
AppendIfExists(HeadersContainer.Headers.SENDING_SILO, sb, (m) => m.SendingSilo);
AppendIfExists(HeadersContainer.Headers.TARGET_ACTIVATION, sb, (m) => m.TargetActivation);
AppendIfExists(HeadersContainer.Headers.TARGET_GRAIN, sb, (m) => m.TargetGrain);
AppendIfExists(HeadersContainer.Headers.TARGET_OBSERVER, sb, (m) => m.TargetObserverId);
AppendIfExists(HeadersContainer.Headers.TARGET_SILO, sb, (m) => m.TargetSilo);
return sb.ToString();
}
private void AppendIfExists(HeadersContainer.Headers header, StringBuilder sb, Func<Message, object> valueProvider)
{
// used only under log3 level
if ((Headers.GetHeadersMask() & header) != HeadersContainer.Headers.NONE)
{
sb.AppendFormat("{0}={1};", header, valueProvider(this));
sb.AppendLine();
}
}
public override string ToString()
{
string response = String.Empty;
if (Direction == Directions.Response)
{
switch (Result)
{
case ResponseTypes.Error:
response = "Error ";
break;
case ResponseTypes.Rejection:
response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo);
break;
default:
break;
}
}
return String.Format("{0}{1}{2}{3}{4} {5}->{6} #{7}{8}{9}: {10}",
IsReadOnly ? "ReadOnly " : "", //0
IsAlwaysInterleave ? "IsAlwaysInterleave " : "", //1
IsNewPlacement ? "NewPlacement " : "", // 2
response, //3
Direction, //4
String.Format("{0}{1}{2}", SendingSilo, SendingGrain, SendingActivation), //5
String.Format("{0}{1}{2}{3}", TargetSilo, TargetGrain, TargetActivation, TargetObserverId), //6
Id, //7
ResendCount > 0 ? "[ResendCount=" + ResendCount + "]" : "", //8
ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : "", //9
DebugContext); //10
}
internal void SetTargetPlacement(PlacementResult value)
{
TargetActivation = value.Activation;
TargetSilo = value.Silo;
if (value.IsNewPlacement)
IsNewPlacement = true;
if (!String.IsNullOrEmpty(value.GrainType))
NewGrainType = value.GrainType;
}
public string GetTargetHistory()
{
var history = new StringBuilder();
history.Append("<");
if (TargetSilo != null)
{
history.Append(TargetSilo).Append(":");
}
if (TargetGrain != null)
{
history.Append(TargetGrain).Append(":");
}
if (TargetActivation != null)
{
history.Append(TargetActivation);
}
history.Append(">");
if (!string.IsNullOrEmpty(TargetHistory))
{
history.Append(" ").Append(TargetHistory);
}
return history.ToString();
}
public bool IsSameDestination(IOutgoingMessage other)
{
var msg = (Message)other;
return msg != null && Object.Equals(TargetSilo, msg.TargetSilo);
}
// For statistical measuring of time spent in queues.
private ITimeInterval timeInterval;
public void Start()
{
timeInterval = TimeIntervalFactory.CreateTimeInterval(true);
timeInterval.Start();
}
public void Stop()
{
timeInterval.Stop();
}
public void Restart()
{
timeInterval.Restart();
}
public TimeSpan Elapsed
{
get { return timeInterval.Elapsed; }
}
public static Message CreatePromptExceptionResponse(Message request, Exception exception)
{
return new Message
{
Category = request.Category,
Direction = Message.Directions.Response,
Result = Message.ResponseTypes.Error,
BodyObject = Response.ExceptionResponse(exception)
};
}
internal void DropExpiredMessage(MessagingStatisticsGroup.Phase phase)
{
MessagingStatisticsGroup.OnMessageExpired(phase);
if (logger.IsVerbose2) logger.Verbose2("Dropping an expired message: {0}", this);
ReleaseBodyAndHeaderBuffers();
}
private static int BufferLength(List<ArraySegment<byte>> buffer)
{
var result = 0;
for (var i = 0; i < buffer.Count; i++)
{
result += buffer[i].Count;
}
return result;
}
[Serializable]
public class HeadersContainer
{
[Flags]
public enum Headers
{
NONE = 0,
ALWAYS_INTERLEAVE = 1 << 0,
CACHE_INVALIDATION_HEADER = 1 << 1,
CATEGORY = 1 << 2,
CORRELATION_ID = 1 << 3,
DEBUG_CONTEXT = 1 << 4,
DIRECTION = 1 << 5,
TIME_TO_LIVE = 1 << 6,
FORWARD_COUNT = 1 << 7,
NEW_GRAIN_TYPE = 1 << 8,
GENERIC_GRAIN_TYPE = 1 << 9,
RESULT = 1 << 10,
REJECTION_INFO = 1 << 11,
REJECTION_TYPE = 1 << 12,
READ_ONLY = 1 << 13,
RESEND_COUNT = 1 << 14,
SENDING_ACTIVATION = 1 << 15,
SENDING_GRAIN = 1 <<16,
SENDING_SILO = 1 << 17,
IS_NEW_PLACEMENT = 1 << 18,
TARGET_ACTIVATION = 1 << 19,
TARGET_GRAIN = 1 << 20,
TARGET_SILO = 1 << 21,
TARGET_OBSERVER = 1 << 22,
IS_UNORDERED = 1 << 23,
REQUEST_CONTEXT = 1 << 24,
IS_RETURNED_FROM_REMOTE_CLUSTER = 1 << 25,
IS_USING_INTERFACE_VERSION = 1 << 26,
// Do not add over int.MaxValue of these.
}
private Categories _category;
private Directions? _direction;
private bool _isReadOnly;
private bool _isAlwaysInterleave;
private bool _isUnordered;
private bool _isReturnedFromRemoteCluster;
private CorrelationId _id;
private int _resendCount;
private int _forwardCount;
private SiloAddress _targetSilo;
private GrainId _targetGrain;
private ActivationId _targetActivation;
private GuidId _targetObserverId;
private SiloAddress _sendingSilo;
private GrainId _sendingGrain;
private ActivationId _sendingActivation;
private bool _isNewPlacement;
private bool _isUsingIfaceVersion;
private ResponseTypes _result;
private TimeSpan? _timeToLive;
private string _debugContext;
private List<ActivationAddress> _cacheInvalidationHeader;
private string _newGrainType;
private string _genericGrainType;
private RejectionTypes _rejectionType;
private string _rejectionInfo;
private Dictionary<string, object> _requestContextData;
private readonly DateTime _localCreationTime;
public HeadersContainer()
{
_localCreationTime = DateTime.UtcNow;
}
public Categories Category
{
get { return _category; }
set
{
_category = value;
}
}
public Directions? Direction
{
get { return _direction; }
set
{
_direction = value;
}
}
public bool IsReadOnly
{
get { return _isReadOnly; }
set
{
_isReadOnly = value;
}
}
public bool IsAlwaysInterleave
{
get { return _isAlwaysInterleave; }
set
{
_isAlwaysInterleave = value;
}
}
public bool IsUnordered
{
get { return _isUnordered; }
set
{
_isUnordered = value;
}
}
public bool IsReturnedFromRemoteCluster
{
get { return _isReturnedFromRemoteCluster; }
set
{
_isReturnedFromRemoteCluster = value;
}
}
public CorrelationId Id
{
get { return _id; }
set
{
_id = value;
}
}
public int ResendCount
{
get { return _resendCount; }
set
{
_resendCount = value;
}
}
public int ForwardCount
{
get { return _forwardCount; }
set
{
_forwardCount = value;
}
}
public SiloAddress TargetSilo
{
get { return _targetSilo; }
set
{
_targetSilo = value;
}
}
public GrainId TargetGrain
{
get { return _targetGrain; }
set
{
_targetGrain = value;
}
}
public ActivationId TargetActivation
{
get { return _targetActivation; }
set
{
_targetActivation = value;
}
}
public GuidId TargetObserverId
{
get { return _targetObserverId; }
set
{
_targetObserverId = value;
}
}
public SiloAddress SendingSilo
{
get { return _sendingSilo; }
set
{
_sendingSilo = value;
}
}
public GrainId SendingGrain
{
get { return _sendingGrain; }
set
{
_sendingGrain = value;
}
}
public ActivationId SendingActivation
{
get { return _sendingActivation; }
set
{
_sendingActivation = value;
}
}
public bool IsNewPlacement
{
get { return _isNewPlacement; }
set
{
_isNewPlacement = value;
}
}
public bool IsUsingIfaceVersion
{
get { return _isUsingIfaceVersion; }
set
{
_isUsingIfaceVersion = value;
}
}
public ResponseTypes Result
{
get { return _result; }
set
{
_result = value;
}
}
public TimeSpan? TimeToLive
{
get
{
return _timeToLive - (DateTime.UtcNow - _localCreationTime);
}
set
{
_timeToLive = value;
}
}
public string DebugContext
{
get { return _debugContext; }
set
{
_debugContext = value;
}
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return _cacheInvalidationHeader; }
set
{
_cacheInvalidationHeader = value;
}
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return _newGrainType; }
set
{
_newGrainType = value;
}
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return _genericGrainType; }
set
{
_genericGrainType = value;
}
}
public RejectionTypes RejectionType
{
get { return _rejectionType; }
set
{
_rejectionType = value;
}
}
public string RejectionInfo
{
get { return _rejectionInfo; }
set
{
_rejectionInfo = value;
}
}
public Dictionary<string, object> RequestContextData
{
get { return _requestContextData; }
set
{
_requestContextData = value;
}
}
internal Headers GetHeadersMask()
{
Headers headers = Headers.NONE;
if(Category != default(Categories))
headers = headers | Headers.CATEGORY;
headers = _direction == null ? headers & ~Headers.DIRECTION : headers | Headers.DIRECTION;
if (IsReadOnly)
headers = headers | Headers.READ_ONLY;
if (IsAlwaysInterleave)
headers = headers | Headers.ALWAYS_INTERLEAVE;
if(IsUnordered)
headers = headers | Headers.IS_UNORDERED;
headers = _id == null ? headers & ~Headers.CORRELATION_ID : headers | Headers.CORRELATION_ID;
if (_resendCount != default(int))
headers = headers | Headers.RESEND_COUNT;
if(_forwardCount != default (int))
headers = headers | Headers.FORWARD_COUNT;
headers = _targetSilo == null ? headers & ~Headers.TARGET_SILO : headers | Headers.TARGET_SILO;
headers = _targetGrain == null ? headers & ~Headers.TARGET_GRAIN : headers | Headers.TARGET_GRAIN;
headers = _targetActivation == null ? headers & ~Headers.TARGET_ACTIVATION : headers | Headers.TARGET_ACTIVATION;
headers = _targetObserverId == null ? headers & ~Headers.TARGET_OBSERVER : headers | Headers.TARGET_OBSERVER;
headers = _sendingSilo == null ? headers & ~Headers.SENDING_SILO : headers | Headers.SENDING_SILO;
headers = _sendingGrain == null ? headers & ~Headers.SENDING_GRAIN : headers | Headers.SENDING_GRAIN;
headers = _sendingActivation == null ? headers & ~Headers.SENDING_ACTIVATION : headers | Headers.SENDING_ACTIVATION;
headers = _isNewPlacement == default(bool) ? headers & ~Headers.IS_NEW_PLACEMENT : headers | Headers.IS_NEW_PLACEMENT;
headers = _isUsingIfaceVersion == default(bool) ? headers & ~Headers.IS_USING_INTERFACE_VERSION : headers | Headers.IS_USING_INTERFACE_VERSION;
headers = _result == default(ResponseTypes)? headers & ~Headers.RESULT : headers | Headers.RESULT;
headers = _timeToLive == null ? headers & ~Headers.TIME_TO_LIVE : headers | Headers.TIME_TO_LIVE;
headers = string.IsNullOrEmpty(_debugContext) ? headers & ~Headers.DEBUG_CONTEXT : headers | Headers.DEBUG_CONTEXT;
headers = _cacheInvalidationHeader == null || _cacheInvalidationHeader.Count == 0 ? headers & ~Headers.CACHE_INVALIDATION_HEADER : headers | Headers.CACHE_INVALIDATION_HEADER;
headers = string.IsNullOrEmpty(_newGrainType) ? headers & ~Headers.NEW_GRAIN_TYPE : headers | Headers.NEW_GRAIN_TYPE;
headers = string.IsNullOrEmpty(GenericGrainType) ? headers & ~Headers.GENERIC_GRAIN_TYPE : headers | Headers.GENERIC_GRAIN_TYPE;
headers = _rejectionType == default(RejectionTypes) ? headers & ~Headers.REJECTION_TYPE : headers | Headers.REJECTION_TYPE;
headers = string.IsNullOrEmpty(_rejectionInfo) ? headers & ~Headers.REJECTION_INFO : headers | Headers.REJECTION_INFO;
headers = _requestContextData == null || _requestContextData.Count == 0 ? headers & ~Headers.REQUEST_CONTEXT : headers | Headers.REQUEST_CONTEXT;
return headers;
}
[CopierMethod]
public static object DeepCopier(object original, ICopyContext context)
{
return original;
}
[SerializerMethod]
public static void Serializer(object untypedInput, ISerializationContext context, Type expected)
{
HeadersContainer input = (HeadersContainer)untypedInput;
var headers = input.GetHeadersMask();
var writer = context.StreamWriter;
writer.Write((int)headers);
if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE)
{
var count = input.CacheInvalidationHeader.Count;
writer.Write(input.CacheInvalidationHeader.Count);
for (int i = 0; i < count; i++)
{
WriteObj(context, typeof(ActivationAddress), input.CacheInvalidationHeader[i]);
}
}
if ((headers & Headers.CATEGORY) != Headers.NONE)
{
writer.Write((byte)input.Category);
}
if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE)
writer.Write(input.DebugContext);
if ((headers & Headers.DIRECTION) != Headers.NONE)
writer.Write((byte)input.Direction.Value);
if ((headers & Headers.TIME_TO_LIVE) != Headers.NONE)
writer.Write(input.TimeToLive.Value);
if ((headers & Headers.FORWARD_COUNT) != Headers.NONE)
writer.Write(input.ForwardCount);
if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE)
writer.Write(input.GenericGrainType);
if ((headers & Headers.CORRELATION_ID) != Headers.NONE)
writer.Write(input.Id);
if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE)
writer.Write(input.IsAlwaysInterleave);
if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE)
writer.Write(input.IsNewPlacement);
// Nothing to do with Headers.IS_USING_INTERFACE_VERSION since the value in
// the header is sufficient
if ((headers & Headers.READ_ONLY) != Headers.NONE)
writer.Write(input.IsReadOnly);
if ((headers & Headers.IS_UNORDERED) != Headers.NONE)
writer.Write(input.IsUnordered);
if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE)
writer.Write(input.NewGrainType);
if ((headers & Headers.REJECTION_INFO) != Headers.NONE)
writer.Write(input.RejectionInfo);
if ((headers & Headers.REJECTION_TYPE) != Headers.NONE)
writer.Write((byte)input.RejectionType);
if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE)
{
var requestData = input.RequestContextData;
var count = requestData.Count;
writer.Write(count);
foreach (var d in requestData)
{
writer.Write(d.Key);
SerializationManager.SerializeInner(d.Value, context, typeof(object));
}
}
if ((headers & Headers.RESEND_COUNT) != Headers.NONE)
writer.Write(input.ResendCount);
if ((headers & Headers.RESULT) != Headers.NONE)
writer.Write((byte)input.Result);
if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE)
{
writer.Write(input.SendingActivation);
}
if ((headers & Headers.SENDING_GRAIN) != Headers.NONE)
{
writer.Write(input.SendingGrain);
}
if ((headers & Headers.SENDING_SILO) != Headers.NONE)
{
writer.Write(input.SendingSilo);
}
if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE)
{
writer.Write(input.TargetActivation);
}
if ((headers & Headers.TARGET_GRAIN) != Headers.NONE)
{
writer.Write(input.TargetGrain);
}
if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE)
{
WriteObj(context, typeof(GuidId), input.TargetObserverId);
}
if ((headers & Headers.TARGET_SILO) != Headers.NONE)
{
writer.Write(input.TargetSilo);
}
}
[DeserializerMethod]
public static object Deserializer(Type expected, IDeserializationContext context)
{
var result = new HeadersContainer();
var reader = context.StreamReader;
context.RecordObject(result);
var headers = (Headers)reader.ReadInt();
if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE)
{
var n = reader.ReadInt();
if (n > 0)
{
var list = result.CacheInvalidationHeader = new List<ActivationAddress>(n);
for (int i = 0; i < n; i++)
{
list.Add((ActivationAddress)ReadObj(typeof(ActivationAddress), context));
}
}
}
if ((headers & Headers.CATEGORY) != Headers.NONE)
result.Category = (Categories)reader.ReadByte();
if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE)
result.DebugContext = reader.ReadString();
if ((headers & Headers.DIRECTION) != Headers.NONE)
result.Direction = (Message.Directions)reader.ReadByte();
if ((headers & Headers.TIME_TO_LIVE) != Headers.NONE)
result.TimeToLive = reader.ReadTimeSpan();
if ((headers & Headers.FORWARD_COUNT) != Headers.NONE)
result.ForwardCount = reader.ReadInt();
if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE)
result.GenericGrainType = reader.ReadString();
if ((headers & Headers.CORRELATION_ID) != Headers.NONE)
result.Id = (Orleans.Runtime.CorrelationId)ReadObj(typeof(Orleans.Runtime.CorrelationId), context);
if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE)
result.IsAlwaysInterleave = ReadBool(reader);
if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE)
result.IsNewPlacement = ReadBool(reader);
if ((headers & Headers.IS_USING_INTERFACE_VERSION) != Headers.NONE)
result.IsUsingIfaceVersion = true;
if ((headers & Headers.READ_ONLY) != Headers.NONE)
result.IsReadOnly = ReadBool(reader);
if ((headers & Headers.IS_UNORDERED) != Headers.NONE)
result.IsUnordered = ReadBool(reader);
if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE)
result.NewGrainType = reader.ReadString();
if ((headers & Headers.REJECTION_INFO) != Headers.NONE)
result.RejectionInfo = reader.ReadString();
if ((headers & Headers.REJECTION_TYPE) != Headers.NONE)
result.RejectionType = (RejectionTypes)reader.ReadByte();
if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE)
{
var c = reader.ReadInt();
var requestData = new Dictionary<string, object>(c);
for (int i = 0; i < c; i++)
{
requestData[reader.ReadString()] = SerializationManager.DeserializeInner(null, context);
}
result.RequestContextData = requestData;
}
if ((headers & Headers.RESEND_COUNT) != Headers.NONE)
result.ResendCount = reader.ReadInt();
if ((headers & Headers.RESULT) != Headers.NONE)
result.Result = (Orleans.Runtime.Message.ResponseTypes)reader.ReadByte();
if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE)
result.SendingActivation = reader.ReadActivationId();
if ((headers & Headers.SENDING_GRAIN) != Headers.NONE)
result.SendingGrain = reader.ReadGrainId();
if ((headers & Headers.SENDING_SILO) != Headers.NONE)
result.SendingSilo = reader.ReadSiloAddress();
if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE)
result.TargetActivation = reader.ReadActivationId();
if ((headers & Headers.TARGET_GRAIN) != Headers.NONE)
result.TargetGrain = reader.ReadGrainId();
if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE)
result.TargetObserverId = (Orleans.Runtime.GuidId)ReadObj(typeof(Orleans.Runtime.GuidId), context);
if ((headers & Headers.TARGET_SILO) != Headers.NONE)
result.TargetSilo = reader.ReadSiloAddress();
return (HeadersContainer)result;
}
private static bool ReadBool(BinaryTokenStreamReader stream)
{
return stream.ReadByte() == (byte) SerializationTokenType.True;
}
private static void WriteObj(ISerializationContext context, Type type, object input)
{
var ser = context.SerializationManager.GetSerializer(type);
ser.Invoke(input, context, type);
}
private static object ReadObj(Type t, IDeserializationContext context)
{
var des = context.SerializationManager.GetDeserializer(t);
return des.Invoke(t, context);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
/**
* The player which extends the character class
*/
public class Player : Character
{
/**
* The thrust of the players space ship
*/
public float thrust = 10f;
/**
* The thrust loss ratio of the players space ship
*/
public float thrustLossRatio = 0.02f;
/**
* The max life and start amount of the player
*/
public int maxLife = 3;
/**
* The time the player stays indestructible after a hit
*/
public float indestructibleTime = 3f;
/**
* Is true if the players space ship has thrust
* Also plays / stops the looped thrust sfx
*/
public bool hasThrust
{
get
{
return this._hasThrust;
}
set
{
if (value == true)
{
this.audioSource.Play();
}
else
{
this.audioSource.Stop();
}
this._hasThrust = value;
}
}
/**
* The current life amount of the player
*/
private int life = 0;
/**
* The time until the player is indestructible
*/
private float indestructibleUntil = 0f;
/**
* The players audio source
*/
private AudioSource audioSource;
/**
* Is true if the players space ship has thrust
*/
private bool _hasThrust = false;
/**
* Loads needed components
*/
protected override void Awake()
{
base.Awake();
this.audioSource = this.GetComponent<AudioSource>();
}
#if UNITY_EDITOR
/**
* Handle player inputs within the Unity Editor
*/
private void Update()
{
this.RotateAroundMouse();
if (Input.GetKeyDown(KeyCode.LeftControl))
{
this.hasThrust = true;
}
else if (this.hasThrust && Input.GetKeyUp(KeyCode.LeftControl))
{
this.hasThrust = false;
}
if (Input.GetMouseButton(0))
{
this.FireMissile();
}
}
#endif
/**
* Gives thrust to the player or reduces the thrust automaticly to zero
*/
private void FixedUpdate()
{
if (this.IsActive() && this.hasThrust)
{
this.Thrust();
}
else
{
this.ReduceThrust();
}
}
/**
* Fires a missile if possible
*/
public void FireMissile()
{
if (this.IsActive() && this.lastMissileShot + this.delayBetweenMissiles <= Time.time)
{
this.lastMissileShot = Time.time;
var missile = MissileManager.Instance.GetMissile(this.flyingObject);
missile.Activate(this.weaponTransform.position, this.transform.rotation, this.transform.up);
}
}
/**
* Rotates the player around the mouse
*/
private void RotateAroundMouse()
{
var mousePosition = Input.mousePosition;
var playerPosition = Camera.main.WorldToScreenPoint(this.transform.position);
mousePosition.x -= playerPosition.x;
mousePosition.y -= playerPosition.y;
var playerAngle = Mathf.Atan2(mousePosition.y, mousePosition.x) * Mathf.Rad2Deg;
this.transform.rotation = Quaternion.Euler(new Vector3(0, 0, playerAngle - 90f));
}
/**
* Increases or holds the players thrust
*/
public void Thrust()
{
if(this.rigidbody2DComponent.velocity.magnitude > this.maxSpeed)
{
this.rigidbody2DComponent.velocity = this.rigidbody2DComponent.velocity.normalized * this.maxSpeed;
}
else
{
this.rigidbody2DComponent.AddForce(this.transform.up * this.thrust);
}
}
/**
* Reduces the players thrust
*/
private void ReduceThrust()
{
if (this.rigidbody2DComponent.velocity.magnitude > 0)
{
this.rigidbody2DComponent.velocity *= 1f - this.thrustLossRatio;
}
}
/**
* Sets the players rotation
*/
public void Rotate(Quaternion rotation)
{
this.transform.rotation = rotation;
}
/**
* Returns true if the player is indistructable
*/
public bool IsIndistructable()
{
return this.indestructibleUntil > Time.time;
}
/**
* Adds the given score to the player score
*/
public void AddScore(int score)
{
this.SetScore(this.score + score);
}
/**
* Sets the players score
*/
private void SetScore(int score)
{
this.score = score;
UIManager.Instance.GetPanel<IngamePanel>(Enum.Panel.Ingame).SetScore(this.score);
}
/**
* Reduces the players life
*/
private void ReduceLife(int life = 1)
{
this.SetLife(this.life - life);
}
/**
* Sets the players lifes
*/
private void SetLife(int life)
{
this.life = life;
UIManager.Instance.GetPanel<IngamePanel>(Enum.Panel.Ingame).SetLife(this.life);
}
/**
* Destroies the player
*/
public override void Destroy(bool addScore = false)
{
if (!this.IsIndistructable())
{
AudioManager.Instance.Play(this.destructionAudioClip);
this.ReduceLife();
if (this.life == 0)
{
this.Deactivate();
GameManager.Instance.GameOver();
}
else
{
this.indestructibleUntil = Time.time + this.indestructibleTime;
this.transform.position = Vector3.zero;
this.rigidbody2DComponent.velocity = Vector2.zero;
this.hasThrust = false;
this.GetComponent<Animator>().SetBool("Indistructable", true);
this.Invoke("RemoveIndistructable", this.indestructibleTime);
}
}
}
/**
* Activates the player
*/
public void Activate()
{
this.gameObject.SetActive(true);
this.Reset();
}
/**
* Removes the indistructable effect
*/
private void RemoveIndistructable()
{
this.GetComponent<Animator>().SetBool("Indistructable", false);
}
/**
* Resets the player object
*/
private void Reset()
{
this.SetScore(0);
this.SetLife(this.maxLife);
this.indestructibleUntil = 0f;
this.transform.position = Vector3.zero;
this.rigidbody2DComponent.velocity = Vector2.zero;
}
}
| |
#region License
// Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#endregion
using System;
using System.Security.Cryptography.X509Certificates;
using Xunit;
namespace SourceCode.Clay.Security.Tests
{
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public static class CertificateTests
{
private static readonly X509Certificate2 s_existingCertificate;
static CertificateTests()
{
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
try
{
// Choose any arbitrary certificate on the machine
s_existingCertificate = certStore.Certificates[0];
}
finally
{
certStore.Close();
}
}
[Trait("Type", "Unit")]
[Fact]
public static void When_load_certificate_thumb_null()
{
const string thumbprint = null;
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.Equal(string.Empty, norm);
Assert.Throws<ArgumentNullException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _));
Assert.Throws<ArgumentNullException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false));
}
[Trait("Type", "Unit")]
[Fact]
public static void When_load_certificate_thumb_empty()
{
const string thumbprint = "";
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.Equal(string.Empty, norm);
Assert.Throws<ArgumentNullException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _));
Assert.Throws<ArgumentNullException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false));
}
[Trait("Type", "Unit")]
[Fact]
public static void When_load_certificate_thumb_nonexistent()
{
var thumbprint = "00000" + s_existingCertificate.Thumbprint.Substring(10) + "00000"; // Valid format but unlikely to exist
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.Equal(thumbprint.Length, norm.Length);
Assert.Equal(CertificateLoader.Sha1Length, norm.Length);
var found = CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _);
Assert.False(found);
Assert.Throws<InvalidOperationException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false));
}
[Trait("Type", "Unit")]
[Fact]
public static void When_load_certificate_thumb_noisy_only()
{
var thumbprint = new string('?', CertificateLoader.Sha1Length); // Special characters only
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.Equal(0, norm.Length);
Assert.Throws<ArgumentNullException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, norm, false, out _));
Assert.Throws<FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _));
Assert.Throws<FormatException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false));
}
[Trait("Type", "Unit")]
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(10)]
[InlineData(39)]
public static void When_load_certificate_thumb_short_by_N(int n)
{
var thumbprint = s_existingCertificate.Thumbprint.Substring(n); // Too short
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.Equal(thumbprint.Length, norm.Length);
Assert.NotEqual(CertificateLoader.Sha1Length, norm.Length);
Assert.Throws<FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _));
Assert.Throws<FormatException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false));
}
[Trait("Type", "Unit")]
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(10)]
public static void When_load_certificate_thumb_long_by_N(int n)
{
var thumbprint = s_existingCertificate.Thumbprint + new string('1', n); // Too long
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.NotEqual(thumbprint.Length, norm.Length);
Assert.Equal(CertificateLoader.Sha1Length, norm.Length);
var found = CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, norm, false, out _);
Assert.True(found);
Assert.Throws<FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _));
Assert.Throws<FormatException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false));
}
[Trait("Type", "Unit")]
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(10)]
[InlineData(39)]
public static void When_load_certificate_thumb_noisy_short(int n)
{
var thumbprint = "\n" + s_existingCertificate.Thumbprint.Substring(n) + "\t"; // Too short after removing special chars
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.NotEqual(thumbprint.Length, norm.Length);
Assert.NotEqual(CertificateLoader.Sha1Length, norm.Length);
Assert.Throws<FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, norm, false, out _));
Assert.Throws<FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _));
Assert.Throws<FormatException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false));
}
[Trait("Type", "Unit")]
[Fact]
public static void When_load_certificate_thumb_noisy_short_0()
{
const string thumbprint = "\r\n"; // 0 chars after removing special chars
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.NotEqual(thumbprint.Length, norm.Length);
Assert.Equal(0, norm.Length);
Assert.Throws<ArgumentNullException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, norm, false, out _));
Assert.Throws<ArgumentNullException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _));
Assert.Throws<ArgumentNullException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false));
}
[Trait("Type", "Unit")]
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(10)]
public static void When_load_certificate_thumb_noisy_long(int n)
{
var thumbprint = "\n" + s_existingCertificate.Thumbprint + new string('1', n) + "\t"; // Too long after removing special chars
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.NotEqual(thumbprint.Length, norm.Length);
Assert.Equal(CertificateLoader.Sha1Length, norm.Length);
var found = CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, norm, false, out _);
Assert.True(found);
Assert.Throws<FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _));
Assert.Throws<FormatException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false));
}
[Trait("Type", "Unit")]
[Fact]
public static void When_load_certificate_thumb_noisy_valid()
{
var thumbprint = "\n" + s_existingCertificate.Thumbprint + "\t"; // Valid after removing special chars
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.NotEqual(thumbprint.Length, norm.Length);
Assert.Equal(CertificateLoader.Sha1Length, norm.Length);
var found = CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, norm, false, out _);
Assert.True(found);
Assert.Throws<FormatException>(() => CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out _));
Assert.Throws<FormatException>(() => CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false));
}
[Trait("Type", "Unit")]
[Fact]
public static void When_load_certificate_thumb_valid()
{
var thumbprint = s_existingCertificate.Thumbprint; // Valid in all respects (given that we already retrieved it locally)
var norm = CertificateLoader.NormalizeThumbprint(thumbprint);
Assert.Equal(CertificateLoader.Sha1Length, norm.Length);
var found = CertificateLoader.TryLoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false, out X509Certificate2 actual);
Assert.True(found);
Assert.Equal(s_existingCertificate.SerialNumber, actual.SerialNumber);
actual = CertificateLoader.LoadCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint, false);
Assert.Equal(s_existingCertificate.SerialNumber, actual.SerialNumber);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
private class ReadWriteAsyncParams
{
public ReadWriteAsyncParams() { }
public ReadWriteAsyncParams(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
this.Buffer = buffer;
this.Offset = offset;
this.Count = count;
this.CancellationHelper = cancellationToken.CanBeCanceled ? new IOCancellationHelper(cancellationToken) : null;
}
public Byte[] Buffer { get; set; }
public int Offset { get; set; }
public int Count { get; set; }
public IOCancellationHelper CancellationHelper { get; private set; }
}
[SecurityCritical]
private unsafe static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(PipeStream.AsyncPSCallback);
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal static void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
// Check that this handle is infact a handle to a pipe.
if (Interop.mincore.GetFileType(safePipeHandle) != Interop.FILE_TYPE_PIPE)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// If the handle is of async type, bind the handle to the ThreadPool so that we can use
// the async operations (it's needed so that our native callbacks get called).
if (!ThreadPool.BindHandle(handle))
{
throw new IOException(SR.IO_BindHandleFailed);
}
}
[SecurityCritical]
private unsafe int ReadCore(byte[] buffer, int offset, int count)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanRead, "can't read");
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
if (_isAsync)
{
IAsyncResult result = BeginReadCore(buffer, offset, count, null, null);
return EndRead(result);
}
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, offset, count, null, out errorCode);
if (r == -1)
{
// If the other side has broken the connection, set state to Broken and return 0
if (errorCode == Interop.ERROR_BROKEN_PIPE ||
errorCode == Interop.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
r = 0;
}
else
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode, String.Empty);
}
}
_isMessageComplete = (errorCode != Interop.ERROR_MORE_DATA);
Debug.Assert(r >= 0, "PipeStream's ReadCore is likely broken.");
return r;
}
[SecurityCritical]
private IAsyncResult BeginRead(AsyncCallback callback, Object state)
{
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
Debug.Assert(readWriteParams != null);
byte[] buffer = readWriteParams.Buffer;
int offset = readWriteParams.Offset;
int count = readWriteParams.Count;
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!CanRead)
{
throw __Error.GetReadNotSupported();
}
CheckReadOperations();
if (!_isAsync)
{
// special case when this is called for sync broken pipes because otherwise Stream's
// Begin/EndRead hang. Reads return 0 bytes in this case so we can call the user's
// callback immediately
if (_state == PipeState.Broken)
{
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._handle = _handle;
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = false;
asyncResult.CallUserCallback();
return asyncResult;
}
else
{
return _streamAsyncHelper.BeginRead(buffer, offset, count, callback, state);
}
}
else
{
return BeginReadCore(buffer, offset, count, callback, state);
}
}
[SecurityCritical]
unsafe private PipeStreamAsyncResult BeginReadCore(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanRead, "can't read");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert(_isAsync, "BeginReadCore doesn't work on synchronous file streams!");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
// Create and store async stream class library specific data in the async result
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._handle = _handle;
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = false;
// handle zero-length buffers separately; fixed keyword ReadFileNative doesn't like
// 0-length buffers. Call user callback and we're done
if (buffer.Length == 0)
{
asyncResult.CallUserCallback();
}
else
{
// For Synchronous IO, I could go with either a userCallback and using
// the managed Monitor class, or I could create a handle and wait on it.
ManualResetEvent waitHandle = new ManualResetEvent(false);
asyncResult._waitHandle = waitHandle;
// Create a managed overlapped class; set the file offsets later
Overlapped overlapped = new Overlapped();
overlapped.OffsetLow = 0;
overlapped.OffsetHigh = 0;
overlapped.AsyncResult = asyncResult;
// Pack the Overlapped class, and store it in the async result
NativeOverlapped* intOverlapped;
intOverlapped = overlapped.Pack(s_IOCallback, buffer);
asyncResult._overlapped = intOverlapped;
// Queue an async ReadFile operation and pass in a packed overlapped
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, offset, count, intOverlapped, out errorCode);
// ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper
// returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer read back from this call
// when using overlapped structures! You must not pass in a non-null lpNumBytesRead to
// ReadFile when using overlapped structures! This is by design NT behavior.
if (r == -1)
{
// One side has closed its handle or server disconnected. Set the state to Broken
// and do some cleanup work
if (errorCode == Interop.ERROR_BROKEN_PIPE ||
errorCode == Interop.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
// Clear the overlapped status bit for this special case. Failure to do so looks
// like we are freeing a pending overlapped.
intOverlapped->InternalLow = IntPtr.Zero;
// EndRead will free the Overlapped struct
asyncResult.CallUserCallback();
}
else if (errorCode != Interop.ERROR_IO_PENDING)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
if (readWriteParams != null)
{
if (readWriteParams.CancellationHelper != null)
{
readWriteParams.CancellationHelper.AllowCancellation(_handle, intOverlapped);
}
}
}
return asyncResult;
}
[SecurityCritical]
private unsafe int EndRead(IAsyncResult asyncResult)
{
// There are 3 significantly different IAsyncResults we'll accept
// here. One is from Stream::BeginRead. The other two are variations
// on our PipeStreamAsyncResult. One is from BeginReadCore,
// while the other is from the BeginRead buffering wrapper.
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
if (!_isAsync)
{
return _streamAsyncHelper.EndRead(asyncResult);
}
PipeStreamAsyncResult afsar = asyncResult as PipeStreamAsyncResult;
if (afsar == null || afsar._isWrite)
{
throw __Error.GetWrongAsyncResult();
}
// Ensure we can't get into any races by doing an interlocked
// CompareExchange here. Avoids corrupting memory via freeing the
// NativeOverlapped class or GCHandle twice.
if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
{
throw __Error.GetEndReadCalledTwice();
}
ReadWriteAsyncParams readWriteParams = asyncResult.AsyncState as ReadWriteAsyncParams;
IOCancellationHelper cancellationHelper = null;
if (readWriteParams != null)
{
cancellationHelper = readWriteParams.CancellationHelper;
if (cancellationHelper != null)
{
readWriteParams.CancellationHelper.SetOperationCompleted();
}
}
// Obtain the WaitHandle, but don't use public property in case we
// delay initialize the manual reset event in the future.
WaitHandle wh = afsar._waitHandle;
if (wh != null)
{
// We must block to ensure that AsyncPSCallback has completed,
// and we should close the WaitHandle in here. AsyncPSCallback
// and the hand-ported imitation version in COMThreadPool.cpp
// are the only places that set this event.
using (wh)
{
wh.WaitOne();
Debug.Assert(afsar._isComplete == true,
"FileStream::EndRead - AsyncPSCallback didn't set _isComplete to true!");
}
}
// Free memory & GC handles.
NativeOverlapped* overlappedPtr = afsar._overlapped;
if (overlappedPtr != null)
{
Overlapped.Free(overlappedPtr);
}
// Now check for any error during the read.
if (afsar._errorCode != 0)
{
if (afsar._errorCode == Interop.ERROR_OPERATION_ABORTED)
{
if (cancellationHelper != null)
{
cancellationHelper.ThrowIOOperationAborted();
}
}
WinIOError(afsar._errorCode);
}
// set message complete to true if the pipe is broken as well; need this to signal to readers
// to stop reading
_isMessageComplete = _state == PipeState.Broken ||
afsar._isMessageComplete;
return afsar._numBytes;
}
[SecurityCritical]
private unsafe void WriteCore(byte[] buffer, int offset, int count)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanWrite, "can't write");
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
if (_isAsync)
{
IAsyncResult result = BeginWriteCore(buffer, offset, count, null, null);
EndWrite(result);
return;
}
int errorCode = 0;
int r = WriteFileNative(_handle, buffer, offset, count, null, out errorCode);
if (r == -1)
{
WinIOError(errorCode);
}
Debug.Assert(r >= 0, "PipeStream's WriteCore is likely broken.");
return;
}
[SecurityCritical]
private IAsyncResult BeginWrite(AsyncCallback callback, Object state)
{
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
Debug.Assert(readWriteParams != null);
byte[] buffer = readWriteParams.Buffer;
int offset = readWriteParams.Offset;
int count = readWriteParams.Count;
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
CheckWriteOperations();
if (!_isAsync)
{
return _streamAsyncHelper.BeginWrite(buffer, offset, count, callback, state);
}
else
{
return BeginWriteCore(buffer, offset, count, callback, state);
}
}
[SecurityCritical]
unsafe private PipeStreamAsyncResult BeginWriteCore(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanWrite, "can't write");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert(_isAsync, "BeginWriteCore doesn't work on synchronous file streams!");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
// Create and store async stream class library specific data in the async result
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = true;
asyncResult._handle = _handle;
// fixed doesn't work well with zero length arrays. Set the zero-byte flag in case
// caller needs to do any cleanup
if (buffer.Length == 0)
{
//intOverlapped->InternalLow = IntPtr.Zero;
// EndRead will free the Overlapped struct
asyncResult.CallUserCallback();
}
else
{
// For Synchronous IO, I could go with either a userCallback and using the managed
// Monitor class, or I could create a handle and wait on it.
ManualResetEvent waitHandle = new ManualResetEvent(false);
asyncResult._waitHandle = waitHandle;
// Create a managed overlapped class; set the file offsets later
Overlapped overlapped = new Overlapped();
overlapped.OffsetLow = 0;
overlapped.OffsetHigh = 0;
overlapped.AsyncResult = asyncResult;
// Pack the Overlapped class, and store it in the async result
NativeOverlapped* intOverlapped = overlapped.Pack(s_IOCallback, buffer);
asyncResult._overlapped = intOverlapped;
int errorCode = 0;
// Queue an async WriteFile operation and pass in a packed overlapped
int r = WriteFileNative(_handle, buffer, offset, count, intOverlapped, out errorCode);
// WriteFile, the OS version, will return 0 on failure, but this WriteFileNative
// wrapper returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer written back from this
// call when using overlapped structures! You must not pass in a non-null
// lpNumBytesWritten to WriteFile when using overlapped structures! This is by design
// NT behavior.
if (r == -1 && errorCode != Interop.ERROR_IO_PENDING)
{
// Clean up
if (intOverlapped != null) Overlapped.Free(intOverlapped);
WinIOError(errorCode);
}
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
if (readWriteParams != null)
{
if (readWriteParams.CancellationHelper != null)
{
readWriteParams.CancellationHelper.AllowCancellation(_handle, intOverlapped);
}
}
}
return asyncResult;
}
[SecurityCritical]
private unsafe void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
if (!_isAsync)
{
_streamAsyncHelper.EndWrite(asyncResult);
return;
}
PipeStreamAsyncResult afsar = asyncResult as PipeStreamAsyncResult;
if (afsar == null || !afsar._isWrite)
{
throw __Error.GetWrongAsyncResult();
}
// Ensure we can't get into any races by doing an interlocked
// CompareExchange here. Avoids corrupting memory via freeing the
// NativeOverlapped class or GCHandle twice. --
if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
{
throw __Error.GetEndWriteCalledTwice();
}
ReadWriteAsyncParams readWriteParams = afsar.AsyncState as ReadWriteAsyncParams;
IOCancellationHelper cancellationHelper = null;
if (readWriteParams != null)
{
cancellationHelper = readWriteParams.CancellationHelper;
if (cancellationHelper != null)
{
cancellationHelper.SetOperationCompleted();
}
}
// Obtain the WaitHandle, but don't use public property in case we
// delay initialize the manual reset event in the future.
WaitHandle wh = afsar._waitHandle;
if (wh != null)
{
// We must block to ensure that AsyncPSCallback has completed,
// and we should close the WaitHandle in here. AsyncPSCallback
// and the hand-ported imitation version in COMThreadPool.cpp
// are the only places that set this event.
using (wh)
{
wh.WaitOne();
Debug.Assert(afsar._isComplete == true, "PipeStream::EndWrite - AsyncPSCallback didn't set _isComplete to true!");
}
}
// Free memory & GC handles.
NativeOverlapped* overlappedPtr = afsar._overlapped;
if (overlappedPtr != null)
{
Overlapped.Free(overlappedPtr);
}
// Now check for any error during the write.
if (afsar._errorCode != 0)
{
if (afsar._errorCode == Interop.ERROR_OPERATION_ABORTED)
{
if (cancellationHelper != null)
{
cancellationHelper.ThrowIOOperationAborted();
}
}
WinIOError(afsar._errorCode);
}
// Number of buffer written is afsar._numBytes.
return;
}
[SecuritySafeCritical]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckReadOperations();
if (!_isAsync)
{
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
ReadWriteAsyncParams state = new ReadWriteAsyncParams(buffer, offset, count, cancellationToken);
return Task.Factory.FromAsync<int>(BeginRead, EndRead, state);
}
[SecuritySafeCritical]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckWriteOperations();
if (!_isAsync)
{
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
ReadWriteAsyncParams state = new ReadWriteAsyncParams(buffer, offset, count, cancellationToken);
return Task.Factory.FromAsync(BeginWrite, EndWrite, state);
}
[SecurityCritical]
private unsafe int ReadFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count,
NativeOverlapped* overlapped, out int errorCode)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative.");
Debug.Assert(buffer.Length - offset >= count, "offset + count >= buffer length");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int r = 0;
int numBytesRead = 0;
fixed (byte* p = buffer)
{
if (_isAsync)
{
r = Interop.mincore.ReadFile(handle, p + offset, count, IntPtr.Zero, overlapped);
}
else
{
r = Interop.mincore.ReadFile(handle, p + offset, count, out numBytesRead, IntPtr.Zero);
}
}
if (r == 0)
{
// We should never silently swallow an error here without some
// extra work. We must make sure that BeginReadCore won't return an
// IAsyncResult that will cause EndRead to block, since the OS won't
// call AsyncPSCallback for us.
errorCode = Marshal.GetLastWin32Error();
// In message mode, the ReadFile can inform us that there is more data to come.
if (errorCode == Interop.ERROR_MORE_DATA)
{
return numBytesRead;
}
return -1;
}
else
{
errorCode = 0;
}
return numBytesRead;
}
[SecurityCritical]
private unsafe int WriteFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count,
NativeOverlapped* overlapped, out int errorCode)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative.");
Debug.Assert(buffer.Length - offset >= count, "offset + count >= buffer length");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int numBytesWritten = 0;
int r = 0;
fixed (byte* p = buffer)
{
if (_isAsync)
{
r = Interop.mincore.WriteFile(handle, p + offset, count, IntPtr.Zero, overlapped);
}
else
{
r = Interop.mincore.WriteFile(handle, p + offset, count, out numBytesWritten, IntPtr.Zero);
}
}
if (r == 0)
{
// We should never silently swallow an error here without some
// extra work. We must make sure that BeginWriteCore won't return an
// IAsyncResult that will cause EndWrite to block, since the OS won't
// call AsyncPSCallback for us.
errorCode = Marshal.GetLastWin32Error();
return -1;
}
else
{
errorCode = 0;
}
return numBytesWritten;
}
// Blocks until the other end of the pipe has read in all written buffer.
[SecurityCritical]
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
// Block until other end of the pipe has read everything.
if (!Interop.mincore.FlushFileBuffers(_handle))
{
WinIOError(Marshal.GetLastWin32Error());
}
}
// ********************** Public Properties *********************** //
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (_isFromExistingHandle)
{
int pipeFlags;
if (!Interop.mincore.GetNamedPipeInfo(_handle, out pipeFlags, Interop.NULL, Interop.NULL,
Interop.NULL))
{
WinIOError(Marshal.GetLastWin32Error());
}
if ((pipeFlags & Interop.PIPE_TYPE_MESSAGE) != 0)
{
return PipeTransmissionMode.Message;
}
else
{
return PipeTransmissionMode.Byte;
}
}
else
{
return _transmissionMode;
}
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
int inBufferSize;
if (!Interop.mincore.GetNamedPipeInfo(_handle, Interop.NULL, Interop.NULL, out inBufferSize, Interop.NULL))
{
WinIOError(Marshal.GetLastWin32Error());
}
return inBufferSize;
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
int outBufferSize;
// Use cached value if direction is out; otherwise get fresh version
if (_pipeDirection == PipeDirection.Out)
{
outBufferSize = _outBufferSize;
}
else if (!Interop.mincore.GetNamedPipeInfo(_handle, Interop.NULL, out outBufferSize,
Interop.NULL, Interop.NULL))
{
WinIOError(Marshal.GetLastWin32Error());
}
return outBufferSize;
}
}
public virtual PipeTransmissionMode ReadMode
{
[SecurityCritical]
get
{
CheckPipePropertyOperations();
// get fresh value if it could be stale
if (_isFromExistingHandle || IsHandleExposed)
{
UpdateReadMode();
}
return _readMode;
}
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
// Nothing fancy here. This is just a wrapper around the Win32 API. Note, that NamedPipeServerStream
// and the AnonymousPipeStreams override this.
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
unsafe
{
int pipeReadType = (int)value << 1;
if (!Interop.mincore.SetNamedPipeHandleState(_handle, &pipeReadType, Interop.NULL, Interop.NULL))
{
WinIOError(Marshal.GetLastWin32Error());
}
else
{
_readMode = value;
}
}
}
}
/// <summary>
/// Determine pipe read mode from Win32
/// </summary>
[SecurityCritical]
private void UpdateReadMode()
{
int flags;
if (!Interop.mincore.GetNamedPipeHandleState(SafePipeHandle, out flags, Interop.NULL, Interop.NULL,
Interop.NULL, Interop.NULL, 0))
{
WinIOError(Marshal.GetLastWin32Error());
}
if ((flags & Interop.PIPE_READMODE_MESSAGE) != 0)
{
_readMode = PipeTransmissionMode.Message;
}
else
{
_readMode = PipeTransmissionMode.Byte;
}
}
/// <summary>
/// Filter out all pipe related errors and do some cleanup before calling __Error.WinIOError.
/// </summary>
/// <param name="errorCode"></param>
[SecurityCritical]
internal void WinIOError(int errorCode)
{
if (errorCode == Interop.ERROR_BROKEN_PIPE ||
errorCode == Interop.ERROR_PIPE_NOT_CONNECTED ||
errorCode == Interop.ERROR_NO_DATA
)
{
// Other side has broken the connection
_state = PipeState.Broken;
throw new IOException(SR.IO_PipeBroken, Win32Marshal.MakeHRFromErrorCode(errorCode));
}
else if (errorCode == Interop.ERROR_HANDLE_EOF)
{
throw __Error.GetEndOfFile();
}
else
{
// For invalid handles, detect the error and mark our handle
// as invalid to give slightly better error messages. Also
// help ensure we avoid handle recycling bugs.
if (errorCode == Interop.ERROR_INVALID_HANDLE)
{
_handle.SetHandleAsInvalid();
_state = PipeState.Broken;
}
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
// ************************ Static Methods ************************ //
[SecurityCritical]
internal static Interop.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability)
{
Interop.SECURITY_ATTRIBUTES secAttrs = default(Interop.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
secAttrs = new Interop.SECURITY_ATTRIBUTES();
secAttrs.nLength = (uint)Marshal.SizeOf(secAttrs);
secAttrs.bInheritHandle = true;
}
return secAttrs;
}
// When doing IO asynchronously (i.e., _isAsync==true), this callback is
// called by a free thread in the threadpool when the IO operation
// completes.
[SecurityCritical]
unsafe private static void AsyncPSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
// Unpack overlapped
Overlapped overlapped = Overlapped.Unpack(pOverlapped);
// Free the overlapped struct in EndRead/EndWrite.
// Extract async result from overlapped
PipeStreamAsyncResult asyncResult = (PipeStreamAsyncResult)overlapped.AsyncResult;
asyncResult._numBytes = (int)numBytes;
// Allow async read to finish
if (!asyncResult._isWrite)
{
if (errorCode == Interop.ERROR_BROKEN_PIPE ||
errorCode == Interop.ERROR_PIPE_NOT_CONNECTED ||
errorCode == Interop.ERROR_NO_DATA)
{
errorCode = 0;
numBytes = 0;
}
}
// For message type buffer.
if (errorCode == Interop.ERROR_MORE_DATA)
{
errorCode = 0;
asyncResult._isMessageComplete = false;
}
else
{
asyncResult._isMessageComplete = true;
}
asyncResult._errorCode = (int)errorCode;
// Call the user-provided callback. It can and often should
// call EndRead or EndWrite. There's no reason to use an async
// delegate here - we're already on a threadpool thread.
// IAsyncResult's completedSynchronously property must return
// false here, saying the user callback was called on another thread.
asyncResult._completedSynchronously = false;
asyncResult._isComplete = true;
// The OS does not signal this event. We must do it ourselves.
ManualResetEvent wh = asyncResult._waitHandle;
if (wh != null)
{
Debug.Assert(!wh.GetSafeWaitHandle().IsClosed, "ManualResetEvent already closed!");
bool r = wh.Set();
Debug.Assert(r, "ManualResetEvent::Set failed!");
if (!r)
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
AsyncCallback callback = asyncResult._userCallback;
if (callback != null)
{
callback(asyncResult);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Hydra.Framework;
namespace Hydra.SharedCache.Common
{
//
// **********************************************************************
/// <summary>
/// This class defines cache items in cache based on various properties
/// and configuration option to clear up memory.
/// </summary>
// **********************************************************************
//
[Serializable]
public class Cleanup
: IComparable<Cleanup>
{
//
// **********************************************************************
/// <summary>
/// Defines the sorting order of cleanup objects
/// </summary>
// **********************************************************************
//
public enum SortingOrder
{
//
// **********************************************************************
/// <summary>
/// ascending sorting order
/// </summary>
// **********************************************************************
//
Asc,
//
// **********************************************************************
/// <summary>
/// descending sorting order
/// </summary>
// **********************************************************************
//
Desc
}
private string key;
//
// **********************************************************************
/// <summary>
/// Gets/sets the Key
/// </summary>
// **********************************************************************
//
public string Key
{
[System.Diagnostics.DebuggerStepThrough]
get
{
return this.key;
}
}
private static SortingOrder sorting = SortingOrder.Asc;
//
// **********************************************************************
/// <summary>
/// Gets/sets the Sorting
/// </summary>
// **********************************************************************
//
public static SortingOrder Sorting
{
[System.Diagnostics.DebuggerStepThrough]
get
{
return sorting;
}
[System.Diagnostics.DebuggerStepThrough]
set
{
sorting = value;
}
}
//
// private Enums.ServiceCacheCleanUp cleanupCacheConfiguration = Enums.ServiceCacheCleanUp.CACHEITEMPRIORITY;
//
private Enums.ServiceCacheCleanUp cleanupCacheConfiguration;
private static bool cleanupValueParsed = false;
//
// **********************************************************************
/// <summary>
/// Gets/sets the CleanupCacheConfiguration
/// Defines the cleanup cache configuration, the default value is CACHEITEMPRIORITY [check <see cref="Enums.ServiceCacheCleanUp"/> for more information]
/// </summary>
// **********************************************************************
//
public Enums.ServiceCacheCleanUp CleanupCacheConfiguration
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (!cleanupValueParsed)
{
try
{
//
// validate configuration entry
//
this.cleanupCacheConfiguration = Provider.Server.LBSServerReplicationCache.ProviderSection.ServerSetting.ServiceCacheCleanup;
}
catch (Exception ex)
{
string msg = @"Configuration failure, please validate your [ServiceCacheCleanUp] key, it contains an invalid value!! Current configured value: {0}; As standard the CACHEITEMPRIORITY has been set.";
Log.Error(string.Format(msg, Provider.Server.LBSServerReplicationCache.ProviderSection.ServerSetting.ServiceCacheCleanup), ex);
this.cleanupCacheConfiguration = Enums.ServiceCacheCleanUp.CACHEITEMPRIORITY;
}
cleanupValueParsed = true;
}
return this.cleanupCacheConfiguration;
}
[System.Diagnostics.DebuggerStepThrough]
set
{
this.cleanupCacheConfiguration = value;
}
}
private CacheItemPriorityType prio = CacheItemPriorityType.Normal;
//
// **********************************************************************
/// <summary>
/// Defines the object priority of the cache item.
/// Gets/sets the Prio
/// </summary>
// **********************************************************************
//
public CacheItemPriorityType Prio
{
[System.Diagnostics.DebuggerStepThrough]
get
{
return this.prio;
}
[System.Diagnostics.DebuggerStepThrough]
set
{
this.prio = value;
}
}
private TimeSpan span;
//
// **********************************************************************
/// <summary>
/// Gets/sets the Span - calculate how much time left until the item
/// will be deleted from the cache.
/// </summary>
// **********************************************************************
//
public TimeSpan Span
{
[System.Diagnostics.DebuggerStepThrough]
get
{
return this.span;
}
[System.Diagnostics.DebuggerStepThrough]
set
{
this.span = value;
}
}
private long hitRatio = 0;
//
// **********************************************************************
/// <summary>
/// Gets/sets the HitRatio
/// </summary>
// **********************************************************************
//
public long HitRatio
{
[System.Diagnostics.DebuggerStepThrough]
get
{
return this.hitRatio;
}
[System.Diagnostics.DebuggerStepThrough]
set
{
this.hitRatio = value;
}
}
private DateTime usageDatetime;
//
// **********************************************************************
/// <summary>
/// Gets/sets the UsageDatetime
/// </summary>
// **********************************************************************
//
public DateTime UsageDatetime
{
[System.Diagnostics.DebuggerStepThrough]
get
{
return this.usageDatetime;
}
[System.Diagnostics.DebuggerStepThrough]
set
{
this.usageDatetime = value;
}
}
private long objectSize;
//
// **********************************************************************
/// <summary>
/// Gets/sets the ObjectSize
/// </summary>
// **********************************************************************
//
public long ObjectSize
{
[System.Diagnostics.DebuggerStepThrough]
get
{
return this.objectSize;
}
[System.Diagnostics.DebuggerStepThrough]
set
{
this.objectSize = value;
}
}
private long hybridPoint = -1;
//
// **********************************************************************
/// <summary>
/// Gets/sets the HybridPoint
/// </summary>
// **********************************************************************
//
public long HybridPoint
{
[System.Diagnostics.DebuggerStepThrough]
get
{
return this.hybridPoint;
}
[System.Diagnostics.DebuggerStepThrough]
set
{
this.hybridPoint = value;
}
}
#region Constructor
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="Cleanup"/> class.
/// </summary>
// **********************************************************************
//
public Cleanup()
{
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="Cleanup"/> class.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="prio">The prio.</param>
/// <param name="span">The span.</param>
/// <param name="hitRatio">The hit ratio.</param>
/// <param name="usageDatetime">The usage datetime.</param>
/// <param name="objectSize">Size of the object.</param>
/// <param name="hybridPoint">The hybrid point.</param>
// **********************************************************************
//
public Cleanup(string key, CacheItemPriorityType prio, TimeSpan span, long hitRatio, DateTime usageDatetime, long objectSize, int hybridPoint)
: this()
{
this.key = key;
this.prio = prio;
this.span = span;
this.hitRatio = hitRatio;
this.usageDatetime = usageDatetime;
this.objectSize = objectSize;
this.hybridPoint = hybridPoint;
}
#endregion Constructor
#region Methods
//
// **********************************************************************
/// <summary>
/// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </returns>
// **********************************************************************
//
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Prio: {0}; \tspan: {1}; \tUsageCntr: {2}; \tUsageDateTime: {3}; \tSize: {4}; \tHyb.Pnt: {5};",
this.prio, this.span, this.hitRatio, this.usageDatetime, this.objectSize, this.hybridPoint);
return sb.ToString();
}
#endregion
#region IComparable<Cleanup> Members
//
// **********************************************************************
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the other parameter.Zero This object is equal to other. Greater than zero This object is greater than other.
/// </returns>
// **********************************************************************
//
public int CompareTo(Cleanup other)
{
return this.cleanupCacheConfiguration.CompareTo(other.cleanupCacheConfiguration);
}
#endregion
//
// **********************************************************************
/// <summary>
/// Sorts the list for cleanup based on the configuration entry it will sort the
/// objects in a correct order to start to delete entries from the cache. Start point
/// to delete is always the first object.
/// </summary>
/// <param name="listToSort">The list to sort, the list contains objects of type <see cref="Cleanup"/></param>
// **********************************************************************
//
private void SortListForCleanup(List<Cleanup> listToSort)
{
switch (this.cleanupCacheConfiguration)
{
case Enums.ServiceCacheCleanUp.HYBRID:
Cleanup.Sorting = SortingOrder.Desc;
listToSort.Sort(Cleanup.CacheItemHybridPoints);
break;
case Enums.ServiceCacheCleanUp.LFU:
Cleanup.Sorting = SortingOrder.Desc;
listToSort.Sort(Cleanup.CacheItemHitRatio);
break;
case Enums.ServiceCacheCleanUp.LLF:
case Enums.ServiceCacheCleanUp.SIZE:
Cleanup.Sorting = SortingOrder.Desc;
listToSort.Sort(Cleanup.CacheItemObjectSize);
break;
case Enums.ServiceCacheCleanUp.LRU:
Cleanup.Sorting = SortingOrder.Desc;
listToSort.Sort(Cleanup.CacheItemHitRatio);
break;
case Enums.ServiceCacheCleanUp.TIMEBASED:
Cleanup.Sorting = SortingOrder.Desc;
listToSort.Sort(Cleanup.CacheItemUsageDateTime);
break;
}
}
#region static specific comparable methods
//
// **********************************************************************
/// <summary>
/// comparsion based on object priority
/// </summary>
// **********************************************************************
//
public static Comparison<Cleanup> CacheItemPriority = delegate(Cleanup cu1, Cleanup cu2)
{
if (Cleanup.Sorting == SortingOrder.Asc)
{
return cu1.prio.CompareTo(cu2.prio);
}
else
{
return cu2.prio.CompareTo(cu1.prio);
}
};
//
// **********************************************************************
/// <summary>
/// Comparsion based on cache item time span
/// </summary>
// **********************************************************************
//
public static Comparison<Cleanup> CacheItemTimeSpan = delegate(Cleanup cu1, Cleanup cu2)
{
if (Cleanup.Sorting == SortingOrder.Asc)
{
return cu1.span.CompareTo(cu2.span);
}
else
{
return cu2.span.CompareTo(cu1.span);
}
};
//
// **********************************************************************
/// <summary>
/// Comparsion based on item hit ratio
/// </summary>
// **********************************************************************
//
public static Comparison<Cleanup> CacheItemHitRatio = delegate(Cleanup cu1, Cleanup cu2)
{
if (Cleanup.Sorting == SortingOrder.Asc)
{
return cu1.hitRatio.CompareTo(cu2.hitRatio);
}
else
{
return cu2.hitRatio.CompareTo(cu1.hitRatio);
}
};
//
// **********************************************************************
/// <summary>
/// Comparsion based on open usage date time
/// </summary>
// **********************************************************************
//
public static Comparison<Cleanup> CacheItemUsageDateTime = delegate(Cleanup cu1, Cleanup cu2)
{
if (Cleanup.Sorting == SortingOrder.Asc)
{
return cu1.usageDatetime.CompareTo(cu2.usageDatetime);
}
else
{
return cu2.usageDatetime.CompareTo(cu1.usageDatetime);
}
};
//
// **********************************************************************
/// <summary>
/// Comparsion based on object size
/// </summary>
// **********************************************************************
//
public static Comparison<Cleanup> CacheItemObjectSize = delegate(Cleanup cu1, Cleanup cu2)
{
if (Cleanup.Sorting == SortingOrder.Asc)
{
return cu1.objectSize.CompareTo(cu2.objectSize);
}
else
{
return cu2.objectSize.CompareTo(cu1.objectSize);
}
};
//
// **********************************************************************
/// <summary>
/// Specific comparsion based on hybrid points.
/// </summary>
// **********************************************************************
//
public static Comparison<Cleanup> CacheItemHybridPoints = delegate(Cleanup cu1, Cleanup cu2)
{
if (Cleanup.Sorting == SortingOrder.Asc)
{
return cu1.hybridPoint.CompareTo(cu2.hybridPoint);
}
else
{
return cu2.hybridPoint.CompareTo(cu1.hybridPoint);
}
};
#endregion static specific comparable methods
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.ExtensionsExplorer;
using NuGet.VisualStudio;
namespace NuGet.Dialog.Providers
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
internal abstract class PackagesTreeNodeBase : IVsExtensionsTreeNode, IVsSortDataSource, IVsProgressPaneConsumer, INotifyPropertyChanged, IVsMessagePaneConsumer
{
// The number of extensions to show per page for online
public const int DefaultItemsPerPage = 10;
// We cache the query until it changes (due to sort order or search)
private IEnumerable<IPackage> _query;
private int _totalCount;
#if VS10
private IList<IVsExtension> _extensions;
#else
private IList _extensions;
#endif
private IList<IVsExtensionsTreeNode> _nodes;
private int _totalPages = 1, _currentPage = 1;
private bool _progressPaneActive;
private bool _isExpanded;
private bool _isSelected;
private bool _loadingInProgress;
private bool _includePrereleaseWhenLastLoaded;
private readonly bool _collapseVersions;
// true if packages are fetched in pages. Otherwise, all packages are fetched in 1 page.
private bool _isPaged;
private CancellationTokenSource _currentCancellationSource;
public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler<EventArgs> PageDataChanged;
protected PackagesTreeNodeBase(IVsExtensionsTreeNode parent, PackagesProviderBase provider, bool collapseVersions = true)
{
Debug.Assert(provider != null);
_collapseVersions = collapseVersions;
Parent = parent;
Provider = provider;
PageSize = DefaultItemsPerPage;
_isPaged = this is IVsPageDataSource;
}
public bool CollapseVersions
{
get
{
return _collapseVersions;
}
}
public bool IsPaged
{
get
{
return _isPaged;
}
}
protected PackagesProviderBase Provider
{
get;
private set;
}
private IVsProgressPane ProgressPane
{
get;
set;
}
private IVsMessagePane MessagePane
{
get;
set;
}
/// <summary>
/// Name of this node
/// </summary>
public abstract string Name
{
get;
}
public bool IsSearchResultsNode
{
get;
set;
}
/// <summary>
/// Select node (UI) property
/// This property maps to TreeViewItem.IsSelected
/// </summary>
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
if (_isSelected != value)
{
_isSelected = value;
OnNotifyPropertyChanged("IsSelected");
}
}
}
public abstract bool SupportsPrereleasePackages { get; }
/// <summary>
/// Expand node (UI) property
/// This property maps to TreeViewItem.IsExpanded
/// </summary>
public bool IsExpanded
{
get
{
return _isExpanded;
}
set
{
if (_isExpanded != value)
{
_isExpanded = value;
OnNotifyPropertyChanged("IsExpanded");
}
}
}
/// <summary>
/// List of templates at this node for the current page only
/// </summary>
#if VS10
public IList<IVsExtension> Extensions
{
#else
public IList Extensions {
#endif
get
{
if (_extensions == null)
{
EnsureExtensionCollection();
LoadPage(1);
}
return _extensions;
}
}
/// <summary>
/// Children at this node
/// </summary>
public IList<IVsExtensionsTreeNode> Nodes
{
get
{
if (_nodes == null)
{
_nodes = new ObservableCollection<IVsExtensionsTreeNode>();
}
return _nodes;
}
}
/// <summary>
/// Parent of this node
/// </summary>
public IVsExtensionsTreeNode Parent
{
get;
private set;
}
public int TotalPages
{
get
{
return _totalPages;
}
internal set
{
_totalPages = value;
NotifyPropertyChanged();
}
}
public int CurrentPage
{
get
{
return _currentPage;
}
internal set
{
_currentPage = value;
NotifyPropertyChanged();
}
}
public int TotalNumberOfPackages
{
get
{
return _totalCount;
}
}
/// <summary>
/// Raised when the current node completes loading packages.
/// </summary>
internal event EventHandler PackageLoadCompleted = delegate { };
internal int PageSize
{
get;
set;
}
/// <summary>
/// Refresh the list of packages belong to this node
/// </summary>
public virtual void Refresh(bool resetQueryBeforeRefresh = false)
{
if (resetQueryBeforeRefresh)
{
ResetQuery();
}
LoadPage(CurrentPage);
}
public override string ToString()
{
return Name;
}
/// <summary>
/// Get all packages belonging to this node.
/// </summary>
/// <returns></returns>
public abstract IQueryable<IPackage> GetPackages(string searchTerm, bool allowPrereleaseVersions);
/// <summary>
/// Helper function to raise property changed events
/// </summary>
private void NotifyPropertyChanged()
{
if (PageDataChanged != null)
{
PageDataChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// Loads the packages in the specified page.
/// </summary>
/// <param name="pageNumber"></param>
public void LoadPage(int pageNumber)
{
if (pageNumber < 1)
{
throw new ArgumentOutOfRangeException(
"pageNumber",
String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 1));
}
if (_loadingInProgress || Provider.SuppressLoad)
{
return;
}
EnsureExtensionCollection();
// Bug #1930: this will clear the content of details pane
Extensions.Clear();
ShowProgressPane();
// avoid more than one loading occurring at the same time
_loadingInProgress = true;
_includePrereleaseWhenLastLoaded = Provider.IncludePrerelease;
_currentCancellationSource = new CancellationTokenSource();
TaskScheduler uiScheduler;
try
{
uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
}
catch (InvalidOperationException)
{
// FromCurrentSynchronizationContext() fails when running from unit test
uiScheduler = TaskScheduler.Default;
}
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageLoadBegin);
Task.Factory.StartNew(
(state) => ExecuteAsync(pageNumber, _currentCancellationSource.Token),
_currentCancellationSource,
_currentCancellationSource.Token).ContinueWith(QueryExecutionCompleted, uiScheduler);
}
private void EnsureExtensionCollection()
{
if (_extensions == null)
{
_extensions = new ObservableCollection<IVsExtension>();
}
}
/// <summary>
/// Called when user clicks on the Cancel button in the progress pane.
/// </summary>
private void CancelCurrentExtensionQuery()
{
Debug.WriteLine("Cancelling pending extensions query.");
if (_currentCancellationSource != null)
{
_currentCancellationSource.Cancel();
_loadingInProgress = false;
Provider.RemoveSearchNode();
}
}
/// <summary>
/// This method executes on background thread.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We want to show error message inside the dialog, rather than blowing up VS.")]
private LoadPageResult ExecuteAsync(int pageNumber, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (_query == null)
{
IQueryable<IPackage> query = GetPackages(searchTerm: null, allowPrereleaseVersions: Provider.IncludePrerelease);
if (CollapseVersions)
{
query = CollapsePackageVersions(query);
}
token.ThrowIfCancellationRequested();
// Execute the total count query
_totalCount = query.Count();
if (_totalCount == 0)
{
return new LoadPageResult(new IPackage[0], 0, 0);
}
if (!_isPaged)
{
PageSize = _totalCount;
}
// make sure we don't query a page that is greater than the maximum page number.
int maximumPages = (_totalCount + PageSize - 1)/PageSize;
pageNumber = Math.Min(pageNumber, maximumPages);
token.ThrowIfCancellationRequested();
IQueryable<IPackage> orderedQuery = ApplyOrdering(query);
// Buffer 3 pages
_query = orderedQuery.AsBufferedEnumerable(PageSize * 3);
if (CollapseVersions)
{
// If we are connecting to an older gallery implementation, we need to use the Published field.
// For newer gallery, the package is never unpublished, it is only unlisted.
_query = _query.Where(PackageExtensions.IsListed).AsCollapsed();
}
}
IList<IPackage> packages = _query.Skip((pageNumber - 1) * PageSize)
.Take(PageSize)
.ToList();
if (packages.Count < PageSize)
{
_totalCount = (pageNumber - 1) * PageSize + packages.Count;
}
token.ThrowIfCancellationRequested();
return new LoadPageResult(packages, pageNumber, _totalCount);
}
protected virtual IQueryable<IPackage> CollapsePackageVersions(IQueryable<IPackage> packages)
{
if (Provider.IncludePrerelease && SupportsPrereleasePackages)
{
return packages.Where(p => p.IsAbsoluteLatestVersion);
}
else
{
return packages.Where(p => p.IsLatestVersion);
}
}
protected virtual IQueryable<IPackage> ApplyOrdering(IQueryable<IPackage> query)
{
// If the default sort is null then fall back to download count
IOrderedQueryable<IPackage> result;
if (Provider.CurrentSort == null)
{
result = query.OrderByDescending(p => p.DownloadCount);
}
else
{
// Order by the current descriptor
result = query.SortBy<IPackage>(Provider.CurrentSort.SortProperties, Provider.CurrentSort.Direction);
}
return result.ThenBy(p => p.Id);
}
public IList<IVsSortDescriptor> GetSortDescriptors()
{
// Get the sort descriptor from the provider
return Provider.SortDescriptors;
}
protected internal void ResetQuery()
{
_query = null;
}
public bool SortSelectionChanged(IVsSortDescriptor selectedDescriptor)
{
Provider.CurrentSort = selectedDescriptor as PackageSortDescriptor;
// The value of CurrentSort could be null if we're dealing with the SearchProvider. Use the selectedDescriptor instead since it returns the actual instance.
if (selectedDescriptor != null)
{
// If we changed the sort order then invalidate the cache.
ResetQuery();
// Reload the first page since the sort order changed
LoadPage(1);
return true;
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We don't want it to crash VS.")]
private void QueryExecutionCompleted(Task<LoadPageResult> task)
{
// If a task throws, the exception must be handled or the Exception
// property must be accessed or the exception will tear down the process when finalized
Exception exception = task.Exception;
if (task.IsFaulted)
{
try
{
ExceptionHelper.WriteToActivityLog(exception);
}
catch
{
// don't let this crash VS
}
}
var cancellationSource = (CancellationTokenSource)task.AsyncState;
if (cancellationSource != _currentCancellationSource)
{
return;
}
_loadingInProgress = false;
// Only process the result if this node is still selected.
if (IsSelected)
{
if (task.IsFaulted)
{
if (cancellationSource.IsCancellationRequested)
{
HideProgressPane();
}
else
{
// show error message in the Message pane
ShowMessagePane(ExceptionUtility.Unwrap(exception).Message);
}
}
else if (task.IsCanceled)
{
HideProgressPane();
}
else
{
LoadPageResult result = task.Result;
UpdateNewPackages(result.Packages.ToList());
int totalPages = (result.TotalCount + PageSize - 1) / PageSize;
TotalPages = Math.Max(1, totalPages);
CurrentPage = Math.Max(1, result.PageNumber);
HideProgressPane();
}
}
Provider.OnPackageLoadCompleted(this);
// for unit tests
PackageLoadCompleted(this, EventArgs.Empty);
NuGetEventTrigger.Instance.TriggerEvent(NuGetEvent.PackageLoadEnd);
}
private void UpdateNewPackages(IList<IPackage> packages)
{
int newPackagesIndex = 0;
int oldPackagesIndex = 0;
while (oldPackagesIndex < _extensions.Count)
{
if (newPackagesIndex >= packages.Count)
{
_extensions.RemoveAt(oldPackagesIndex);
}
else
{
PackageItem currentOldItem = (PackageItem)_extensions[oldPackagesIndex];
if (PackageEqualityComparer.IdAndVersion.Equals(packages[newPackagesIndex], currentOldItem.PackageIdentity))
{
newPackagesIndex++;
oldPackagesIndex++;
}
else
{
_extensions.RemoveAt(oldPackagesIndex);
}
}
}
while (newPackagesIndex < packages.Count)
{
var extension = Provider.CreateExtension(packages[newPackagesIndex++]);
if (extension != null)
{
_extensions.Add(extension);
}
}
if (_extensions.Count > 0)
{
// select the first package by default
((IVsExtension)_extensions[0]).IsSelected = true;
}
}
protected void OnNotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public void SetProgressPane(IVsProgressPane progressPane)
{
ProgressPane = progressPane;
}
public void SetMessagePane(IVsMessagePane messagePane)
{
MessagePane = messagePane;
}
protected bool ShowProgressPane()
{
if (ProgressPane != null)
{
_progressPaneActive = true;
return ProgressPane.Show(new CancelProgressCallback(CancelCurrentExtensionQuery), true);
}
else
{
return false;
}
}
protected void HideProgressPane()
{
if (_progressPaneActive && ProgressPane != null)
{
ProgressPane.Close();
_progressPaneActive = false;
}
}
protected bool ShowMessagePane(string message)
{
if (MessagePane != null)
{
MessagePane.SetMessageThreadSafe(message);
return MessagePane.Show();
}
else
{
return false;
}
}
/// <summary>
/// Called when this node is opened.
/// </summary>
internal void OnOpened()
{
if (!Provider.SuppressNextRefresh)
{
Provider.SelectedNode = this;
if (!this.IsSearchResultsNode)
{
// If user switches back to this node, and the Include Prerelease combox box value
// has changed, we need to reload the packages.
//
// This 'if' statement must come before the next one, so that we favor setting
// 'resetQueryBeforeRefresh' to true.
if (_includePrereleaseWhenLastLoaded != Provider.IncludePrerelease)
{
Refresh(resetQueryBeforeRefresh: true);
return;
}
if (Provider.RefreshOnNodeSelection)
{
Refresh();
}
}
}
}
/// <summary>
/// Called when the focus switches away from this node
/// </summary>
internal virtual void OnClosed()
{
if (IsSearchResultsNode)
{
Provider.RemoveSearchNode();
}
}
}
}
| |
namespace android.graphics
{
[global::MonoJavaBridge.JavaClass()]
public partial class Matrix : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static Matrix()
{
InitJNI();
}
protected Matrix(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class ScaleToFit : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ScaleToFit()
{
InitJNI();
}
internal ScaleToFit(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _values3338;
public static global::android.graphics.Matrix.ScaleToFit[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.graphics.Matrix.ScaleToFit>(@__env.CallStaticObjectMethod(android.graphics.Matrix.ScaleToFit.staticClass, global::android.graphics.Matrix.ScaleToFit._values3338)) as android.graphics.Matrix.ScaleToFit[];
}
internal static global::MonoJavaBridge.MethodId _valueOf3339;
public static global::android.graphics.Matrix.ScaleToFit valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.graphics.Matrix.ScaleToFit.staticClass, global::android.graphics.Matrix.ScaleToFit._valueOf3339, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Matrix.ScaleToFit;
}
internal static global::MonoJavaBridge.FieldId _CENTER3340;
public static global::android.graphics.Matrix.ScaleToFit CENTER
{
get
{
return default(global::android.graphics.Matrix.ScaleToFit);
}
}
internal static global::MonoJavaBridge.FieldId _END3341;
public static global::android.graphics.Matrix.ScaleToFit END
{
get
{
return default(global::android.graphics.Matrix.ScaleToFit);
}
}
internal static global::MonoJavaBridge.FieldId _FILL3342;
public static global::android.graphics.Matrix.ScaleToFit FILL
{
get
{
return default(global::android.graphics.Matrix.ScaleToFit);
}
}
internal static global::MonoJavaBridge.FieldId _START3343;
public static global::android.graphics.Matrix.ScaleToFit START
{
get
{
return default(global::android.graphics.Matrix.ScaleToFit);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.Matrix.ScaleToFit.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Matrix$ScaleToFit"));
global::android.graphics.Matrix.ScaleToFit._values3338 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Matrix.ScaleToFit.staticClass, "values", "()[Landroid/graphics/Matrix/ScaleToFit;");
global::android.graphics.Matrix.ScaleToFit._valueOf3339 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Matrix.ScaleToFit.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/graphics/Matrix$ScaleToFit;");
}
}
internal static global::MonoJavaBridge.MethodId _finalize3344;
protected override void finalize()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._finalize3344);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._finalize3344);
}
internal static global::MonoJavaBridge.MethodId _equals3345;
public override bool equals(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._equals3345, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._equals3345, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _toString3346;
public override global::java.lang.String toString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.Matrix._toString3346)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._toString3346)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _set3347;
public virtual void set(android.graphics.Matrix arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._set3347, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._set3347, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _reset3348;
public virtual void reset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._reset3348);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._reset3348);
}
internal static global::MonoJavaBridge.MethodId _toShortString3349;
public virtual global::java.lang.String toShortString()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.Matrix._toShortString3349)) as java.lang.String;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._toShortString3349)) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getValues3350;
public virtual void getValues(float[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._getValues3350, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._getValues3350, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isIdentity3351;
public virtual bool isIdentity()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._isIdentity3351);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._isIdentity3351);
}
internal static global::MonoJavaBridge.MethodId _rectStaysRect3352;
public virtual bool rectStaysRect()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._rectStaysRect3352);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._rectStaysRect3352);
}
internal static global::MonoJavaBridge.MethodId _setTranslate3353;
public virtual void setTranslate(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._setTranslate3353, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setTranslate3353, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setScale3354;
public virtual void setScale(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._setScale3354, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setScale3354, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setScale3355;
public virtual void setScale(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._setScale3355, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setScale3355, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _setRotate3356;
public virtual void setRotate(float arg0, float arg1, float arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._setRotate3356, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setRotate3356, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _setRotate3357;
public virtual void setRotate(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._setRotate3357, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setRotate3357, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setSinCos3358;
public virtual void setSinCos(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._setSinCos3358, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setSinCos3358, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _setSinCos3359;
public virtual void setSinCos(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._setSinCos3359, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setSinCos3359, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setSkew3360;
public virtual void setSkew(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._setSkew3360, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setSkew3360, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _setSkew3361;
public virtual void setSkew(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._setSkew3361, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setSkew3361, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setConcat3362;
public virtual bool setConcat(android.graphics.Matrix arg0, android.graphics.Matrix arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._setConcat3362, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setConcat3362, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _preTranslate3363;
public virtual bool preTranslate(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._preTranslate3363, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._preTranslate3363, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _preScale3364;
public virtual bool preScale(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._preScale3364, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._preScale3364, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _preScale3365;
public virtual bool preScale(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._preScale3365, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._preScale3365, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _preRotate3366;
public virtual bool preRotate(float arg0, float arg1, float arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._preRotate3366, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._preRotate3366, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _preRotate3367;
public virtual bool preRotate(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._preRotate3367, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._preRotate3367, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _preSkew3368;
public virtual bool preSkew(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._preSkew3368, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._preSkew3368, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _preSkew3369;
public virtual bool preSkew(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._preSkew3369, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._preSkew3369, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _preConcat3370;
public virtual bool preConcat(android.graphics.Matrix arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._preConcat3370, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._preConcat3370, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _postTranslate3371;
public virtual bool postTranslate(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._postTranslate3371, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._postTranslate3371, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _postScale3372;
public virtual bool postScale(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._postScale3372, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._postScale3372, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _postScale3373;
public virtual bool postScale(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._postScale3373, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._postScale3373, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _postRotate3374;
public virtual bool postRotate(float arg0, float arg1, float arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._postRotate3374, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._postRotate3374, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _postRotate3375;
public virtual bool postRotate(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._postRotate3375, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._postRotate3375, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _postSkew3376;
public virtual bool postSkew(float arg0, float arg1, float arg2, float arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._postSkew3376, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._postSkew3376, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _postSkew3377;
public virtual bool postSkew(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._postSkew3377, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._postSkew3377, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _postConcat3378;
public virtual bool postConcat(android.graphics.Matrix arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._postConcat3378, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._postConcat3378, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setRectToRect3379;
public virtual bool setRectToRect(android.graphics.RectF arg0, android.graphics.RectF arg1, android.graphics.Matrix.ScaleToFit arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._setRectToRect3379, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setRectToRect3379, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _setPolyToPoly3380;
public virtual bool setPolyToPoly(float[] arg0, int arg1, float[] arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._setPolyToPoly3380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setPolyToPoly3380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _invert3381;
public virtual bool invert(android.graphics.Matrix arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._invert3381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._invert3381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _mapPoints3382;
public virtual void mapPoints(float[] arg0, int arg1, float[] arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._mapPoints3382, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._mapPoints3382, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _mapPoints3383;
public virtual void mapPoints(float[] arg0, float[] arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._mapPoints3383, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._mapPoints3383, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _mapPoints3384;
public virtual void mapPoints(float[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._mapPoints3384, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._mapPoints3384, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _mapVectors3385;
public virtual void mapVectors(float[] arg0, int arg1, float[] arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._mapVectors3385, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._mapVectors3385, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _mapVectors3386;
public virtual void mapVectors(float[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._mapVectors3386, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._mapVectors3386, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _mapVectors3387;
public virtual void mapVectors(float[] arg0, float[] arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._mapVectors3387, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._mapVectors3387, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _mapRect3388;
public virtual bool mapRect(android.graphics.RectF arg0, android.graphics.RectF arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._mapRect3388, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._mapRect3388, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _mapRect3389;
public virtual bool mapRect(android.graphics.RectF arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.Matrix._mapRect3389, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._mapRect3389, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _mapRadius3390;
public virtual float mapRadius(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.graphics.Matrix._mapRadius3390, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._mapRadius3390, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setValues3391;
public virtual void setValues(float[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.Matrix._setValues3391, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.Matrix.staticClass, global::android.graphics.Matrix._setValues3391, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _Matrix3392;
public Matrix() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Matrix.staticClass, global::android.graphics.Matrix._Matrix3392);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _Matrix3393;
public Matrix(android.graphics.Matrix arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Matrix.staticClass, global::android.graphics.Matrix._Matrix3393, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static int MSCALE_X
{
get
{
return 0;
}
}
public static int MSKEW_X
{
get
{
return 1;
}
}
public static int MTRANS_X
{
get
{
return 2;
}
}
public static int MSKEW_Y
{
get
{
return 3;
}
}
public static int MSCALE_Y
{
get
{
return 4;
}
}
public static int MTRANS_Y
{
get
{
return 5;
}
}
public static int MPERSP_0
{
get
{
return 6;
}
}
public static int MPERSP_1
{
get
{
return 7;
}
}
public static int MPERSP_2
{
get
{
return 8;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.Matrix.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Matrix"));
global::android.graphics.Matrix._finalize3344 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "finalize", "()V");
global::android.graphics.Matrix._equals3345 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "equals", "(Ljava/lang/Object;)Z");
global::android.graphics.Matrix._toString3346 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "toString", "()Ljava/lang/String;");
global::android.graphics.Matrix._set3347 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "set", "(Landroid/graphics/Matrix;)V");
global::android.graphics.Matrix._reset3348 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "reset", "()V");
global::android.graphics.Matrix._toShortString3349 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "toShortString", "()Ljava/lang/String;");
global::android.graphics.Matrix._getValues3350 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "getValues", "([F)V");
global::android.graphics.Matrix._isIdentity3351 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "isIdentity", "()Z");
global::android.graphics.Matrix._rectStaysRect3352 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "rectStaysRect", "()Z");
global::android.graphics.Matrix._setTranslate3353 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setTranslate", "(FF)V");
global::android.graphics.Matrix._setScale3354 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setScale", "(FF)V");
global::android.graphics.Matrix._setScale3355 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setScale", "(FFFF)V");
global::android.graphics.Matrix._setRotate3356 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setRotate", "(FFF)V");
global::android.graphics.Matrix._setRotate3357 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setRotate", "(F)V");
global::android.graphics.Matrix._setSinCos3358 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setSinCos", "(FFFF)V");
global::android.graphics.Matrix._setSinCos3359 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setSinCos", "(FF)V");
global::android.graphics.Matrix._setSkew3360 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setSkew", "(FFFF)V");
global::android.graphics.Matrix._setSkew3361 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setSkew", "(FF)V");
global::android.graphics.Matrix._setConcat3362 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setConcat", "(Landroid/graphics/Matrix;Landroid/graphics/Matrix;)Z");
global::android.graphics.Matrix._preTranslate3363 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "preTranslate", "(FF)Z");
global::android.graphics.Matrix._preScale3364 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "preScale", "(FFFF)Z");
global::android.graphics.Matrix._preScale3365 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "preScale", "(FF)Z");
global::android.graphics.Matrix._preRotate3366 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "preRotate", "(FFF)Z");
global::android.graphics.Matrix._preRotate3367 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "preRotate", "(F)Z");
global::android.graphics.Matrix._preSkew3368 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "preSkew", "(FF)Z");
global::android.graphics.Matrix._preSkew3369 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "preSkew", "(FFFF)Z");
global::android.graphics.Matrix._preConcat3370 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "preConcat", "(Landroid/graphics/Matrix;)Z");
global::android.graphics.Matrix._postTranslate3371 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "postTranslate", "(FF)Z");
global::android.graphics.Matrix._postScale3372 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "postScale", "(FFFF)Z");
global::android.graphics.Matrix._postScale3373 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "postScale", "(FF)Z");
global::android.graphics.Matrix._postRotate3374 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "postRotate", "(FFF)Z");
global::android.graphics.Matrix._postRotate3375 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "postRotate", "(F)Z");
global::android.graphics.Matrix._postSkew3376 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "postSkew", "(FFFF)Z");
global::android.graphics.Matrix._postSkew3377 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "postSkew", "(FF)Z");
global::android.graphics.Matrix._postConcat3378 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "postConcat", "(Landroid/graphics/Matrix;)Z");
global::android.graphics.Matrix._setRectToRect3379 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setRectToRect", "(Landroid/graphics/RectF;Landroid/graphics/RectF;Landroid/graphics/Matrix$ScaleToFit;)Z");
global::android.graphics.Matrix._setPolyToPoly3380 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setPolyToPoly", "([FI[FII)Z");
global::android.graphics.Matrix._invert3381 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "invert", "(Landroid/graphics/Matrix;)Z");
global::android.graphics.Matrix._mapPoints3382 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "mapPoints", "([FI[FII)V");
global::android.graphics.Matrix._mapPoints3383 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "mapPoints", "([F[F)V");
global::android.graphics.Matrix._mapPoints3384 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "mapPoints", "([F)V");
global::android.graphics.Matrix._mapVectors3385 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "mapVectors", "([FI[FII)V");
global::android.graphics.Matrix._mapVectors3386 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "mapVectors", "([F)V");
global::android.graphics.Matrix._mapVectors3387 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "mapVectors", "([F[F)V");
global::android.graphics.Matrix._mapRect3388 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "mapRect", "(Landroid/graphics/RectF;Landroid/graphics/RectF;)Z");
global::android.graphics.Matrix._mapRect3389 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "mapRect", "(Landroid/graphics/RectF;)Z");
global::android.graphics.Matrix._mapRadius3390 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "mapRadius", "(F)F");
global::android.graphics.Matrix._setValues3391 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "setValues", "([F)V");
global::android.graphics.Matrix._Matrix3392 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "<init>", "()V");
global::android.graphics.Matrix._Matrix3393 = @__env.GetMethodIDNoThrow(global::android.graphics.Matrix.staticClass, "<init>", "(Landroid/graphics/Matrix;)V");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SymbolSearch;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.SymbolSearch;
using Microsoft.VisualStudio.LanguageServices.Utilities;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.VisualStudio;
using Roslyn.Utilities;
using SVsServiceProvider = Microsoft.VisualStudio.Shell.SVsServiceProvider;
namespace Microsoft.VisualStudio.LanguageServices.Packaging
{
/// <summary>
/// Free threaded wrapper around the NuGet.VisualStudio STA package installer interfaces.
/// We want to be able to make queries about packages from any thread. For example, the
/// add-NuGet-reference feature wants to know what packages a project already has
/// references to. NuGet.VisualStudio provides this information, but only in a COM STA
/// manner. As we don't want our background work to bounce and block on the UI thread
/// we have this helper class which queries the information on the UI thread and caches
/// the data so it can be read from the background.
/// </summary>
[ExportWorkspaceService(typeof(IPackageInstallerService)), Shared]
internal partial class PackageInstallerService : AbstractDelayStartedService, IPackageInstallerService, IVsSearchProviderCallback
{
private readonly object _gate = new object();
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly SVsServiceProvider _serviceProvider;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
// We refer to the package services through proxy types so that we can
// delay loading their DLLs until we actually need them.
private IPackageServicesProxy _packageServices;
private CancellationTokenSource _tokenSource = new CancellationTokenSource();
// We keep track of what types of changes we've seen so we can then determine what to
// refresh on the UI thread. If we hear about project changes, we only refresh that
// project. If we hear about a solution level change, we'll refresh all projects.
private bool _solutionChanged;
private HashSet<ProjectId> _changedProjects = new HashSet<ProjectId>();
private readonly ConcurrentDictionary<ProjectId, ProjectState> _projectToInstalledPackageAndVersion =
new ConcurrentDictionary<ProjectId, ProjectState>();
[ImportingConstructor]
public PackageInstallerService(
VisualStudioWorkspaceImpl workspace,
SVsServiceProvider serviceProvider,
IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
: base(workspace, SymbolSearchOptions.Enabled,
SymbolSearchOptions.SuggestForTypesInReferenceAssemblies,
SymbolSearchOptions.SuggestForTypesInNuGetPackages)
{
_workspace = workspace;
_serviceProvider = serviceProvider;
_editorAdaptersFactoryService = editorAdaptersFactoryService;
}
public ImmutableArray<PackageSource> PackageSources { get; private set; } = ImmutableArray<PackageSource>.Empty;
public event EventHandler PackageSourcesChanged;
private bool IsEnabled => _packageServices != null;
bool IPackageInstallerService.IsEnabled(ProjectId projectId)
{
if (_packageServices == null)
{
return false;
}
if (_projectToInstalledPackageAndVersion.TryGetValue(projectId, out var state))
{
return state.IsEnabled;
}
// If we haven't scanned the project yet, assume that we're available for it.
return true;
}
protected override void EnableService()
{
// Our service has been enabled. Now load the VS package dlls.
var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel));
var packageInstallerServices = componentModel.GetExtensions<IVsPackageInstallerServices>().FirstOrDefault();
var packageInstaller = componentModel.GetExtensions<IVsPackageInstaller2>().FirstOrDefault();
var packageUninstaller = componentModel.GetExtensions<IVsPackageUninstaller>().FirstOrDefault();
var packageSourceProvider = componentModel.GetExtensions<IVsPackageSourceProvider>().FirstOrDefault();
if (packageInstallerServices == null ||
packageInstaller == null ||
packageUninstaller == null ||
packageSourceProvider == null)
{
return;
}
_packageServices = new PackageServicesProxy(
packageInstallerServices, packageInstaller, packageUninstaller, packageSourceProvider);
// Start listening to additional events workspace changes.
_workspace.WorkspaceChanged += OnWorkspaceChanged;
_packageServices.SourcesChanged += OnSourceProviderSourcesChanged;
}
protected override void StartWorking()
{
this.AssertIsForeground();
if (!this.IsEnabled)
{
return;
}
OnSourceProviderSourcesChanged(this, EventArgs.Empty);
OnWorkspaceChanged(null, new WorkspaceChangeEventArgs(
WorkspaceChangeKind.SolutionAdded, null, null));
}
private void OnSourceProviderSourcesChanged(object sender, EventArgs e)
{
if (!this.IsForeground())
{
this.InvokeBelowInputPriority(() => OnSourceProviderSourcesChanged(sender, e));
return;
}
this.AssertIsForeground();
PackageSources = _packageServices.GetSources(includeUnOfficial: true, includeDisabled: false)
.Select(r => new PackageSource(r.Key, r.Value))
.ToImmutableArrayOrEmpty();
PackageSourcesChanged?.Invoke(this, EventArgs.Empty);
}
public bool TryInstallPackage(
Workspace workspace,
DocumentId documentId,
string source,
string packageName,
string versionOpt,
bool includePrerelease,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
// The 'workspace == _workspace' line is probably not necessary. However, we include
// it just to make sure that someone isn't trying to install a package into a workspace
// other than the VisualStudioWorkspace.
if (workspace == _workspace && _workspace != null && _packageServices != null)
{
var projectId = documentId.ProjectId;
var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(SDTE));
var dteProject = _workspace.TryGetDTEProject(projectId);
if (dteProject != null)
{
var description = string.Format(ServicesVSResources.Install_0, packageName);
var undoManager = _editorAdaptersFactoryService.TryGetUndoManager(
workspace, documentId, cancellationToken);
return TryInstallAndAddUndoAction(
source, packageName, versionOpt, includePrerelease, dte, dteProject, undoManager);
}
}
return false;
}
private bool TryInstallPackage(
string source,
string packageName,
string versionOpt,
bool includePrerelease,
EnvDTE.DTE dte,
EnvDTE.Project dteProject)
{
try
{
if (!_packageServices.IsPackageInstalled(dteProject, packageName))
{
dte.StatusBar.Text = string.Format(ServicesVSResources.Installing_0, packageName);
if (versionOpt == null)
{
_packageServices.InstallLatestPackage(
source, dteProject, packageName, includePrerelease, ignoreDependencies: false);
}
else
{
_packageServices.InstallPackage(
source, dteProject, packageName, versionOpt, ignoreDependencies: false);
}
var installedVersion = GetInstalledVersion(packageName, dteProject);
dte.StatusBar.Text = string.Format(ServicesVSResources.Installing_0_completed,
GetStatusBarText(packageName, installedVersion));
return true;
}
// fall through.
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
dte.StatusBar.Text = string.Format(ServicesVSResources.Package_install_failed_colon_0, e.Message);
var notificationService = _workspace.Services.GetService<INotificationService>();
notificationService?.SendNotification(
string.Format(ServicesVSResources.Installing_0_failed_Additional_information_colon_1, packageName, e.Message),
severity: NotificationSeverity.Error);
// fall through.
}
return false;
}
private static string GetStatusBarText(string packageName, string installedVersion)
{
return installedVersion == null ? packageName : $"{packageName} - {installedVersion}";
}
private bool TryUninstallPackage(
string packageName, EnvDTE.DTE dte, EnvDTE.Project dteProject)
{
this.AssertIsForeground();
try
{
if (_packageServices.IsPackageInstalled(dteProject, packageName))
{
dte.StatusBar.Text = string.Format(ServicesVSResources.Uninstalling_0, packageName);
var installedVersion = GetInstalledVersion(packageName, dteProject);
_packageServices.UninstallPackage(dteProject, packageName, removeDependencies: true);
dte.StatusBar.Text = string.Format(ServicesVSResources.Uninstalling_0_completed,
GetStatusBarText(packageName, installedVersion));
return true;
}
// fall through.
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
dte.StatusBar.Text = string.Format(ServicesVSResources.Package_uninstall_failed_colon_0, e.Message);
var notificationService = _workspace.Services.GetService<INotificationService>();
notificationService?.SendNotification(
string.Format(ServicesVSResources.Uninstalling_0_failed_Additional_information_colon_1, packageName, e.Message),
severity: NotificationSeverity.Error);
// fall through.
}
return false;
}
private string GetInstalledVersion(string packageName, EnvDTE.Project dteProject)
{
this.AssertIsForeground();
try
{
var installedPackages = _packageServices.GetInstalledPackages(dteProject);
var metadata = installedPackages.FirstOrDefault(m => m.Id == packageName);
return metadata?.VersionString;
}
catch (ArgumentException e) when (IsKnownNugetIssue(e))
{
// Nuget may throw an ArgumentException when there is something about the project
// they do not like/support.
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
}
return null;
}
private bool IsKnownNugetIssue(ArgumentException exception)
{
// See https://github.com/NuGet/Home/issues/4706
// Nuget throws on legal projects. We do not want to report this exception
// as it is known (and NFWs are expensive), but we do want to report if we
// run into anything else.
return exception.Message.Contains("is not a valid version string");
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
ThisCanBeCalledOnAnyThread();
bool localSolutionChanged = false;
ProjectId localChangedProject = null;
switch (e.Kind)
{
default:
// Nothing to do for any other events.
return;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectRemoved:
localChangedProject = e.ProjectId;
break;
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionCleared:
case WorkspaceChangeKind.SolutionReloaded:
case WorkspaceChangeKind.SolutionRemoved:
localSolutionChanged = true;
break;
}
lock (_gate)
{
// Augment the data that the foreground thread will process.
_solutionChanged |= localSolutionChanged;
if (localChangedProject != null)
{
_changedProjects.Add(localChangedProject);
}
// Now cancel any inflight work that is processing the data.
_tokenSource.Cancel();
_tokenSource = new CancellationTokenSource();
// And enqueue a new job to process things. Wait one second before starting.
// That way if we get a flurry of events we'll end up processing them after
// they've all come in.
var cancellationToken = _tokenSource.Token;
Task.Delay(TimeSpan.FromSeconds(1), cancellationToken)
.ContinueWith(_ => ProcessBatchedChangesOnForeground(cancellationToken), cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, ForegroundTaskScheduler);
}
}
private void ProcessBatchedChangesOnForeground(CancellationToken cancellationToken)
{
this.AssertIsForeground();
// If we've been asked to stop, then there's no point proceeding.
if (cancellationToken.IsCancellationRequested)
{
return;
}
// If we've been disconnected, then there's no point proceeding.
if (_workspace == null || _packageServices == null)
{
return;
}
// Get a project to process.
var solution = _workspace.CurrentSolution;
var projectId = DequeueNextProject(solution);
if (projectId == null)
{
// No project to process, nothing to do.
return;
}
// Process this single project.
ProcessProjectChange(solution, projectId);
// After processing this single project, yield so the foreground thread
// can do more work. Then go and loop again so we can process the
// rest of the projects.
Task.Factory.SafeStartNew(
() => ProcessBatchedChangesOnForeground(cancellationToken), cancellationToken, ForegroundTaskScheduler);
}
private ProjectId DequeueNextProject(Solution solution)
{
this.AssertIsForeground();
lock (_gate)
{
// If we detected a solution change, then we need to process all projects.
// This includes all the projects that we already know about, as well as
// all the projects in the current workspace solution.
if (_solutionChanged)
{
_changedProjects.AddRange(solution.ProjectIds);
_changedProjects.AddRange(_projectToInstalledPackageAndVersion.Keys);
}
_solutionChanged = false;
// Remove and return the first project in the list.
var projectId = _changedProjects.FirstOrDefault();
_changedProjects.Remove(projectId);
return projectId;
}
}
private void ProcessProjectChange(Solution solution, ProjectId projectId)
{
this.AssertIsForeground();
// Remove anything we have associated with this project.
_projectToInstalledPackageAndVersion.TryRemove(projectId, out var projectState);
var project = solution.GetProject(projectId);
if (project == null)
{
// Project was removed. Nothing needs to be done.
return;
}
// We really only need to know the NuGet status for managed language projects.
// Also, the NuGet APIs may throw on some projects that don't implement the
// full set of DTE APIs they expect. So we filter down to just C# and VB here
// as we know these languages are safe to build up this index for.
if (project.Language != LanguageNames.CSharp &&
project.Language != LanguageNames.VisualBasic)
{
return;
}
// Project was changed in some way. Let's go find the set of installed packages for it.
var dteProject = _workspace.TryGetDTEProject(projectId);
if (dteProject == null)
{
// Don't have a DTE project for this project ID. not something we can query NuGet for.
return;
}
var installedPackages = new Dictionary<string, string>();
var isEnabled = false;
// Calling into NuGet. Assume they may fail for any reason.
try
{
var installedPackageMetadata = _packageServices.GetInstalledPackages(dteProject);
installedPackages.AddRange(installedPackageMetadata.Select(m => new KeyValuePair<string, string>(m.Id, m.VersionString)));
isEnabled = true;
}
catch (ArgumentException e) when (IsKnownNugetIssue(e))
{
// Nuget may throw an ArgumentException when there is something about the project
// they do not like/support.
}
catch (Exception e) when (FatalError.ReportWithoutCrash(e))
{
}
var state = new ProjectState(isEnabled, installedPackages);
_projectToInstalledPackageAndVersion.AddOrUpdate(
projectId, state, (_1, _2) => state);
}
public bool IsInstalled(Workspace workspace, ProjectId projectId, string packageName)
{
ThisCanBeCalledOnAnyThread();
return _projectToInstalledPackageAndVersion.TryGetValue(projectId, out var installedPackages) &&
installedPackages.InstalledPackageToVersion.ContainsKey(packageName);
}
public ImmutableArray<string> GetInstalledVersions(string packageName)
{
ThisCanBeCalledOnAnyThread();
var installedVersions = new HashSet<string>();
foreach (var state in _projectToInstalledPackageAndVersion.Values)
{
string version = null;
if (state.InstalledPackageToVersion.TryGetValue(packageName, out version) && version != null)
{
installedVersions.Add(version);
}
}
// Order the versions with a weak heuristic so that 'newer' versions come first.
// Essentially, we try to break the version on dots, and then we use a LogicalComparer
// to try to more naturally order the things we see between the dots.
var versionsAndSplits = installedVersions.Select(v => new { Version = v, Split = v.Split('.') }).ToList();
versionsAndSplits.Sort((v1, v2) =>
{
var diff = CompareSplit(v1.Split, v2.Split);
return diff != 0 ? diff : -v1.Version.CompareTo(v2.Version);
});
return versionsAndSplits.Select(v => v.Version).ToImmutableArray();
}
private int CompareSplit(string[] split1, string[] split2)
{
ThisCanBeCalledOnAnyThread();
for (int i = 0, n = Math.Min(split1.Length, split2.Length); i < n; i++)
{
// Prefer things that look larger. i.e. 7 should come before 6.
// Use a logical string comparer so that 10 is understood to be
// greater than 3.
var diff = -LogicalStringComparer.Instance.Compare(split1[i], split2[i]);
if (diff != 0)
{
return diff;
}
}
// Choose the one with more parts.
return split2.Length - split1.Length;
}
public IEnumerable<Project> GetProjectsWithInstalledPackage(Solution solution, string packageName, string version)
{
ThisCanBeCalledOnAnyThread();
var result = new List<Project>();
foreach (var kvp in this._projectToInstalledPackageAndVersion)
{
var state = kvp.Value;
if (state.InstalledPackageToVersion.TryGetValue(packageName, out var installedVersion) && installedVersion == version)
{
var project = solution.GetProject(kvp.Key);
if (project != null)
{
result.Add(project);
}
}
}
return result;
}
public void ShowManagePackagesDialog(string packageName)
{
this.AssertIsForeground();
var shell = (IVsShell)_serviceProvider.GetService(typeof(SVsShell));
if (shell == null)
{
return;
}
var nugetGuid = new Guid("5fcc8577-4feb-4d04-ad72-d6c629b083cc");
shell.LoadPackage(ref nugetGuid, out var nugetPackage);
if (nugetPackage == null)
{
return;
}
// We're able to launch the package manager (with an item in its search box) by
// using the IVsSearchProvider API that the NuGet package exposes.
//
// We get that interface for it and then pass it a SearchQuery that effectively
// wraps the package name we're looking for. The NuGet package will then read
// out that string and populate their search box with it.
var extensionProvider = (IVsPackageExtensionProvider)nugetPackage;
var extensionGuid = new Guid("042C2B4B-C7F7-49DB-B7A2-402EB8DC7892");
var emptyGuid = Guid.Empty;
var searchProvider = (IVsSearchProvider)extensionProvider.CreateExtensionInstance(ref emptyGuid, ref extensionGuid);
var task = searchProvider.CreateSearch(dwCookie: 1, pSearchQuery: new SearchQuery(packageName), pSearchCallback: this);
task.Start();
}
public void ReportProgress(IVsSearchTask pTask, uint dwProgress, uint dwMaxProgress)
{
}
public void ReportComplete(IVsSearchTask pTask, uint dwResultsFound)
{
}
public void ReportResult(IVsSearchTask pTask, IVsSearchItemResult pSearchItemResult)
{
pSearchItemResult.InvokeAction();
}
public void ReportResults(IVsSearchTask pTask, uint dwResults, IVsSearchItemResult[] pSearchItemResults)
{
}
private class SearchQuery : IVsSearchQuery
{
public SearchQuery(string packageName)
{
this.SearchString = packageName;
}
public string SearchString { get; }
public uint ParseError => 0;
public uint GetTokens(uint dwMaxTokens, IVsSearchToken[] rgpSearchTokens)
{
return 0;
}
}
private class PackageServicesProxy : IPackageServicesProxy
{
private readonly IVsPackageInstaller2 _packageInstaller;
private readonly IVsPackageInstallerServices _packageInstallerServices;
private readonly IVsPackageSourceProvider _packageSourceProvider;
private readonly IVsPackageUninstaller _packageUninstaller;
public PackageServicesProxy(
IVsPackageInstallerServices packageInstallerServices,
IVsPackageInstaller2 packageInstaller,
IVsPackageUninstaller packageUninstaller,
IVsPackageSourceProvider packageSourceProvider)
{
_packageInstallerServices = packageInstallerServices;
_packageInstaller = packageInstaller;
_packageUninstaller = packageUninstaller;
_packageSourceProvider = packageSourceProvider;
}
public event EventHandler SourcesChanged
{
add
{
_packageSourceProvider.SourcesChanged += value;
}
remove
{
_packageSourceProvider.SourcesChanged -= value;
}
}
public IEnumerable<PackageMetadata> GetInstalledPackages(EnvDTE.Project project)
{
return _packageInstallerServices.GetInstalledPackages(project)
.Select(m => new PackageMetadata(m.Id, m.VersionString))
.ToList();
}
public bool IsPackageInstalled(EnvDTE.Project project, string id)
=> _packageInstallerServices.IsPackageInstalled(project, id);
public void InstallPackage(string source, EnvDTE.Project project, string packageId, string version, bool ignoreDependencies)
=> _packageInstaller.InstallPackage(source, project, packageId, version, ignoreDependencies);
public void InstallLatestPackage(string source, EnvDTE.Project project, string packageId, bool includePrerelease, bool ignoreDependencies)
=> _packageInstaller.InstallLatestPackage(source, project, packageId, includePrerelease, ignoreDependencies);
public IEnumerable<KeyValuePair<string, string>> GetSources(bool includeUnOfficial, bool includeDisabled)
=> _packageSourceProvider.GetSources(includeUnOfficial, includeDisabled);
public void UninstallPackage(EnvDTE.Project project, string packageId, bool removeDependencies)
=> _packageUninstaller.UninstallPackage(project, packageId, removeDependencies);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>AdScheduleView</c> resource.</summary>
public sealed partial class AdScheduleViewName : gax::IResourceName, sys::IEquatable<AdScheduleViewName>
{
/// <summary>The possible contents of <see cref="AdScheduleViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>
/// .
/// </summary>
CustomerCampaignCriterion = 1,
}
private static gax::PathTemplate s_customerCampaignCriterion = new gax::PathTemplate("customers/{customer_id}/adScheduleViews/{campaign_id_criterion_id}");
/// <summary>Creates a <see cref="AdScheduleViewName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AdScheduleViewName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AdScheduleViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AdScheduleViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AdScheduleViewName"/> with the pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AdScheduleViewName"/> constructed from the provided ids.</returns>
public static AdScheduleViewName FromCustomerCampaignCriterion(string customerId, string campaignId, string criterionId) =>
new AdScheduleViewName(ResourceNameType.CustomerCampaignCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdScheduleViewName"/> with pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdScheduleViewName"/> with pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>.
/// </returns>
public static string Format(string customerId, string campaignId, string criterionId) =>
FormatCustomerCampaignCriterion(customerId, campaignId, criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdScheduleViewName"/> with pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdScheduleViewName"/> with pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>.
/// </returns>
public static string FormatCustomerCampaignCriterion(string customerId, string campaignId, string criterionId) =>
s_customerCampaignCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="AdScheduleViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adScheduleViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AdScheduleViewName"/> if successful.</returns>
public static AdScheduleViewName Parse(string adScheduleViewName) => Parse(adScheduleViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AdScheduleViewName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adScheduleViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AdScheduleViewName"/> if successful.</returns>
public static AdScheduleViewName Parse(string adScheduleViewName, bool allowUnparsed) =>
TryParse(adScheduleViewName, allowUnparsed, out AdScheduleViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdScheduleViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adScheduleViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdScheduleViewName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adScheduleViewName, out AdScheduleViewName result) =>
TryParse(adScheduleViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdScheduleViewName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adScheduleViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdScheduleViewName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adScheduleViewName, bool allowUnparsed, out AdScheduleViewName result)
{
gax::GaxPreconditions.CheckNotNull(adScheduleViewName, nameof(adScheduleViewName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignCriterion.TryParseName(adScheduleViewName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCampaignCriterion(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(adScheduleViewName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AdScheduleViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string criterionId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignId = campaignId;
CriterionId = criterionId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AdScheduleViewName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public AdScheduleViewName(string customerId, string campaignId, string criterionId) : this(ResourceNameType.CustomerCampaignCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCampaignCriterion: return s_customerCampaignCriterion.Expand(CustomerId, $"{CampaignId}~{CriterionId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AdScheduleViewName);
/// <inheritdoc/>
public bool Equals(AdScheduleViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AdScheduleViewName a, AdScheduleViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AdScheduleViewName a, AdScheduleViewName b) => !(a == b);
}
public partial class AdScheduleView
{
/// <summary>
/// <see cref="AdScheduleViewName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AdScheduleViewName ResourceNameAsAdScheduleViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AdScheduleViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Xe.BinaryMapper;
namespace OpenKh.Bbs
{
public partial class Bbsa
{
protected static string[] KnownExtensions = new string[] {
"Arc", "Bin", "Tm2", "Pmo",
"Pam", "Pmp", "Pvd", "Bcd",
"Fep", "Frr", "Ead", "Ese",
"Lub", "Lad", "L2d", "Pst",
"Epd", "Olo", "Bep", "Txa",
"Aac", "Abc", "Scd", "Bsd",
"Seb", "Ctd", "Ecm", "Ept",
"Mss", "Nmd", "Ite", "Itb",
"Itc", "Bdd", "Bdc", "Ngd",
"Exb", "Gpd", "Exa", "Esd",
"MTX", "INF", "COD", "CLU",
"PMF", "ESE", "PTX", ""
};
protected static Dictionary<uint, string> Paths = new Dictionary<uint, string>
{
[0x0050414D] = "arc/map",
[0x4E455645] = "arc/event",
[0x00004350] = "arc/pc",
[0x10004350] = "arc/pc_ven",
[0x20004350] = "arc/pc_aqua",
[0x30004350] = "arc/pc_terra",
[0x4D454E45] = "arc/enemy",
[0x53534F42] = "arc/boss",
[0x0043504E] = "arc/npc",
[0x4D4D4947] = "arc/gimmick",
[0x50414557] = "arc/weapon",
[0x4D455449] = "arc/item",
[0x45464645] = "arc/effect",
[0x554E454D] = "arc/menu",
[0x00435445] = "arc/etc",
[0x00535953] = "arc/system",
[0x53455250] = "arc/preset",
[0x41455250] = "arc/preset.alpha",
[0x55424544] = "arc/debug",
};
protected static Dictionary<byte, string> PathCategories = new Dictionary<byte, string>
{
[0x00] = "arc_",
[0x80] = "sound/bgm",
[0xC0] = "lua",
[0x90] = "sound/se/common",
[0x91] = "sound/se/event/{1}",
[0x92] = "sound/se/footstep/{1}",
[0x93] = "sound/se/enemy",
[0x94] = "sound/se/weapon",
[0x95] = "sound/se/act",
[0xA1] = "sound/voice/{0}/event/{1}",
[0xAA] = "sound/voice/{0}/battle",
[0xD0] = "message/{0}/system",
[0xD1] = "message/{0}/map",
[0xD2] = "message/{0}/menu",
[0xD3] = "message/{0}/event",
[0xD4] = "message/{0}/mission",
[0xD5] = "message/{0}/npc_talk/{1}",
[0xD6] = "message/{0}/network",
[0xD7] = "message/{0}/battledice",
[0xD8] = "message/{0}/minigame",
[0xD9] = "message/{0}/shop",
[0xDA] = "message/{0}/playerselect",
[0xDB] = "message/{0}/report",
};
protected static Dictionary<string, uint> PathCategoriesReverse = PathCategories
.SelectMany(x =>
Constants.Language.Select((l, i) => new
{
Key = (x.Key << 24) | (i << 21),
Value = x.Value.Replace("{0}", l)
})
)
.SelectMany(x =>
Constants.Worlds.Select((w, i) => new
{
Key = x.Key | (i << 16),
Value = x.Value.Replace("{1}", w)
})
)
.GroupBy(x => x.Value)
.ToDictionary(x => x.Key, x => (uint)x.First().Key);
protected static Dictionary<string, uint> PathsReverse =
Paths.ToDictionary(x => x.Value, x => x.Key);
protected static string[] AllPaths =
PathsReverse
.Select(x => (x.Key + '/').ToUpper())
.Concat(new string[] { string.Empty })
.ToArray();
protected static string[] KnownExtensionsWithDot =
KnownExtensions.Select(x => ('.' + x).ToUpper()).ToArray();
protected class Header
{
[Data] public int MagicCode { get; set; }
[Data] public int Version { get; set; }
[Data] public short PartitionCount { get; set; }
[Data] public short Unk0a { get; set; }
[Data] public short Unk0c { get; set; }
[Data] public short DirectoryCount { get; set; }
[Data] public int PartitionOffset { get; set; }
[Data] public int DirectoryOffset { get; set; }
[Data] public short ArchivePartitionSector { get; set; }
[Data] public short Archive0Sector { get; set; }
[Data] public int TotalSectorCount { get; set; }
[Data] public int Archive1Sector { get; set; }
[Data] public int Archive2Sector { get; set; }
[Data] public int Archive3Sector { get; set; }
[Data] public int Archive4Sector { get; set; }
public Partition<PartitionFileEntry>[] Partitions { get; set; }
}
protected class ArchivePartitionHeader
{
[Data] public byte Unknown00 { get; set; }
[Data] public byte PartitionCount { get; set; }
[Data] public short Unknown02 { get; set; }
[Data] public short LbaStartOffset { get; set; }
[Data] public short UnknownOffset { get; set; }
public Partition<ArchivePartitionEntry>[] Partitions { get; set; }
}
protected class DirectoryEntry
{
public uint FileHash { get; set; }
public uint Info { get; set; }
public uint DirectoryHash { get; set; }
public int Offset => (int)(Info >> 12);
public int Size => (int)(Info & 0xFFF);
public override string ToString() =>
$"{DirectoryHash:X08}/{FileHash:X08} {Offset:X05} {Size:X03}";
}
private const int LbaLength = 8;
protected readonly Header _header;
protected readonly ArchivePartitionHeader _header2;
protected readonly DirectoryEntry[] _directoryEntries;
protected Bbsa(Stream stream)
{
_header = BinaryMapping.ReadObject<Header>(stream, (int)stream.Position);
_header.Partitions = ReadPartitions<PartitionFileEntry>(stream, 0x30, _header.PartitionCount);
ReadPartitionLba(_header.Partitions, stream, _header.PartitionOffset);
stream.Position = _header.DirectoryOffset;
var reader = new BinaryReader(stream);
_directoryEntries = Enumerable.Range(0, _header.DirectoryCount)
.Select(x => new DirectoryEntry
{
FileHash = reader.ReadUInt32(),
Info = reader.ReadUInt32(),
DirectoryHash = reader.ReadUInt32()
}).ToArray();
int header2Offset = _header.ArchivePartitionSector * 0x800;
stream.Position = header2Offset;
_header2 = BinaryMapping.ReadObject<ArchivePartitionHeader>(stream);
_header2.Partitions = ReadPartitions<ArchivePartitionEntry>(stream, header2Offset + 8, _header2.PartitionCount);
ReadPartitionLba(_header2.Partitions, stream, header2Offset + _header2.LbaStartOffset);
ReadUnknownStruct(_header2.Partitions, stream, header2Offset + _header2.UnknownOffset);
}
public IEnumerable<Entry> Files
{
get
{
foreach (var partition in _header.Partitions)
{
Paths.TryGetValue(partition.Name, out var folder);
foreach (var lba in partition.Lba)
{
NameDictionary.TryGetValue(lba.Hash, out var fileName);
yield return new Entry(
this,
lba.Offset,
lba.Size,
fileName,
folder,
lba.Hash,
0);
}
}
foreach (var file in _directoryEntries)
{
NameDictionary.TryGetValue(file.FileHash, out var fileName);
NameDictionary.TryGetValue(file.DirectoryHash, out var folderName);
yield return new Entry(
this,
file.Offset,
file.Size,
fileName,
folderName,
file.FileHash,
file.DirectoryHash);
}
}
}
public int GetOffset(string fileName)
{
var directory = Path.GetDirectoryName(fileName).Replace('\\', '/');
var file = Path.GetFileName(fileName);
var name = Path.GetFileNameWithoutExtension(file);
if (!PathsReverse.TryGetValue(directory, out var pathId))
return -1;
var pathInfo = _header.Partitions.FirstOrDefault(x => x.Name == pathId);
if (pathInfo == null)
return -1;
var hash = GetHash(name.ToUpper());
var lba = pathInfo.Lba.FirstOrDefault(x => x.Hash == hash);
if (lba == null)
return -1;
return (lba.Offset + _header.Archive0Sector) * 0x800;
}
public static Bbsa Read(Stream stream) => new Bbsa(stream);
public static string GetDirectoryName(uint hash) =>
Paths.TryGetValue(hash, out var path) ? path : CalculateFolderName(hash);
public static uint GetDirectoryHash(string directory)
{
if (PathsReverse.TryGetValue(directory.ToLower(), out var hash))
return (uint)hash;
if (PathCategoriesReverse.TryGetValue(directory.ToLower(), out hash))
return (uint)hash;
return uint.MaxValue;
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Collections.Generic;
using System.Text;
namespace NUnit.Framework.Internal.Filters
{
public class OrFilterTests : TestFilterTests
{
[Test]
public void IsNotEmpty()
{
var filter = new OrFilter(new CategoryFilter("Dummy"), new CategoryFilter("Another"));
Assert.False(filter.IsEmpty);
}
[Test]
public void IsNotEmptyFullName()
{
var filter = new OrFilter(new FullNameFilter("Dummy"), new FullNameFilter("Another"));
Assert.False(filter.IsEmpty);
}
[Test]
public void MatchTest()
{
var filter = new OrFilter(new CategoryFilter("Dummy"), new CategoryFilter("Another"));
Assert.That(filter.Match(_dummyFixture));
Assert.That(filter.Match(_anotherFixture));
Assert.False(filter.Match(_yetAnotherFixture));
}
[Test]
public void MatchTestMixed()
{
var filter = new OrFilter(new CategoryFilter("Dummy"), new FullNameFilter(ANOTHER_CLASS));
Assert.That(filter.Match(_dummyFixture));
Assert.That(filter.Match(_anotherFixture));
Assert.False(filter.Match(_yetAnotherFixture));
}
[Test]
public void MatchTestEmpty()
{
var filter = new OrFilter(new TestFilter[] {});
Assert.False(filter.Match(_dummyFixture));
Assert.False(filter.Match(_anotherFixture));
Assert.False(filter.Match(_yetAnotherFixture));
}
[Test]
public void MatchTestFullName()
{
var filter = new OrFilter(new FullNameFilter(DUMMY_CLASS), new FullNameFilter(ANOTHER_CLASS));
Assert.That(filter.Match(_dummyFixture));
Assert.That(filter.Match(_anotherFixture));
Assert.False(filter.Match(_yetAnotherFixture));
}
[Test]
public void MatchTestFullNameRegex()
{
var filter = new OrFilter(new FullNameFilter(DUMMY_CLASS_REGEX) { IsRegex = true }, new FullNameFilter(ANOTHER_CLASS_REGEX) { IsRegex = true });
Assert.That(filter.Match(_dummyFixture));
Assert.That(filter.Match(_anotherFixture));
Assert.False(filter.Match(_yetAnotherFixture));
}
[Test]
public void PassTest()
{
var filter = new OrFilter(new CategoryFilter("Dummy"), new CategoryFilter("Another"));
Assert.That(filter.Pass(_topLevelSuite));
Assert.That(filter.Pass(_dummyFixture));
Assert.That(filter.Pass(_dummyFixture.Tests[0]));
Assert.That(filter.Pass(_anotherFixture));
Assert.That(filter.Pass(_anotherFixture.Tests[0]));
Assert.False(filter.Pass(_yetAnotherFixture));
}
[Test]
public void PassTestFullName()
{
var filter = new OrFilter(new FullNameFilter(DUMMY_CLASS), new FullNameFilter(ANOTHER_CLASS));
Assert.That(filter.Pass(_topLevelSuite));
Assert.That(filter.Pass(_dummyFixture));
Assert.That(filter.Pass(_dummyFixture.Tests[0]));
Assert.That(filter.Pass(_anotherFixture));
Assert.That(filter.Pass(_anotherFixture.Tests[0]));
Assert.False(filter.Pass(_yetAnotherFixture));
}
[Test]
public void PassTestFullNameRegex()
{
var filter = new OrFilter(new FullNameFilter(DUMMY_CLASS_REGEX) { IsRegex = true }, new FullNameFilter(ANOTHER_CLASS_REGEX) { IsRegex = true });
Assert.That(filter.Pass(_topLevelSuite));
Assert.That(filter.Pass(_dummyFixture));
Assert.That(filter.Pass(_dummyFixture.Tests[0]));
Assert.That(filter.Pass(_anotherFixture));
Assert.That(filter.Pass(_anotherFixture.Tests[0]));
Assert.False(filter.Pass(_yetAnotherFixture));
}
[Test]
public void ExplicitMatchTest()
{
var filter = new OrFilter(new CategoryFilter("Dummy"), new CategoryFilter("Another"));
Assert.That(filter.IsExplicitMatch(_topLevelSuite));
Assert.That(filter.IsExplicitMatch(_dummyFixture));
Assert.False(filter.IsExplicitMatch(_dummyFixture.Tests[0]));
Assert.That(filter.IsExplicitMatch(_anotherFixture));
Assert.False(filter.IsExplicitMatch(_anotherFixture.Tests[0]));
Assert.False(filter.IsExplicitMatch(_yetAnotherFixture));
}
/// <summary>
/// Generic combination tests for the <see cref="OrFilter"/>. This test checks that the
/// <see cref="OrFilter"/> correctly combines the results from its sub-filters.
/// Furthermore it checks that the result from the correct match-function of the
/// sub-filters is used to calculate the OR combination.
///
/// The input is an array of booleans (<paramref name="inputBooleans"/>). For each boolean
/// value a <see cref="MockTestFilter"/> is added to the <see cref="OrFilter"/>
/// whose match-function (defined through the parameter <paramref name="matchFunction"/>)
/// evaluates to the boolean value indicated.
/// Afterwards the requested match-function (<paramref name="matchFunction"/>) is called
/// on the <see cref="OrFilter"/> and is compared to the expected result
/// (<paramref name="expectedResult"/>).
/// This tests also throws an exception if the match-function call from the
/// <see cref="OrFilter"/> calls not the same match-function on the
/// <see cref="MockTestFilter"/>, thus checking that the <see cref="OrFilter"/>
/// combines the correct results from the sub-filters.
///
/// See also <see cref="MockTestFilter"/>.
/// </summary>
[TestCase(new bool[] { false, false }, false, MockTestFilter.MatchFunction.IsExplicitMatch)]
[TestCase(new bool[] { true, false }, true, MockTestFilter.MatchFunction.IsExplicitMatch)]
[TestCase(new bool[] { false, true }, true, MockTestFilter.MatchFunction.IsExplicitMatch)]
[TestCase(new bool[] { true, true }, true, MockTestFilter.MatchFunction.IsExplicitMatch)]
[TestCase(new bool[] { false, false }, false, MockTestFilter.MatchFunction.Match)]
[TestCase(new bool[] { true, false }, true, MockTestFilter.MatchFunction.Match)]
[TestCase(new bool[] { false, true }, true, MockTestFilter.MatchFunction.Match)]
[TestCase(new bool[] { true, true }, true, MockTestFilter.MatchFunction.Match)]
[TestCase(new bool[] { false, false }, false, MockTestFilter.MatchFunction.Pass)]
[TestCase(new bool[] { true, false }, true, MockTestFilter.MatchFunction.Pass)]
[TestCase(new bool[] { false, true }, true, MockTestFilter.MatchFunction.Pass)]
[TestCase(new bool[] { true, true }, true, MockTestFilter.MatchFunction.Pass)]
public void CombineTest(IEnumerable<bool> inputBooleans, bool expectedResult,
MockTestFilter.MatchFunction matchFunction)
{
var filters = new List<MockTestFilter>();
foreach (var inputBool in inputBooleans)
{
var strictFilter = new MockTestFilter(_dummyFixture, matchFunction, inputBool);
Assert.AreEqual(inputBool, ExecuteMatchFunction(strictFilter, matchFunction));
filters.Add(strictFilter);
}
var filter = new OrFilter(filters.ToArray());
bool calculatedResult = ExecuteMatchFunction(filter, matchFunction);
Assert.AreEqual(expectedResult, calculatedResult);
}
/// <summary>
/// Executes the requested <paramref name="matchFunction"/> on the <paramref name="filter"/>.
/// </summary>
private bool ExecuteMatchFunction(
TestFilter filter, MockTestFilter.MatchFunction matchFunction)
{
switch (matchFunction)
{
case MockTestFilter.MatchFunction.IsExplicitMatch:
return filter.IsExplicitMatch(_dummyFixture);
case MockTestFilter.MatchFunction.Match:
return filter.Match(_dummyFixture);
case MockTestFilter.MatchFunction.Pass:
return filter.Pass(_dummyFixture);
default:
throw new ArgumentException(
"Unexpected StrictIdFilterForTests.EqualValueFunction.", nameof(matchFunction));
}
}
[Test]
public void BuildFromXml()
{
TestFilter filter = TestFilter.FromXml(
"<filter><or><cat>Dummy</cat><cat>Another</cat></or></filter>");
Assert.That(filter, Is.TypeOf<OrFilter>());
Assert.That(filter.Match(_dummyFixture));
Assert.That(filter.Match(_anotherFixture));
}
[Test]
public void BuildFromXmlFullName()
{
TestFilter filter = TestFilter.FromXml(
$"<filter><or><test>{DUMMY_CLASS}</test><test>{ANOTHER_CLASS}</test></or></filter>");
Assert.That(filter, Is.TypeOf<OrFilter>());
Assert.That(filter.Match(_dummyFixture));
Assert.That(filter.Match(_anotherFixture));
}
[Test]
public void BuildFromXmlFullNameRegex()
{
TestFilter filter = TestFilter.FromXml(
$"<filter><or><test re=\"1\">{DUMMY_CLASS_REGEX}</test><test re=\"1\">{ANOTHER_CLASS_REGEX}</test></or></filter>");
Assert.That(filter, Is.TypeOf<OrFilter>());
Assert.That(filter.Match(_dummyFixture));
Assert.That(filter.Match(_anotherFixture));
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace ParquetSharp.Filter2.Predicate
{
using System;
using ParquetSharp.Hadoop.Metadata;
using ParquetSharp.External;
using ParquetSharp.IO.Api;
/**
* These are the operators in a filter predicate expression tree.
* They are constructed by using the methods in {@link FilterApi}
*/
public static class Operators
{
internal interface Column
{
// For testing
Type getColumnType();
ColumnPath getColumnPath();
}
public abstract class Column<T> : Column where T : IComparable<T>, IComparable
{
private readonly ColumnPath columnPath;
private readonly System.Type columnType;
protected Column(ColumnPath columnPath, System.Type columnType)
{
Preconditions.checkNotNull(columnPath, "columnPath");
Preconditions.checkNotNull(columnType, "columnType");
this.columnPath = columnPath;
this.columnType = columnType;
}
public Type getColumnType()
{
return columnType;
}
public ColumnPath getColumnPath()
{
return columnPath;
}
public override string ToString()
{
return "column(" + columnPath.toDotString() + ")";
}
public override bool Equals(object o)
{
if (this == o) return true;
if (o == null || GetType() != o.GetType()) return false;
Column<T> column = (Column<T>)o;
if (!columnType.Equals(column.columnType)) return false;
if (!columnPath.Equals(column.columnPath)) return false;
return true;
}
public override int GetHashCode()
{
int result = columnPath.GetHashCode();
result = 31 * result + columnType.GetHashCode();
return result;
}
}
public interface SupportsEqNotEq { } // marker for columns that can be used with eq() and notEq()
public interface SupportsLtGt : SupportsEqNotEq { } // marker for columns that can be used with lt(), ltEq(), gt(), gtEq()
sealed public class IntColumn : Column<int>, SupportsLtGt
{
internal IntColumn(ColumnPath columnPath)
: base(columnPath, typeof(int?))
{
}
}
sealed public class LongColumn : Column<long>, SupportsLtGt
{
internal LongColumn(ColumnPath columnPath)
: base(columnPath, typeof(long?))
{
}
}
sealed public class DoubleColumn : Column<double>, SupportsLtGt
{
internal DoubleColumn(ColumnPath columnPath)
: base(columnPath, typeof(double?))
{
}
}
sealed public class FloatColumn : Column<float>, SupportsLtGt
{
internal FloatColumn(ColumnPath columnPath)
: base(columnPath, typeof(float?))
{
}
}
sealed public class BooleanColumn : Column<bool>, SupportsEqNotEq
{
internal BooleanColumn(ColumnPath columnPath)
: base(columnPath, typeof(bool?))
{
}
}
sealed public class BinaryColumn : Column<Binary>, SupportsLtGt
{
internal BinaryColumn(ColumnPath columnPath)
: base(columnPath, typeof(Binary))
{
}
}
// base class for Eq, NotEq, Lt, Gt, LtEq, GtEq
public abstract class ColumnFilterPredicate<T> : FilterPredicate where T : IComparable<T>, IComparable
{
private readonly Column<T> column;
private readonly T value;
private readonly string toString;
protected ColumnFilterPredicate(Column<T> column, T value)
{
this.column = Preconditions.checkNotNull(column, "column");
// Eq and NotEq allow value to be null, Lt, Gt, LtEq, GtEq however do not, so they guard against
// null in their own constructors.
this.value = value;
string name = GetType().Name.ToLowerInvariant();
if (name.Length > 3 && name[name.Length - 2] == '`')
{
name = name.Substring(0, name.Length - 2);
}
this.toString = name + "(" + column.getColumnPath().toDotString() + ", " + value + ")";
}
public Column<T> getColumn()
{
return column;
}
public T getValue()
{
return value;
}
public override string ToString()
{
return toString;
}
public override bool Equals(object o)
{
if (this == o) return true;
if (o == null || GetType() != o.GetType()) return false;
ColumnFilterPredicate<T> that = (ColumnFilterPredicate<T>)o;
if (!column.Equals(that.column)) return false;
if (value != null ? !value.Equals(that.value) : that.value != null) return false;
return true;
}
public override int GetHashCode()
{
int result = column.GetHashCode();
result = 31 * result + (value != null ? value.GetHashCode() : 0);
result = 31 * result + GetType().GetHashCode();
return result;
}
public abstract R accept<R>(FilterPredicateVisitor<R> visitor);
}
internal interface Eq
{
// For testing
Column getColumn();
object getValue();
}
sealed public class Eq<T> : ColumnFilterPredicate<T>, Eq where T : IComparable<T>, IComparable
{
// value can be null
internal Eq(Column<T> column, T value)
: base(column, value)
{
}
public override R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
Column Eq.getColumn()
{
return getColumn();
}
object Eq.getValue()
{
return getValue();
}
}
internal interface NotEq
{
// For testing
Column getColumn();
object getValue();
}
sealed public class NotEq<T> : ColumnFilterPredicate<T>, NotEq where T : IComparable<T>, IComparable
{
// value can be null
internal NotEq(Column<T> column, T value)
: base(column, value)
{
}
public override R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
Column NotEq.getColumn()
{
return getColumn();
}
object NotEq.getValue()
{
return getValue();
}
}
internal interface Lt
{
// For testing
object getValue();
}
sealed public class Lt<T> : ColumnFilterPredicate<T>, Lt where T : IComparable<T>, IComparable
{
// value cannot be null
internal Lt(Column<T> column, T value)
: base(column, Preconditions.checkNotNull(value, "value"))
{
}
public override R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
object Lt.getValue()
{
return getValue();
}
}
internal interface LtEq
{
// For testing
object getValue();
}
sealed public class LtEq<T> : ColumnFilterPredicate<T>, LtEq where T : IComparable<T>, IComparable
{
// value cannot be null
internal LtEq(Column<T> column, T value)
: base(column, Preconditions.checkNotNull(value, "value"))
{
}
public override R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
object LtEq.getValue()
{
return getValue();
}
}
internal interface Gt
{
// For testing
Column getColumn();
object getValue();
}
sealed public class Gt<T> : ColumnFilterPredicate<T>, Gt where T : IComparable<T>, IComparable
{
// value cannot be null
internal Gt(Column<T> column, T value)
: base(column, Preconditions.checkNotNull(value, "value"))
{
}
public override R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
Column Gt.getColumn()
{
return getColumn();
}
object Gt.getValue()
{
return getValue();
}
}
internal interface GtEq
{
// For testing
Column getColumn();
object getValue();
}
sealed public class GtEq<T> : ColumnFilterPredicate<T>, GtEq where T : IComparable<T>, IComparable
{
// value cannot be null
internal GtEq(Column<T> column, T value)
: base(column, Preconditions.checkNotNull(value, "value"))
{
}
public override R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
Column GtEq.getColumn()
{
return getColumn();
}
object GtEq.getValue()
{
return getValue();
}
}
// base class for And, Or
public abstract class BinaryLogicalFilterPredicate : FilterPredicate
{
private readonly FilterPredicate left;
private readonly FilterPredicate right;
private readonly string toString;
protected BinaryLogicalFilterPredicate(FilterPredicate left, FilterPredicate right)
{
this.left = Preconditions.checkNotNull(left, "left");
this.right = Preconditions.checkNotNull(right, "right");
string name = GetType().Name.ToLowerInvariant();
this.toString = name + "(" + left + ", " + right + ")";
}
public FilterPredicate getLeft()
{
return left;
}
public FilterPredicate getRight()
{
return right;
}
public override string ToString()
{
return toString;
}
public override bool Equals(object o)
{
if (this == o) return true;
if (o == null || GetType() != o.GetType()) return false;
BinaryLogicalFilterPredicate that = (BinaryLogicalFilterPredicate)o;
if (!left.Equals(that.left)) return false;
if (!right.Equals(that.right)) return false;
return true;
}
public override int GetHashCode()
{
int result = left.GetHashCode();
result = 31 * result + right.GetHashCode();
result = 31 * result + GetType().GetHashCode();
return result;
}
public abstract R accept<R>(FilterPredicateVisitor<R> visitor);
}
sealed public class And : BinaryLogicalFilterPredicate
{
internal And(FilterPredicate left, FilterPredicate right)
: base(left, right)
{
}
public override R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
}
sealed public class Or : BinaryLogicalFilterPredicate
{
internal Or(FilterPredicate left, FilterPredicate right)
: base(left, right)
{
}
public override R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
}
public class Not : FilterPredicate
{
private readonly FilterPredicate predicate;
private readonly string toString;
internal Not(FilterPredicate predicate)
{
this.predicate = Preconditions.checkNotNull(predicate, "predicate");
this.toString = "not(" + predicate + ")";
}
public FilterPredicate getPredicate()
{
return predicate;
}
public override string ToString()
{
return toString;
}
public R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
public override bool Equals(object o)
{
if (this == o) return true;
if (o == null || GetType() != o.GetType()) return false;
Not not = (Not)o;
return predicate.Equals(not.predicate);
}
public override int GetHashCode()
{
return predicate.GetHashCode() * 31 + GetType().GetHashCode();
}
}
internal interface UserDefined
{
// For testing
object getUserDefinedPredicate();
}
public abstract class UserDefined<T, U> : FilterPredicate, UserDefined
where T : IComparable<T>, IComparable
where U : UserDefinedPredicate<T>
{
protected readonly Column<T> column;
protected UserDefined(Column<T> column)
{
this.column = Preconditions.checkNotNull(column, "column");
}
public Column<T> getColumn()
{
return column;
}
public abstract U getUserDefinedPredicate();
public R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
object UserDefined.getUserDefinedPredicate()
{
return getUserDefinedPredicate();
}
}
internal interface UserDefinedByClass
{
// For testing
Type getUserDefinedPredicateClass();
}
sealed public class UserDefinedByClass<T, U> : UserDefined<T, U>, UserDefinedByClass
where T : IComparable<T>, IComparable
where U : UserDefinedPredicate<T>, new()
{
private readonly Type udpClass;
private readonly string toString;
private const string INSTANTIATION_ERROR_MESSAGE =
"Could not instantiate custom filter: {0}. User defined predicates must be static classes with a default constructor.";
internal UserDefinedByClass(Column<T> column)
: base(column)
{
this.udpClass = typeof(U);
string name = GetType().Name.ToLowerInvariant();
this.toString = name + "(" + column.getColumnPath().toDotString() + ", " + udpClass.FullName + ")";
// defensively try to instantiate the class early to make sure that it's possible
getUserDefinedPredicate();
}
public Type getUserDefinedPredicateClass()
{
return udpClass;
}
public override U getUserDefinedPredicate()
{
try
{
return new U();
}
catch (Exception e)
{
throw new RuntimeException(string.Format(INSTANTIATION_ERROR_MESSAGE, udpClass), e);
}
}
public override string ToString()
{
return toString;
}
public override bool Equals(object o)
{
if (this == o) return true;
if (o == null || GetType() != o.GetType()) return false;
UserDefinedByClass<T, U> that = (UserDefinedByClass<T, U>)o;
if (!column.Equals(that.column)) return false;
if (!udpClass.Equals(that.udpClass)) return false;
return true;
}
public override int GetHashCode()
{
int result = column.GetHashCode();
result = 31 * result + udpClass.GetHashCode();
result = result * 31 + GetType().GetHashCode();
return result;
}
}
sealed public class UserDefinedByInstance<T, U> : UserDefined<T, U>
where T : IComparable<T>, IComparable
where U : UserDefinedPredicate<T>
{
private readonly string toString;
private readonly U udpInstance;
public UserDefinedByInstance(Column<T> column, U udpInstance)
: base(column)
{
this.udpInstance = Preconditions.checkNotNull(udpInstance, "udpInstance");
string name = GetType().Name.ToLowerInvariant();
this.toString = name + "(" + column.getColumnPath().toDotString() + ", " + udpInstance + ")";
}
public override U getUserDefinedPredicate()
{
return udpInstance;
}
public override string ToString()
{
return toString;
}
public override bool Equals(object o)
{
if (this == o) return true;
if (o == null || GetType() != o.GetType()) return false;
UserDefinedByInstance<T, U> that = (UserDefinedByInstance<T, U>)o;
if (!column.Equals(that.column)) return false;
if (!udpInstance.Equals(that.udpInstance)) return false;
return true;
}
public override int GetHashCode()
{
int result = column.GetHashCode();
result = 31 * result + udpInstance.GetHashCode();
result = result * 31 + GetType().GetHashCode();
return result;
}
}
// Represents the inverse of a UserDefined. It is equivalent to not(userDefined), without the use
// of the not() operator
sealed public class LogicalNotUserDefined<T, U> : FilterPredicate
where T : IComparable<T>, IComparable
where U : UserDefinedPredicate<T>
{
private readonly UserDefined<T, U> udp;
private readonly string toString;
internal LogicalNotUserDefined(UserDefined<T, U> userDefined)
{
this.udp = Preconditions.checkNotNull(userDefined, "userDefined");
this.toString = "inverted(" + udp + ")";
}
public UserDefined<T, U> getUserDefined()
{
return udp;
}
public R accept<R>(FilterPredicateVisitor<R> visitor)
{
return visitor.visit(this);
}
public override string ToString()
{
return toString;
}
public override bool Equals(object o)
{
if (this == o) return true;
if (o == null || GetType() != o.GetType()) return false;
LogicalNotUserDefined<T, U> that = (LogicalNotUserDefined<T, U>)o;
if (!udp.Equals(that.udp)) return false;
return true;
}
public override int GetHashCode()
{
int result = udp.GetHashCode();
result = result * 31 + GetType().GetHashCode();
return result;
}
}
}
}
| |
// 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.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.PreferFrameworkType;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.Analyzers;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PreferFrameworkType
{
public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpPreferFrameworkTypeDiagnosticAnalyzer(), new PreferFrameworkTypeCodeFixProvider());
private readonly CodeStyleOption<bool> onWithInfo = new CodeStyleOption<bool>(true, NotificationOption.Suggestion);
private readonly CodeStyleOption<bool> offWithInfo = new CodeStyleOption<bool>(false, NotificationOption.Suggestion);
private IDictionary<OptionKey, object> NoFrameworkType => OptionsSet(
SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption.Suggestion),
SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo, GetLanguage()));
private IDictionary<OptionKey, object> FrameworkTypeEverywhere => OptionsSet(
SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption.Suggestion),
SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo, GetLanguage()));
private IDictionary<OptionKey, object> FrameworkTypeInDeclaration => OptionsSet(
SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption.Suggestion),
SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, onWithInfo, GetLanguage()));
private IDictionary<OptionKey, object> FrameworkTypeInMemberAccess => OptionsSet(
SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption.Suggestion),
SingleOption(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, offWithInfo, GetLanguage()));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task NotWhenOptionsAreNotSet()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|int|] x = 1;
}
}", new TestParameters(options: NoFrameworkType));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task NotOnDynamic()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|dynamic|] x = 1;
}
}", new TestParameters(options: FrameworkTypeInDeclaration));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task NotOnSystemVoid()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
[|void|] Method()
{
}
}", new TestParameters(options: FrameworkTypeEverywhere));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task NotOnUserdefinedType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|Program|] p;
}
}", new TestParameters(options: FrameworkTypeEverywhere));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task NotOnFrameworkType()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|Int32|] p;
}
}", new TestParameters(options: FrameworkTypeInDeclaration));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task NotOnQualifiedTypeSyntax()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
void Method()
{
[|System.Int32|] p;
}
}", new TestParameters(options: FrameworkTypeInDeclaration));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
[|List|]<int> p;
}
}", new TestParameters(options: FrameworkTypeInDeclaration));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task NotOnIdentifierThatIsNotTypeSyntax()
{
await TestMissingInRegularAndScriptAsync(
@"using System;
class Program
{
void Method()
{
int [|p|];
}
}", new TestParameters(options: FrameworkTypeInDeclaration));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task QualifiedReplacementWhenNoUsingFound()
{
var code =
@"class Program
{
[|string|] _myfield = 5;
}";
var expected =
@"class Program
{
System.String _myfield = 5;
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task FieldDeclaration()
{
var code =
@"using System;
class Program
{
[|int|] _myfield;
}";
var expected =
@"using System;
class Program
{
Int32 _myfield;
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task FieldDeclarationWithInitializer()
{
var code =
@"using System;
class Program
{
[|string|] _myfield = 5;
}";
var expected =
@"using System;
class Program
{
String _myfield = 5;
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task DelegateDeclaration()
{
var code =
@"using System;
class Program
{
public delegate [|int|] PerformCalculation(int x, int y);
}";
var expected =
@"using System;
class Program
{
public delegate Int32 PerformCalculation(int x, int y);
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task PropertyDeclaration()
{
var code =
@"using System;
class Program
{
public [|long|] MyProperty { get; set; }
}";
var expected =
@"using System;
class Program
{
public Int64 MyProperty { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task GenericPropertyDeclaration()
{
var code =
@"using System;
using System.Collections.Generic;
class Program
{
public List<[|long|]> MyProperty { get; set; }
}";
var expected =
@"using System;
using System.Collections.Generic;
class Program
{
public List<Int64> MyProperty { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task QualifiedReplacementInGenericTypeParameter()
{
var code =
@"using System.Collections.Generic;
class Program
{
public List<[|long|]> MyProperty { get; set; }
}";
var expected =
@"using System.Collections.Generic;
class Program
{
public List<System.Int64> MyProperty { get; set; }
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task MethodDeclarationReturnType()
{
var code =
@"using System;
class Program
{
public [|long|] Method() { }
}";
var expected =
@"using System;
class Program
{
public Int64 Method() { }
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task MethodDeclarationParameters()
{
var code =
@"using System;
class Program
{
public void Method([|double|] d) { }
}";
var expected =
@"using System;
class Program
{
public void Method(Double d) { }
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task GenericMethodInvocation()
{
var code =
@"using System;
class Program
{
public void Method<T>() { }
public void Test() { Method<[|int|]>(); }
}";
var expected =
@"using System;
class Program
{
public void Method<T>() { }
public void Test() { Method<Int32>(); }
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task LocalDeclaration()
{
var code =
@"using System;
class Program
{
void Method()
{
[|int|] f = 5;
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
Int32 f = 5;
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task MemberAccess()
{
var code =
@"using System;
class Program
{
void Method()
{
Console.Write([|int|].MaxValue);
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
Console.Write(Int32.MaxValue);
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task MemberAccess2()
{
var code =
@"using System;
class Program
{
void Method()
{
var x = [|int|].Parse(""1"");
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
var x = Int32.Parse(""1"");
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task DocCommentTriviaCrefExpression()
{
var code =
@"using System;
class Program
{
/// <see cref=""[|int|].MaxValue""/>
void Method()
{
}
}";
var expected =
@"using System;
class Program
{
/// <see cref=""Int32.MaxValue""/>
void Method()
{
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInMemberAccess);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task DefaultExpression()
{
var code =
@"using System;
class Program
{
void Method()
{
var v = default([|int|]);
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
var v = default(Int32);
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task TypeOfExpression()
{
var code =
@"using System;
class Program
{
void Method()
{
var v = typeof([|int|]);
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
var v = typeof(Int32);
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task NameOfExpression()
{
var code =
@"using System;
class Program
{
void Method()
{
var v = nameof([|int|]);
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
var v = nameof(Int32);
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task FormalParametersWithinLambdaExression()
{
var code =
@"using System;
class Program
{
void Method()
{
Func<int, int> func3 = ([|int|] z) => z + 1;
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
Func<int, int> func3 = (Int32 z) => z + 1;
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task DelegateMethodExpression()
{
var code =
@"using System;
class Program
{
void Method()
{
Func<int, int> func7 = delegate ([|int|] dx) { return dx + 1; };
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
Func<int, int> func7 = delegate (Int32 dx) { return dx + 1; };
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task ObjectCreationExpression()
{
var code =
@"using System;
class Program
{
void Method()
{
string s2 = new [|string|]('c', 1);
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
string s2 = new String('c', 1);
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task ArrayDeclaration()
{
var code =
@"using System;
class Program
{
void Method()
{
[|int|][] k = new int[4];
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
Int32[] k = new int[4];
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task ArrayInitializer()
{
var code =
@"using System;
class Program
{
void Method()
{
int[] k = new [|int|][] { 1, 2, 3 };
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
int[] k = new Int32[] { 1, 2, 3 };
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task MultiDimentionalArrayAsGenericTypeParameter()
{
var code =
@"using System;
using System.Collections.Generic;
class Program
{
void Method()
{
List<[|string|][][,][,,,]> a;
}
}";
var expected =
@"using System;
using System.Collections.Generic;
class Program
{
void Method()
{
List<String[][,][,,,]> a;
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task ForStatement()
{
var code =
@"using System;
class Program
{
void Method()
{
for ([|int|] j = 0; j < 4; j++) { }
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
for (Int32 j = 0; j < 4; j++) { }
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task ForeachStatement()
{
var code =
@"using System;
class Program
{
void Method()
{
foreach ([|int|] item in new int[] { 1, 2, 3 }) { }
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
foreach (Int32 item in new int[] { 1, 2, 3 }) { }
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task LeadingTrivia()
{
var code =
@"using System;
class Program
{
void Method()
{
// this is a comment
[|int|] x = 5;
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
// this is a comment
Int32 x = 5;
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration, ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)]
public async Task TrailingTrivia()
{
var code =
@"using System;
class Program
{
void Method()
{
[|int|] /* 2 */ x = 5;
}
}";
var expected =
@"using System;
class Program
{
void Method()
{
Int32 /* 2 */ x = 5;
}
}";
await TestInRegularAndScriptAsync(code, expected, options: FrameworkTypeInDeclaration, ignoreTrivia: false);
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
using System;
using System.IO;
using System.Collections;
using System.Reflection;
using NUnit.Core.Builders;
using NUnit.Core.Extensibility;
namespace NUnit.Core
{
/// <summary>
/// CoreExtensions is a singleton class that groups together all
/// the extension points that are supported in the test domain.
/// It also provides access to the test builders and decorators
/// by other parts of the NUnit core.
/// </summary>
public class CoreExtensions : ExtensionHost, IService
{
static Logger log = InternalTrace.GetLogger("CoreExtensions");
#region Instance Fields
private IAddinRegistry addinRegistry;
private bool initialized;
private SuiteBuilderCollection suiteBuilders;
private TestCaseBuilderCollection testBuilders;
private TestDecoratorCollection testDecorators;
private EventListenerCollection listeners;
private FrameworkRegistry frameworks;
private TestCaseProviders testcaseProviders;
private DataPointProviders dataPointProviders;
#endregion
#region CoreExtensions Singleton
private static CoreExtensions host;
public static CoreExtensions Host
{
get
{
if (host == null)
host = new CoreExtensions();
return host;
}
}
#endregion
#region Constructors
public CoreExtensions()
{
this.suiteBuilders = new SuiteBuilderCollection(this);
this.testBuilders = new TestCaseBuilderCollection(this);
this.testDecorators = new TestDecoratorCollection(this);
this.listeners = new EventListenerCollection(this);
this.frameworks = new FrameworkRegistry(this);
this.testcaseProviders = new TestCaseProviders(this);
this.dataPointProviders = new DataPointProviders(this);
this.extensions = new ArrayList();
extensions.Add(suiteBuilders);
extensions.Add(testBuilders);
extensions.Add(testDecorators);
extensions.Add(listeners);
extensions.Add(frameworks);
extensions.Add(testcaseProviders);
extensions.Add(dataPointProviders);
this.supportedTypes = ExtensionType.Core;
// TODO: This should be somewhere central
// string logfile = Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData );
// logfile = Path.Combine( logfile, "NUnit" );
// logfile = Path.Combine( logfile, "NUnitTest.log" );
//
// appender = new log4net.Appender.ConsoleAppender();
//// appender.File = logfile;
//// appender.AppendToFile = true;
//// appender.LockingModel = new log4net.Appender.FileAppender.MinimalLock();
// appender.Layout = new log4net.Layout.PatternLayout(
// "%date{ABSOLUTE} %-5level [%4thread] %logger{1}: PID=%property{PID} %message%newline" );
// appender.Threshold = log4net.Core.Level.All;
// log4net.Config.BasicConfigurator.Configure(appender);
}
#endregion
#region Public Properties
public bool Initialized
{
get { return initialized; }
}
/// <summary>
/// Our AddinRegistry may be set from outside or passed into the domain
/// </summary>
public IAddinRegistry AddinRegistry
{
get
{
if ( addinRegistry == null )
addinRegistry = AppDomain.CurrentDomain.GetData( "AddinRegistry" ) as IAddinRegistry;
return addinRegistry;
}
set { addinRegistry = value; }
}
#endregion
#region Internal Properties
internal ISuiteBuilder SuiteBuilders
{
get { return suiteBuilders; }
}
internal ITestCaseBuilder2 TestBuilders
{
get { return testBuilders; }
}
internal ITestDecorator TestDecorators
{
get { return testDecorators; }
}
internal EventListener Listeners
{
get { return listeners; }
}
internal FrameworkRegistry TestFrameworks
{
get { return frameworks; }
}
internal TestCaseProviders TestCaseProviders
{
get { return testcaseProviders; }
}
#endregion
#region Public Methods
public void InstallBuiltins()
{
log.Info( "Installing Builtins" );
// Define NUnit Frameworks
frameworks.Register( "NUnit", "nunit.framework" );
frameworks.Register("NUnitLite", "NUnitLite");
// Install builtin SuiteBuilders
suiteBuilders.Install( new NUnitTestFixtureBuilder() );
suiteBuilders.Install( new SetUpFixtureBuilder() );
// Install builtin TestCaseBuilder
testBuilders.Install( new NUnitTestCaseBuilder() );
//testBuilders.Install(new TheoryBuilder());
// Install builtin TestCaseProviders
testcaseProviders.Install(new TestCaseParameterProvider());
testcaseProviders.Install(new TestCaseSourceProvider());
testcaseProviders.Install(new CombinatorialTestCaseProvider());
// Install builtin DataPointProvider
dataPointProviders.Install(new InlineDataPointProvider());
dataPointProviders.Install(new ValueSourceProvider());
dataPointProviders.Install(new DatapointProvider());
}
public void InstallAddins()
{
log.Info( "Installing Addins" );
if( AddinRegistry != null )
{
foreach (Addin addin in AddinRegistry.Addins)
{
if ( (this.ExtensionTypes & addin.ExtensionType) != 0 )
{
AddinStatus status = AddinStatus.Unknown;
string message = null;
try
{
Type type = Type.GetType(addin.TypeName);
if ( type == null )
{
status = AddinStatus.Error;
message = string.Format( "Unable to locate {0} Type", addin.TypeName );
}
else if ( !InstallAddin( type ) )
{
status = AddinStatus.Error;
message = "Install method returned false";
}
else
{
status = AddinStatus.Loaded;
}
}
catch( Exception ex )
{
status = AddinStatus.Error;
message = ex.ToString();
}
AddinRegistry.SetStatus( addin.Name, status, message );
if ( status != AddinStatus.Loaded )
{
log.Error( "Failed to load {0}", addin.Name );
log.Error( message );
}
}
}
}
}
public void InstallAdhocExtensions( Assembly assembly )
{
foreach ( Type type in assembly.GetExportedTypes() )
{
if ( type.GetCustomAttributes(typeof(NUnitAddinAttribute), false).Length == 1 )
InstallAddin( type );
}
}
#endregion
#region Helper Methods
private bool InstallAddin( Type type )
{
ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes);
object obj = ctor.Invoke( new object[0] );
IAddin theAddin = (IAddin)obj;
return theAddin.Install(this);
}
#endregion
#region IService Members
public void UnloadService()
{
// TODO: Add CoreExtensions.UnloadService implementation
}
public void InitializeService()
{
InstallBuiltins();
InstallAddins();
initialized = true;
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.Util;
using NPOI.DDF;
using System.Collections.Generic;
using NPOI.HWPF.UserModel;
using System.Collections;
using System;
namespace NPOI.HWPF.Model
{
/**
* Holds information about all pictures embedded in Word Document either via "Insert -> Picture -> From File" or via
* clipboard. Responsible for images extraction and determining whether some document's piece Contains embedded image.
* Analyzes raw data bytestream 'Data' (where Word stores all embedded objects) provided by HWPFDocument.
*
* Word stores images as is within so called "Data stream" - the stream within a Word docfile Containing various data
* that hang off of characters in the main stream. For example, binary data describing in-line pictures and/or
* formfields an also embedded objects-native data. Word picture structures are concatenated one after the other in
* the data stream if the document Contains pictures.
* Data stream is easily reachable via HWPFDocument._dataStream property.
* A picture is represented in the document text stream as a special character, an Unicode \u0001 whose
* CharacterRun.IsSpecial() returns true. The file location of the picture in the Word binary file is accessed
* via CharacterRun.GetPicOffSet(). The CharacterRun.GetPicOffSet() is a byte offset into the data stream.
* Beginning at the position recorded in picOffSet, a header data structure, will be stored.
*
* @author Dmitry Romanov
*/
public class PicturesTable
{
private static POILogger logger = POILogFactory
.GetLogger( typeof(PicturesTable) );
static int TYPE_IMAGE = 0x08;
static int TYPE_IMAGE_WORD2000 = 0x00;
static int TYPE_IMAGE_PASTED_FROM_CLIPBOARD = 0xA;
static int TYPE_IMAGE_PASTED_FROM_CLIPBOARD_WORD2000 = 0x2;
static int TYPE_HORIZONTAL_LINE = 0xE;
static int BLOCK_TYPE_OFFSET = 0xE;
static int MM_MODE_TYPE_OFFSET = 0x6;
private HWPFDocument _document;
private byte[] _dataStream;
private byte[] _mainStream;
private FSPATable _fspa;
private EscherRecordHolder _dgg;
/** @link dependency
* @stereotype instantiate*/
/*# Picture lnkPicture; */
/**
*
* @param _document
* @param _dataStream
*/
public PicturesTable(HWPFDocument _document, byte[] _dataStream, byte[] _mainStream, FSPATable fspa, EscherRecordHolder dgg)
{
this._document = _document;
this._dataStream = _dataStream;
this._mainStream = _mainStream;
this._fspa = fspa;
this._dgg = dgg;
}
/**
* determines whether specified CharacterRun Contains reference to a picture
* @param run
*/
public bool HasPicture(CharacterRun run)
{
if (run.IsSpecialCharacter() && !run.IsObj() && !run.IsOle2() && !run.IsData())
{
// Image should be in it's own run, or in a run with the end-of-special marker
if ("\u0001".Equals(run.Text) || "\u0001\u0015".Equals(run.Text))
{
return IsBlockContainsImage(run.GetPicOffset());
}
}
return false;
}
public bool HasEscherPicture(CharacterRun run)
{
if (run.IsSpecialCharacter() && !run.IsObj() && !run.IsOle2() && !run.IsData() && run.Text.StartsWith("\u0008"))
{
return true;
}
return false;
}
/**
* determines whether specified CharacterRun Contains reference to a picture
* @param run
*/
public bool HasHorizontalLine(CharacterRun run)
{
if (run.IsSpecialCharacter() && "\u0001".Equals(run.Text))
{
return IsBlockContainsHorizontalLine(run.GetPicOffset());
}
return false;
}
private bool IsPictureRecognized(short blockType, short mappingModeOfMETAFILEPICT)
{
return (blockType == TYPE_IMAGE || blockType == TYPE_IMAGE_PASTED_FROM_CLIPBOARD || (blockType == TYPE_IMAGE_WORD2000 && mappingModeOfMETAFILEPICT == 0x64) || (blockType == TYPE_IMAGE_PASTED_FROM_CLIPBOARD_WORD2000 && mappingModeOfMETAFILEPICT == 0x64));
}
private static short GetBlockType(byte[] dataStream, int pictOffset)
{
return LittleEndian.GetShort(dataStream, pictOffset + BLOCK_TYPE_OFFSET);
}
private static short GetMmMode(byte[] dataStream, int pictOffset)
{
return LittleEndian.GetShort(dataStream, pictOffset + MM_MODE_TYPE_OFFSET);
}
/**
* Returns picture object tied to specified CharacterRun
* @param run
* @param FillBytes if true, Picture will be returned with Filled byte array that represent picture's contents. If you don't want
* to have that byte array in memory but only write picture's contents to stream, pass false and then use Picture.WriteImageContent
* @see Picture#WriteImageContent(java.io.OutputStream)
* @return a Picture object if picture exists for specified CharacterRun, null otherwise. PicturesTable.hasPicture is used to determine this.
* @see #hasPicture(NPOI.HWPF.usermodel.CharacterRun)
*/
public Picture ExtractPicture(CharacterRun run, bool FillBytes)
{
if (HasPicture(run))
{
return new Picture(run.GetPicOffset(), _dataStream, FillBytes);
}
return null;
}
/**
* Performs a recursive search for pictures in the given list of escher records.
*
* @param escherRecords the escher records.
* @param pictures the list to populate with the pictures.
*/
private void SearchForPictures(IList escherRecords, List<Picture> pictures)
{
foreach (EscherRecord escherRecord in escherRecords)
{
if (escherRecord is EscherBSERecord)
{
EscherBSERecord bse = (EscherBSERecord)escherRecord;
EscherBlipRecord blip = bse.BlipRecord;
if (blip != null)
{
pictures.Add(new Picture(blip.PictureData));
}
else if (bse.Offset > 0)
{
try
{
// Blip stored in delay stream, which in a word doc, is the main stream
IEscherRecordFactory recordFactory = new DefaultEscherRecordFactory();
EscherRecord record = recordFactory.CreateRecord(_mainStream, bse.Offset);
if (record is EscherBlipRecord)
{
record.FillFields(_mainStream, bse.Offset, recordFactory);
blip = (EscherBlipRecord)record;
pictures.Add(new Picture(blip.PictureData));
}
}
catch (Exception exc)
{
logger.Log(
POILogger.WARN,
"Unable to load picture from BLIB record at offset #",
bse.Offset, exc);
}
}
}
// Recursive call.
SearchForPictures(escherRecord.ChildRecords, pictures);
}
}
/**
* Not all documents have all the images concatenated in the data stream
* although MS claims so. The best approach is to scan all character Runs.
*
* @return a list of Picture objects found in current document
*/
public List<Picture> GetAllPictures()
{
List<Picture> pictures = new List<Picture>();
Range range = _document.GetOverallRange();
for (int i = 0; i < range.NumCharacterRuns; i++)
{
CharacterRun run = range.GetCharacterRun(i);
if (run == null)
{
continue;
}
Picture picture = ExtractPicture(run, false);
if (picture != null)
{
pictures.Add(picture);
}
}
SearchForPictures(_dgg.EscherRecords, pictures);
return pictures;
}
private bool IsBlockContainsImage(int i)
{
return IsPictureRecognized(GetBlockType(_dataStream, i), GetMmMode(_dataStream, i));
}
private bool IsBlockContainsHorizontalLine(int i)
{
return GetBlockType(_dataStream, i) == TYPE_HORIZONTAL_LINE && GetMmMode(_dataStream, i) == 0x64;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Cryptography.X509Certificates {
using Microsoft.Win32;
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Security.Util;
using System.Text;
using System.Runtime.Versioning;
using System.Globalization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public enum X509ContentType {
Unknown = 0x00,
Cert = 0x01,
SerializedCert = 0x02,
Pfx = 0x03,
Pkcs12 = Pfx,
SerializedStore = 0x04,
Pkcs7 = 0x05,
Authenticode = 0x06
}
// DefaultKeySet, UserKeySet and MachineKeySet are mutually exclusive
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum X509KeyStorageFlags {
DefaultKeySet = 0x00,
UserKeySet = 0x01,
MachineKeySet = 0x02,
Exportable = 0x04,
UserProtected = 0x08,
PersistKeySet = 0x10
}
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class X509Certificate :
IDisposable,
IDeserializationCallback,
ISerializable {
private const string m_format = "X509";
private string m_subjectName;
private string m_issuerName;
private byte[] m_serialNumber;
private byte[] m_publicKeyParameters;
private byte[] m_publicKeyValue;
private string m_publicKeyOid;
private byte[] m_rawData;
private byte[] m_thumbprint;
private DateTime m_notBefore;
private DateTime m_notAfter;
[System.Security.SecurityCritical] // auto-generated
private SafeCertContextHandle m_safeCertContext;
private bool m_certContextCloned = false;
//
// public constructors
//
[System.Security.SecuritySafeCritical] // auto-generated
private void Init()
{
m_safeCertContext = SafeCertContextHandle.InvalidHandle;
}
public X509Certificate ()
{
Init();
}
public X509Certificate (byte[] data):this() {
if ((data != null) && (data.Length != 0))
LoadCertificateFromBlob(data, null, X509KeyStorageFlags.DefaultKeySet);
}
public X509Certificate (byte[] rawData, string password):this() {
#if FEATURE_LEGACYNETCF
if ((rawData != null) && (rawData.Length != 0)) {
#endif
LoadCertificateFromBlob(rawData, password, X509KeyStorageFlags.DefaultKeySet);
#if FEATURE_LEGACYNETCF
}
#endif
}
#if FEATURE_X509_SECURESTRINGS
public X509Certificate (byte[] rawData, SecureString password):this() {
LoadCertificateFromBlob(rawData, password, X509KeyStorageFlags.DefaultKeySet);
}
#endif // FEATURE_X509_SECURESTRINGS
public X509Certificate (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags):this() {
#if FEATURE_LEGACYNETCF
if ((rawData != null) && (rawData.Length != 0)) {
#endif
LoadCertificateFromBlob(rawData, password, keyStorageFlags);
#if FEATURE_LEGACYNETCF
}
#endif
}
#if FEATURE_X509_SECURESTRINGS
public X509Certificate (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags):this() {
LoadCertificateFromBlob(rawData, password, keyStorageFlags);
}
#endif // FEATURE_X509_SECURESTRINGS
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
public X509Certificate (string fileName):this() {
LoadCertificateFromFile(fileName, null, X509KeyStorageFlags.DefaultKeySet);
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
public X509Certificate (string fileName, string password):this() {
LoadCertificateFromFile(fileName, password, X509KeyStorageFlags.DefaultKeySet);
}
#if FEATURE_X509_SECURESTRINGS
[System.Security.SecuritySafeCritical] // auto-generated
public X509Certificate (string fileName, SecureString password):this() {
LoadCertificateFromFile(fileName, password, X509KeyStorageFlags.DefaultKeySet);
}
#endif // FEATURE_X509_SECURESTRINGS
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
public X509Certificate (string fileName, string password, X509KeyStorageFlags keyStorageFlags):this() {
LoadCertificateFromFile(fileName, password, keyStorageFlags);
}
#if FEATURE_X509_SECURESTRINGS
[System.Security.SecuritySafeCritical] // auto-generated
public X509Certificate (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags):this() {
LoadCertificateFromFile(fileName, password, keyStorageFlags);
}
#endif // FEATURE_X509_SECURESTRINGS
// Package protected constructor for creating a certificate from a PCCERT_CONTEXT
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
#endif
public X509Certificate (IntPtr handle):this() {
if (handle == IntPtr.Zero)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHandle"), "handle");
Contract.EndContractBlock();
X509Utils._DuplicateCertContext(handle, ref m_safeCertContext);
}
[System.Security.SecuritySafeCritical] // auto-generated
public X509Certificate (X509Certificate cert):this() {
if (cert == null)
throw new ArgumentNullException("cert");
Contract.EndContractBlock();
if (cert.m_safeCertContext.pCertContext != IntPtr.Zero) {
m_safeCertContext = cert.GetCertContextForCloning();
m_certContextCloned = true;
}
}
public X509Certificate (SerializationInfo info, StreamingContext context):this() {
byte[] rawData = (byte[]) info.GetValue("RawData", typeof(byte[]));
if (rawData != null)
LoadCertificateFromBlob(rawData, null, X509KeyStorageFlags.DefaultKeySet);
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public static X509Certificate CreateFromCertFile (string filename) {
return new X509Certificate(filename);
}
public static X509Certificate CreateFromSignedFile (string filename) {
return new X509Certificate(filename);
}
[System.Runtime.InteropServices.ComVisible(false)]
public IntPtr Handle {
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
#endif
get {
return m_safeCertContext.pCertContext;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method has been deprecated. Please use the Subject property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual string GetName() {
ThrowIfContextInvalid();
return X509Utils._GetSubjectInfo(m_safeCertContext, X509Constants.CERT_NAME_RDN_TYPE, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
[Obsolete("This method has been deprecated. Please use the Issuer property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public virtual string GetIssuerName() {
ThrowIfContextInvalid();
return X509Utils._GetIssuerName(m_safeCertContext, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual byte[] GetSerialNumber() {
ThrowIfContextInvalid();
if (m_serialNumber == null)
m_serialNumber = X509Utils._GetSerialNumber(m_safeCertContext);
return (byte[]) m_serialNumber.Clone();
}
public virtual string GetSerialNumberString() {
return SerialNumber;
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual byte[] GetKeyAlgorithmParameters() {
ThrowIfContextInvalid();
if (m_publicKeyParameters == null)
m_publicKeyParameters = X509Utils._GetPublicKeyParameters(m_safeCertContext);
return (byte[]) m_publicKeyParameters.Clone();
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual string GetKeyAlgorithmParametersString() {
ThrowIfContextInvalid();
return Hex.EncodeHexString(GetKeyAlgorithmParameters());
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual string GetKeyAlgorithm() {
ThrowIfContextInvalid();
if (m_publicKeyOid == null)
m_publicKeyOid = X509Utils._GetPublicKeyOid(m_safeCertContext);
return m_publicKeyOid;
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual byte[] GetPublicKey() {
ThrowIfContextInvalid();
if (m_publicKeyValue == null)
m_publicKeyValue = X509Utils._GetPublicKeyValue(m_safeCertContext);
return (byte[]) m_publicKeyValue.Clone();
}
public virtual string GetPublicKeyString() {
return Hex.EncodeHexString(GetPublicKey());
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual byte[] GetRawCertData() {
return RawData;
}
public virtual string GetRawCertDataString() {
return Hex.EncodeHexString(GetRawCertData());
}
public virtual byte[] GetCertHash() {
SetThumbprint();
return (byte[]) m_thumbprint.Clone();
}
public virtual string GetCertHashString() {
SetThumbprint();
return Hex.EncodeHexString(m_thumbprint);
}
public virtual string GetEffectiveDateString() {
return NotBefore.ToString();
}
public virtual string GetExpirationDateString() {
return NotAfter.ToString();
}
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals (Object obj) {
if (!(obj is X509Certificate)) return false;
X509Certificate other = (X509Certificate) obj;
return this.Equals(other);
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual bool Equals (X509Certificate other) {
if (other == null)
return false;
if (m_safeCertContext.IsInvalid)
return other.m_safeCertContext.IsInvalid;
if (!this.Issuer.Equals(other.Issuer))
return false;
if (!this.SerialNumber.Equals(other.SerialNumber))
return false;
return true;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override int GetHashCode() {
if (m_safeCertContext.IsInvalid)
return 0;
SetThumbprint();
int value = 0;
for (int i = 0; i < m_thumbprint.Length && i < 4; ++i) {
value = value << 8 | m_thumbprint[i];
}
return value;
}
public override string ToString() {
return ToString(false);
}
[System.Security.SecuritySafeCritical] // auto-generated
public virtual string ToString (bool fVerbose) {
if (fVerbose == false || m_safeCertContext.IsInvalid)
return GetType().FullName;
StringBuilder sb = new StringBuilder();
// Subject
sb.Append("[Subject]" + Environment.NewLine + " ");
sb.Append(this.Subject);
// Issuer
sb.Append(Environment.NewLine + Environment.NewLine + "[Issuer]" + Environment.NewLine + " ");
sb.Append(this.Issuer);
// Serial Number
sb.Append(Environment.NewLine + Environment.NewLine + "[Serial Number]" + Environment.NewLine + " ");
sb.Append(this.SerialNumber);
// NotBefore
sb.Append(Environment.NewLine + Environment.NewLine + "[Not Before]" + Environment.NewLine + " ");
sb.Append(FormatDate(this.NotBefore));
// NotAfter
sb.Append(Environment.NewLine + Environment.NewLine + "[Not After]" + Environment.NewLine + " ");
sb.Append(FormatDate(this.NotAfter));
// Thumbprint
sb.Append(Environment.NewLine + Environment.NewLine + "[Thumbprint]" + Environment.NewLine + " ");
sb.Append(this.GetCertHashString());
sb.Append(Environment.NewLine);
return sb.ToString();
}
/// <summary>
/// Convert a date to a string.
///
/// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into
/// the future into strings. If the expiration date of an X.509 certificate is beyond the range
/// of one of these these cases, we need to fall back to a calendar which can express the dates
/// </summary>
protected static string FormatDate(DateTime date) {
CultureInfo culture = CultureInfo.CurrentCulture;
if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0)) {
// The most common case of culture failing to work is in the Um-AlQuara calendar. In this case,
// we can fall back to the Hijri calendar, otherwise fall back to the invariant culture.
if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar) {
culture = culture.Clone() as CultureInfo;
culture.DateTimeFormat.Calendar = new HijriCalendar();
}
else
{
culture = CultureInfo.InvariantCulture;
}
}
return date.ToString(culture);
}
public virtual string GetFormat() {
return m_format;
}
public string Issuer {
[System.Security.SecuritySafeCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_issuerName == null)
m_issuerName = X509Utils._GetIssuerName(m_safeCertContext, false);
return m_issuerName;
}
}
public string Subject {
[System.Security.SecuritySafeCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_subjectName == null)
m_subjectName = X509Utils._GetSubjectInfo(m_safeCertContext, X509Constants.CERT_NAME_RDN_TYPE, false);
return m_subjectName;
}
}
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#else
[System.Security.SecurityCritical]
#endif
// auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Import(byte[] rawData) {
Reset();
LoadCertificateFromBlob(rawData, null, X509KeyStorageFlags.DefaultKeySet);
}
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#else
[System.Security.SecurityCritical]
#endif
// auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) {
Reset();
LoadCertificateFromBlob(rawData, password, keyStorageFlags);
}
#if FEATURE_X509_SECURESTRINGS
[System.Security.SecurityCritical] // auto-generated_required
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) {
Reset();
LoadCertificateFromBlob(rawData, password, keyStorageFlags);
}
#endif // FEATURE_X509_SECURESTRINGS
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Import(string fileName) {
Reset();
LoadCertificateFromFile(fileName, null, X509KeyStorageFlags.DefaultKeySet);
}
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) {
Reset();
LoadCertificateFromFile(fileName, password, keyStorageFlags);
}
#if FEATURE_X509_SECURESTRINGS
[System.Security.SecurityCritical] // auto-generated_required
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) {
Reset();
LoadCertificateFromFile(fileName, password, keyStorageFlags);
}
#endif // FEATURE_X509_SECURESTRINGS
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public virtual byte[] Export(X509ContentType contentType) {
return ExportHelper(contentType, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(false)]
public virtual byte[] Export(X509ContentType contentType, string password) {
return ExportHelper(contentType, password);
}
#if FEATURE_X509_SECURESTRINGS
[System.Security.SecuritySafeCritical] // auto-generated
public virtual byte[] Export(X509ContentType contentType, SecureString password) {
return ExportHelper(contentType, password);
}
#endif // FEATURE_X509_SECURESTRINGS
[System.Security.SecurityCritical] // auto-generated_required
[System.Runtime.InteropServices.ComVisible(false)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)]
#pragma warning restore 618
public virtual void Reset () {
m_subjectName = null;
m_issuerName = null;
m_serialNumber = null;
m_publicKeyParameters = null;
m_publicKeyValue = null;
m_publicKeyOid = null;
m_rawData = null;
m_thumbprint = null;
m_notBefore = DateTime.MinValue;
m_notAfter = DateTime.MinValue;
if (!m_safeCertContext.IsInvalid) {
// Free the current certificate handle
if (!m_certContextCloned) {
m_safeCertContext.Dispose();
}
m_safeCertContext = SafeCertContextHandle.InvalidHandle;
}
m_certContextCloned = false;
}
public void Dispose() {
Dispose(true);
}
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing) {
if (disposing) {
Reset();
}
}
#if FEATURE_SERIALIZATION
/// <internalonly/>
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) {
if (m_safeCertContext.IsInvalid)
info.AddValue("RawData", null);
else
info.AddValue("RawData", this.RawData);
}
/// <internalonly/>
void IDeserializationCallback.OnDeserialization(Object sender) {}
#endif
//
// internal.
//
internal SafeCertContextHandle CertContext {
[System.Security.SecurityCritical] // auto-generated
get {
return m_safeCertContext;
}
}
/// <summary>
/// Returns the SafeCertContextHandle. Use this instead of the CertContext property when
/// creating another X509Certificate object based on this one to ensure the underlying
/// cert context is not released at the wrong time.
/// </summary>
[System.Security.SecurityCritical]
internal SafeCertContextHandle GetCertContextForCloning() {
m_certContextCloned = true;
return m_safeCertContext;
}
//
// private methods.
//
[System.Security.SecurityCritical] // auto-generated
private void ThrowIfContextInvalid() {
if (m_safeCertContext.IsInvalid)
throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidHandle"), "m_safeCertContext");
}
private DateTime NotAfter {
[System.Security.SecuritySafeCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_notAfter == DateTime.MinValue) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME();
X509Utils._GetDateNotAfter(m_safeCertContext, ref fileTime);
m_notAfter = DateTime.FromFileTime(fileTime.ToTicks());
}
return m_notAfter;
}
}
private DateTime NotBefore {
[System.Security.SecuritySafeCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_notBefore == DateTime.MinValue) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME();
X509Utils._GetDateNotBefore(m_safeCertContext, ref fileTime);
m_notBefore = DateTime.FromFileTime(fileTime.ToTicks());
}
return m_notBefore;
}
}
private byte[] RawData {
[System.Security.SecurityCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_rawData == null)
m_rawData = X509Utils._GetCertRawData(m_safeCertContext);
return (byte[]) m_rawData.Clone();
}
}
private string SerialNumber {
[System.Security.SecuritySafeCritical] // auto-generated
get {
ThrowIfContextInvalid();
if (m_serialNumber == null)
m_serialNumber = X509Utils._GetSerialNumber(m_safeCertContext);
return Hex.EncodeHexStringFromInt(m_serialNumber);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
private void SetThumbprint () {
ThrowIfContextInvalid();
if (m_thumbprint == null)
m_thumbprint = X509Utils._GetThumbprint(m_safeCertContext);
}
[System.Security.SecurityCritical] // auto-generated
private byte[] ExportHelper (X509ContentType contentType, object password) {
switch(contentType) {
case X509ContentType.Cert:
break;
#if FEATURE_CORECLR
case (X509ContentType)0x02 /* X509ContentType.SerializedCert */:
case (X509ContentType)0x03 /* X509ContentType.Pkcs12 */:
throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"),
new NotSupportedException());
#else // FEATURE_CORECLR
case X509ContentType.SerializedCert:
break;
case X509ContentType.Pkcs12:
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Open | KeyContainerPermissionFlags.Export);
kp.Demand();
break;
#endif // FEATURE_CORECLR else
default:
throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_InvalidContentType"));
}
#if !FEATURE_CORECLR
IntPtr szPassword = IntPtr.Zero;
byte[] encodedRawData = null;
SafeCertStoreHandle safeCertStoreHandle = X509Utils.ExportCertToMemoryStore(this);
RuntimeHelpers.PrepareConstrainedRegions();
try {
szPassword = X509Utils.PasswordToHGlobalUni(password);
encodedRawData = X509Utils._ExportCertificatesToBlob(safeCertStoreHandle, contentType, szPassword);
}
finally {
if (szPassword != IntPtr.Zero)
Marshal.ZeroFreeGlobalAllocUnicode(szPassword);
safeCertStoreHandle.Dispose();
}
if (encodedRawData == null)
throw new CryptographicException(Environment.GetResourceString("Cryptography_X509_ExportFailed"));
return encodedRawData;
#else // !FEATURE_CORECLR
return RawData;
#endif // !FEATURE_CORECLR
}
[System.Security.SecuritySafeCritical] // auto-generated
private void LoadCertificateFromBlob (byte[] rawData, object password, X509KeyStorageFlags keyStorageFlags) {
if (rawData == null || rawData.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyOrNullArray"), "rawData");
Contract.EndContractBlock();
X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertBlobType(rawData));
#if !FEATURE_CORECLR
if (contentType == X509ContentType.Pkcs12 &&
(keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create);
kp.Demand();
}
#endif // !FEATURE_CORECLR
uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags);
IntPtr szPassword = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try {
szPassword = X509Utils.PasswordToHGlobalUni(password);
X509Utils._LoadCertFromBlob(rawData,
szPassword,
dwFlags,
#if FEATURE_CORECLR
false,
#else // FEATURE_CORECLR
(keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true,
#endif // FEATURE_CORECLR else
ref m_safeCertContext);
}
finally {
if (szPassword != IntPtr.Zero)
Marshal.ZeroFreeGlobalAllocUnicode(szPassword);
}
}
[System.Security.SecurityCritical] // auto-generated
private void LoadCertificateFromFile (string fileName, object password, X509KeyStorageFlags keyStorageFlags) {
if (fileName == null)
throw new ArgumentNullException("fileName");
Contract.EndContractBlock();
string fullPath = Path.GetFullPathInternal(fileName);
new FileIOPermission (FileIOPermissionAccess.Read, fullPath).Demand();
X509ContentType contentType = X509Utils.MapContentType(X509Utils._QueryCertFileType(fileName));
#if !FEATURE_CORECLR
if (contentType == X509ContentType.Pkcs12 &&
(keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == X509KeyStorageFlags.PersistKeySet) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.Create);
kp.Demand();
}
#endif // !FEATURE_CORECLR
uint dwFlags = X509Utils.MapKeyStorageFlags(keyStorageFlags);
IntPtr szPassword = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try {
szPassword = X509Utils.PasswordToHGlobalUni(password);
X509Utils._LoadCertFromFile(fileName,
szPassword,
dwFlags,
#if FEATURE_CORECLR
false,
#else // FEATURE_CORECLR
(keyStorageFlags & X509KeyStorageFlags.PersistKeySet) == 0 ? false : true,
#endif // FEATURE_CORECLR else
ref m_safeCertContext);
}
finally {
if (szPassword != IntPtr.Zero)
Marshal.ZeroFreeGlobalAllocUnicode(szPassword);
}
}
#if FEATURE_LEGACYNETCF
protected internal String CreateHexString(byte[] sArray) {
return Hex.EncodeHexString(sArray);
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// (C) 2002 Ville Palo
// (C) 2003 Martin Willemoes Hansen
// Copyright (C) 2004 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 Xunit;
using System.Xml;
using System.Data.SqlTypes;
using System.Globalization;
namespace System.Data.Tests.SqlTypes
{
public class SqlByteTest
{
private const string Error = " does not work correctly";
public SqlByteTest()
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
}
// Test constructor
[Fact]
public void Create()
{
byte b = 29;
SqlByte TestByte = new SqlByte(b);
Assert.Equal((byte)29, TestByte.Value);
}
// Test public fields
[Fact]
public void PublicFields()
{
Assert.Equal((SqlByte)255, SqlByte.MaxValue);
Assert.Equal((SqlByte)0, SqlByte.MinValue);
Assert.True(SqlByte.Null.IsNull);
Assert.Equal((byte)0, SqlByte.Zero.Value);
}
// Test properties
[Fact]
public void Properties()
{
SqlByte TestByte = new SqlByte(54);
SqlByte TestByte2 = new SqlByte(1);
Assert.True(SqlByte.Null.IsNull);
Assert.Equal((byte)54, TestByte.Value);
Assert.Equal((byte)1, TestByte2.Value);
}
// PUBLIC STATIC METHODS
[Fact]
public void AddMethod()
{
SqlByte TestByte64 = new SqlByte(64);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte164 = new SqlByte(164);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((byte)64, SqlByte.Add(TestByte64, TestByte0).Value);
Assert.Equal((byte)228, SqlByte.Add(TestByte64, TestByte164).Value);
Assert.Equal((byte)164, SqlByte.Add(TestByte0, TestByte164).Value);
Assert.Equal((byte)255, SqlByte.Add(TestByte255, TestByte0).Value);
try
{
SqlByte.Add(TestByte255, TestByte64);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void BitwiseAndMethod()
{
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte1 = new SqlByte(1);
SqlByte TestByte62 = new SqlByte(62);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((byte)0, SqlByte.BitwiseAnd(TestByte2, TestByte1).Value);
Assert.Equal((byte)0, SqlByte.BitwiseAnd(TestByte1, TestByte62).Value);
Assert.Equal((byte)2, SqlByte.BitwiseAnd(TestByte62, TestByte2).Value);
Assert.Equal((byte)1, SqlByte.BitwiseAnd(TestByte1, TestByte255).Value);
Assert.Equal((byte)62, SqlByte.BitwiseAnd(TestByte62, TestByte255).Value);
}
[Fact]
public void BitwiseOrMethod()
{
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte1 = new SqlByte(1);
SqlByte TestByte62 = new SqlByte(62);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((byte)3, SqlByte.BitwiseOr(TestByte2, TestByte1).Value);
Assert.Equal((byte)63, SqlByte.BitwiseOr(TestByte1, TestByte62).Value);
Assert.Equal((byte)62, SqlByte.BitwiseOr(TestByte62, TestByte2).Value);
Assert.Equal((byte)255, SqlByte.BitwiseOr(TestByte1, TestByte255).Value);
Assert.Equal((byte)255, SqlByte.BitwiseOr(TestByte62, TestByte255).Value);
}
[Fact]
public void CompareTo()
{
SqlByte TestByte13 = new SqlByte(13);
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte10II = new SqlByte(10);
SqlString TestString = new SqlString("This is a test");
Assert.True(TestByte13.CompareTo(TestByte10) > 0);
Assert.True(TestByte10.CompareTo(TestByte13) < 0);
Assert.True(TestByte10.CompareTo(TestByte10II) == 0);
try
{
TestByte13.CompareTo(TestString);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentException), e.GetType());
}
}
[Fact]
public void DivideMethod()
{
SqlByte TestByte13 = new SqlByte(13);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte180 = new SqlByte(180);
SqlByte TestByte3 = new SqlByte(3);
Assert.Equal((byte)6, SqlByte.Divide(TestByte13, TestByte2).Value);
Assert.Equal((byte)90, SqlByte.Divide(TestByte180, TestByte2).Value);
Assert.Equal((byte)60, SqlByte.Divide(TestByte180, TestByte3).Value);
Assert.Equal((byte)0, SqlByte.Divide(TestByte13, TestByte180).Value);
Assert.Equal((byte)0, SqlByte.Divide(TestByte13, TestByte180).Value);
try
{
SqlByte.Divide(TestByte13, TestByte0);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(DivideByZeroException), e.GetType());
}
}
[Fact]
public void EqualsMethod()
{
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte158 = new SqlByte(158);
SqlByte TestByte180 = new SqlByte(180);
SqlByte TestByte180II = new SqlByte(180);
Assert.True(!TestByte0.Equals(TestByte158));
Assert.True(!TestByte158.Equals(TestByte180));
Assert.True(!TestByte180.Equals(new SqlString("TEST")));
Assert.True(TestByte180.Equals(TestByte180II));
}
[Fact]
public void StaticEqualsMethod()
{
SqlByte TestByte34 = new SqlByte(34);
SqlByte TestByte34II = new SqlByte(34);
SqlByte TestByte15 = new SqlByte(15);
Assert.True(SqlByte.Equals(TestByte34, TestByte34II).Value);
Assert.True(!SqlByte.Equals(TestByte34, TestByte15).Value);
Assert.True(!SqlByte.Equals(TestByte15, TestByte34II).Value);
}
[Fact]
public void GetHashCodeTest()
{
SqlByte TestByte15 = new SqlByte(15);
SqlByte TestByte216 = new SqlByte(216);
Assert.Equal(15, TestByte15.GetHashCode());
Assert.Equal(216, TestByte216.GetHashCode());
}
[Fact]
public void GetTypeTest()
{
SqlByte TestByte = new SqlByte(84);
Assert.Equal("System.Data.SqlTypes.SqlByte", TestByte.GetType().ToString());
}
[Fact]
public void GreaterThan()
{
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte10II = new SqlByte(10);
SqlByte TestByte110 = new SqlByte(110);
Assert.True(!SqlByte.GreaterThan(TestByte10, TestByte110).Value);
Assert.True(SqlByte.GreaterThan(TestByte110, TestByte10).Value);
Assert.True(!SqlByte.GreaterThan(TestByte10II, TestByte10).Value);
}
[Fact]
public void GreaterThanOrEqual()
{
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte10II = new SqlByte(10);
SqlByte TestByte110 = new SqlByte(110);
Assert.True(!SqlByte.GreaterThanOrEqual(TestByte10, TestByte110).Value);
Assert.True(SqlByte.GreaterThanOrEqual(TestByte110, TestByte10).Value);
Assert.True(SqlByte.GreaterThanOrEqual(TestByte10II, TestByte10).Value);
}
[Fact]
public void LessThan()
{
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte10II = new SqlByte(10);
SqlByte TestByte110 = new SqlByte(110);
Assert.True(SqlByte.LessThan(TestByte10, TestByte110).Value);
Assert.True(!SqlByte.LessThan(TestByte110, TestByte10).Value);
Assert.True(!SqlByte.LessThan(TestByte10II, TestByte10).Value);
}
[Fact]
public void LessThanOrEqual()
{
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte10II = new SqlByte(10);
SqlByte TestByte110 = new SqlByte(110);
Assert.True(SqlByte.LessThanOrEqual(TestByte10, TestByte110).Value);
Assert.True(!SqlByte.LessThanOrEqual(TestByte110, TestByte10).Value);
Assert.True(SqlByte.LessThanOrEqual(TestByte10II, TestByte10).Value);
Assert.True(SqlByte.LessThanOrEqual(TestByte10II, SqlByte.Null).IsNull);
}
[Fact]
public void Mod()
{
SqlByte TestByte132 = new SqlByte(132);
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte200 = new SqlByte(200);
Assert.Equal((SqlByte)2, SqlByte.Mod(TestByte132, TestByte10));
Assert.Equal((SqlByte)10, SqlByte.Mod(TestByte10, TestByte200));
Assert.Equal((SqlByte)0, SqlByte.Mod(TestByte200, TestByte10));
Assert.Equal((SqlByte)68, SqlByte.Mod(TestByte200, TestByte132));
}
[Fact]
public void Multiply()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((byte)24, SqlByte.Multiply(TestByte12, TestByte2).Value);
Assert.Equal((byte)24, SqlByte.Multiply(TestByte2, TestByte12).Value);
try
{
SqlByte.Multiply(TestByte128, TestByte2);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void NotEquals()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
SqlByte TestByte128II = new SqlByte(128);
Assert.True(SqlByte.NotEquals(TestByte12, TestByte128).Value);
Assert.True(SqlByte.NotEquals(TestByte128, TestByte12).Value);
Assert.True(SqlByte.NotEquals(TestByte128II, TestByte12).Value);
Assert.True(!SqlByte.NotEquals(TestByte128II, TestByte128).Value);
Assert.True(!SqlByte.NotEquals(TestByte128, TestByte128II).Value);
}
[Fact]
public void OnesComplement()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((SqlByte)243, SqlByte.OnesComplement(TestByte12));
Assert.Equal((SqlByte)127, SqlByte.OnesComplement(TestByte128));
}
[Fact]
public void Parse()
{
try
{
SqlByte.Parse(null);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(ArgumentNullException), e.GetType());
}
try
{
SqlByte.Parse("not-a-number");
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(FormatException), e.GetType());
}
try
{
int OverInt = (int)SqlByte.MaxValue + 1;
SqlByte.Parse(OverInt.ToString());
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
Assert.Equal((byte)150, SqlByte.Parse("150").Value);
}
[Fact]
public void Subtract()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((byte)116, SqlByte.Subtract(TestByte128, TestByte12).Value);
try
{
SqlByte.Subtract(TestByte12, TestByte128);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void ToSqlBoolean()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByteNull = SqlByte.Null;
Assert.True(TestByte12.ToSqlBoolean().Value);
Assert.True(!TestByte0.ToSqlBoolean().Value);
Assert.True(TestByteNull.ToSqlBoolean().IsNull);
}
[Fact]
public void ToSqlDecimal()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12, TestByte12.ToSqlDecimal().Value);
Assert.Equal(0, TestByte0.ToSqlDecimal().Value);
Assert.Equal(228, TestByte228.ToSqlDecimal().Value);
}
[Fact]
public void ToSqlDouble()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12, TestByte12.ToSqlDouble().Value);
Assert.Equal(0, TestByte0.ToSqlDouble().Value);
Assert.Equal(228, TestByte228.ToSqlDouble().Value);
}
[Fact]
public void ToSqlInt16()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal((short)12, TestByte12.ToSqlInt16().Value);
Assert.Equal((short)0, TestByte0.ToSqlInt16().Value);
Assert.Equal((short)228, TestByte228.ToSqlInt16().Value);
}
[Fact]
public void ToSqlInt32()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12, TestByte12.ToSqlInt32().Value);
Assert.Equal(0, TestByte0.ToSqlInt32().Value);
Assert.Equal(228, TestByte228.ToSqlInt32().Value);
}
[Fact]
public void ToSqlInt64()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12, TestByte12.ToSqlInt64().Value);
Assert.Equal(0, TestByte0.ToSqlInt64().Value);
Assert.Equal(228, TestByte228.ToSqlInt64().Value);
}
[Fact]
public void ToSqlMoney()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12.0000M, TestByte12.ToSqlMoney().Value);
Assert.Equal(0, TestByte0.ToSqlMoney().Value);
Assert.Equal(228.0000M, TestByte228.ToSqlMoney().Value);
}
[Fact]
public void ToSqlSingle()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal(12, TestByte12.ToSqlSingle().Value);
Assert.Equal(0, TestByte0.ToSqlSingle().Value);
Assert.Equal(228, TestByte228.ToSqlSingle().Value);
}
[Fact]
public void ToSqlString()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal("12", TestByte12.ToSqlString().Value);
Assert.Equal("0", TestByte0.ToSqlString().Value);
Assert.Equal("228", TestByte228.ToSqlString().Value);
}
[Fact]
public void ToStringTest()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte0 = new SqlByte(0);
SqlByte TestByte228 = new SqlByte(228);
Assert.Equal("12", TestByte12.ToString());
Assert.Equal("0", TestByte0.ToString());
Assert.Equal("228", TestByte228.ToString());
}
[Fact]
public void TestXor()
{
SqlByte TestByte14 = new SqlByte(14);
SqlByte TestByte58 = new SqlByte(58);
SqlByte TestByte130 = new SqlByte(130);
Assert.Equal((byte)52, SqlByte.Xor(TestByte14, TestByte58).Value);
Assert.Equal((byte)140, SqlByte.Xor(TestByte14, TestByte130).Value);
Assert.Equal((byte)184, SqlByte.Xor(TestByte58, TestByte130).Value);
}
// OPERATORS
[Fact]
public void AdditionOperator()
{
SqlByte TestByte24 = new SqlByte(24);
SqlByte TestByte64 = new SqlByte(64);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((SqlByte)88, TestByte24 + TestByte64);
try
{
SqlByte result = TestByte64 + TestByte255;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void BitwiseAndOperator()
{
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte4 = new SqlByte(4);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((SqlByte)0, TestByte2 & TestByte4);
Assert.Equal((SqlByte)2, TestByte2 & TestByte255);
}
[Fact]
public void BitwiseOrOperator()
{
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte4 = new SqlByte(4);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((SqlByte)6, TestByte2 | TestByte4);
Assert.Equal((SqlByte)255, TestByte2 | TestByte255);
}
[Fact]
public void DivisionOperator()
{
SqlByte TestByte2 = new SqlByte(2);
SqlByte TestByte4 = new SqlByte(4);
SqlByte TestByte255 = new SqlByte(255);
SqlByte TestByte0 = new SqlByte(0);
Assert.Equal((SqlByte)2, TestByte4 / TestByte2);
Assert.Equal((SqlByte)127, TestByte255 / TestByte2);
try
{
TestByte2 = TestByte255 / TestByte0;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(DivideByZeroException), e.GetType());
}
}
[Fact]
public void EqualityOperator()
{
SqlByte TestByte15 = new SqlByte(15);
SqlByte TestByte15II = new SqlByte(15);
SqlByte TestByte255 = new SqlByte(255);
Assert.True((TestByte15 == TestByte15II).Value);
Assert.True(!(TestByte15 == TestByte255).Value);
Assert.True(!(TestByte15 != TestByte15II).Value);
Assert.True((TestByte15 != TestByte255).Value);
}
[Fact]
public void ExclusiveOrOperator()
{
SqlByte TestByte15 = new SqlByte(15);
SqlByte TestByte10 = new SqlByte(10);
SqlByte TestByte255 = new SqlByte(255);
Assert.Equal((SqlByte)5, (TestByte15 ^ TestByte10));
Assert.Equal((SqlByte)240, (TestByte15 ^ TestByte255));
}
[Fact]
public void ThanOrEqualOperators()
{
SqlByte TestByte165 = new SqlByte(165);
SqlByte TestByte100 = new SqlByte(100);
SqlByte TestByte100II = new SqlByte(100);
SqlByte TestByte255 = new SqlByte(255);
Assert.True((TestByte165 > TestByte100).Value);
Assert.True(!(TestByte165 > TestByte255).Value);
Assert.True(!(TestByte100 > TestByte100II).Value);
Assert.True(!(TestByte165 >= TestByte255).Value);
Assert.True((TestByte255 >= TestByte165).Value);
Assert.True((TestByte100 >= TestByte100II).Value);
Assert.True(!(TestByte165 < TestByte100).Value);
Assert.True((TestByte165 < TestByte255).Value);
Assert.True(!(TestByte100 < TestByte100II).Value);
Assert.True((TestByte165 <= TestByte255).Value);
Assert.True(!(TestByte255 <= TestByte165).Value);
Assert.True((TestByte100 <= TestByte100II).Value);
}
[Fact]
public void MultiplicationOperator()
{
SqlByte TestByte4 = new SqlByte(4);
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((SqlByte)48, TestByte4 * TestByte12);
try
{
SqlByte test = (TestByte128 * TestByte4);
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void OnesComplementOperator()
{
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((SqlByte)243, ~TestByte12);
Assert.Equal((SqlByte)127, ~TestByte128);
}
[Fact]
public void SubtractionOperator()
{
SqlByte TestByte4 = new SqlByte(4);
SqlByte TestByte12 = new SqlByte(12);
SqlByte TestByte128 = new SqlByte(128);
Assert.Equal((SqlByte)8, TestByte12 - TestByte4);
try
{
SqlByte test = TestByte4 - TestByte128;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlBooleanToSqlByte()
{
SqlBoolean TestBoolean = new SqlBoolean(true);
SqlByte TestByte;
TestByte = (SqlByte)TestBoolean;
Assert.Equal((byte)1, TestByte.Value);
}
[Fact]
public void SqlByteToByte()
{
SqlByte TestByte = new SqlByte(12);
byte test = (byte)TestByte;
Assert.Equal((byte)12, test);
}
[Fact]
public void SqlDecimalToSqlByte()
{
SqlDecimal TestDecimal64 = new SqlDecimal(64);
SqlDecimal TestDecimal900 = new SqlDecimal(900);
Assert.Equal((byte)64, ((SqlByte)TestDecimal64).Value);
try
{
SqlByte test = (SqlByte)TestDecimal900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlDoubleToSqlByte()
{
SqlDouble TestDouble64 = new SqlDouble(64);
SqlDouble TestDouble900 = new SqlDouble(900);
Assert.Equal((byte)64, ((SqlByte)TestDouble64).Value);
try
{
SqlByte test = (SqlByte)TestDouble900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlInt16ToSqlByte()
{
SqlInt16 TestInt1664 = new SqlInt16(64);
SqlInt16 TestInt16900 = new SqlInt16(900);
Assert.Equal((byte)64, ((SqlByte)TestInt1664).Value);
try
{
SqlByte test = (SqlByte)TestInt16900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlInt32ToSqlByte()
{
SqlInt32 TestInt3264 = new SqlInt32(64);
SqlInt32 TestInt32900 = new SqlInt32(900);
Assert.Equal((byte)64, ((SqlByte)TestInt3264).Value);
try
{
SqlByte test = (SqlByte)TestInt32900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlInt64ToSqlByte()
{
SqlInt64 TestInt6464 = new SqlInt64(64);
SqlInt64 TestInt64900 = new SqlInt64(900);
Assert.Equal((byte)64, ((SqlByte)TestInt6464).Value);
try
{
SqlByte test = (SqlByte)TestInt64900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlMoneyToSqlByte()
{
SqlMoney TestMoney64 = new SqlMoney(64);
SqlMoney TestMoney900 = new SqlMoney(900);
Assert.Equal((byte)64, ((SqlByte)TestMoney64).Value);
try
{
SqlByte test = (SqlByte)TestMoney900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlSingleToSqlByte()
{
SqlSingle TestSingle64 = new SqlSingle(64);
SqlSingle TestSingle900 = new SqlSingle(900);
Assert.Equal((byte)64, ((SqlByte)TestSingle64).Value);
try
{
SqlByte test = (SqlByte)TestSingle900;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
}
[Fact]
public void SqlStringToSqlByte()
{
SqlString TestString = new SqlString("Test string");
SqlString TestString100 = new SqlString("100");
SqlString TestString1000 = new SqlString("1000");
Assert.Equal((byte)100, ((SqlByte)TestString100).Value);
try
{
SqlByte test = (SqlByte)TestString1000;
}
catch (Exception e)
{
Assert.Equal(typeof(OverflowException), e.GetType());
}
try
{
SqlByte test = (SqlByte)TestString;
Assert.False(true);
}
catch (Exception e)
{
Assert.Equal(typeof(FormatException), e.GetType());
}
}
[Fact]
public void ByteToSqlByte()
{
byte TestByte = 14;
Assert.Equal((byte)14, ((SqlByte)TestByte).Value);
}
[Fact]
public void GetXsdTypeTest()
{
XmlQualifiedName qualifiedName = SqlByte.GetXsdType(null);
Assert.Equal("unsignedByte", qualifiedName.Name);
}
}
}
| |
namespace Factotum
{
partial class LineView
{
/// <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();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LineView));
this.btnEdit = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.btnAdd = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.cboStatusFilter = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.dgvLineList = new Factotum.DataGridViewStd();
this.label3 = new System.Windows.Forms.Label();
this.txtNameFilter = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.cboUnitFilter = new System.Windows.Forms.ComboBox();
this.panel1 = new System.Windows.Forms.Panel();
this.label5 = new System.Windows.Forms.Label();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
((System.ComponentModel.ISupportInitialize)(this.dgvLineList)).BeginInit();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// btnEdit
//
this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnEdit.Location = new System.Drawing.Point(11, 251);
this.btnEdit.Name = "btnEdit";
this.btnEdit.Size = new System.Drawing.Size(64, 22);
this.btnEdit.TabIndex = 2;
this.btnEdit.Text = "Edit";
this.btnEdit.UseVisualStyleBackColor = true;
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(13, 102);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(46, 13);
this.label1.TabIndex = 5;
this.label1.Text = "Line List";
//
// btnAdd
//
this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnAdd.Location = new System.Drawing.Point(81, 251);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(64, 22);
this.btnAdd.TabIndex = 3;
this.btnAdd.Text = "Add";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnDelete
//
this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnDelete.Location = new System.Drawing.Point(151, 251);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(64, 22);
this.btnDelete.TabIndex = 4;
this.btnDelete.Text = "Delete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// cboStatusFilter
//
this.cboStatusFilter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboStatusFilter.FormattingEnabled = true;
this.cboStatusFilter.Items.AddRange(new object[] {
"Active",
"Inactive"});
this.cboStatusFilter.Location = new System.Drawing.Point(240, 40);
this.cboStatusFilter.Name = "cboStatusFilter";
this.cboStatusFilter.Size = new System.Drawing.Size(85, 21);
this.cboStatusFilter.TabIndex = 11;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(197, 43);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(37, 13);
this.label2.TabIndex = 10;
this.label2.Text = "Status";
//
// dgvLineList
//
this.dgvLineList.AllowUserToAddRows = false;
this.dgvLineList.AllowUserToDeleteRows = false;
this.dgvLineList.AllowUserToOrderColumns = true;
this.dgvLineList.AllowUserToResizeRows = false;
this.dgvLineList.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.dgvLineList.Location = new System.Drawing.Point(15, 118);
this.dgvLineList.MultiSelect = false;
this.dgvLineList.Name = "dgvLineList";
this.dgvLineList.ReadOnly = true;
this.dgvLineList.RowHeadersVisible = false;
this.dgvLineList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvLineList.Size = new System.Drawing.Size(345, 123);
this.dgvLineList.StandardTab = true;
this.dgvLineList.TabIndex = 6;
this.dgvLineList.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dgvLineList_KeyDown);
this.dgvLineList.DoubleClick += new System.EventHandler(this.btnEdit_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 43);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(58, 13);
this.label3.TabIndex = 12;
this.label3.Text = "Line Name";
//
// txtNameFilter
//
this.txtNameFilter.Location = new System.Drawing.Point(70, 40);
this.txtNameFilter.Name = "txtNameFilter";
this.txtNameFilter.Size = new System.Drawing.Size(92, 20);
this.txtNameFilter.TabIndex = 13;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(6, 17);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(30, 13);
this.label4.TabIndex = 14;
this.label4.Text = "Unit";
//
// cboUnitFilter
//
this.cboUnitFilter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboUnitFilter.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cboUnitFilter.FormattingEnabled = true;
this.cboUnitFilter.Items.AddRange(new object[] {
"Active",
"Inactive"});
this.cboUnitFilter.Location = new System.Drawing.Point(37, 14);
this.cboUnitFilter.Name = "cboUnitFilter";
this.cboUnitFilter.Size = new System.Drawing.Size(125, 21);
this.cboUnitFilter.TabIndex = 15;
//
// panel1
//
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.txtNameFilter);
this.panel1.Controls.Add(this.label4);
this.panel1.Controls.Add(this.cboStatusFilter);
this.panel1.Controls.Add(this.cboUnitFilter);
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.label3);
this.panel1.ForeColor = System.Drawing.SystemColors.ControlText;
this.panel1.Location = new System.Drawing.Point(15, 18);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(344, 75);
this.panel1.TabIndex = 1;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.ForeColor = System.Drawing.SystemColors.ControlText;
this.label5.Location = new System.Drawing.Point(22, 9);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(53, 13);
this.label5.TabIndex = 0;
this.label5.Text = "List Filters";
//
// LineView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.ClientSize = new System.Drawing.Size(373, 285);
this.Controls.Add(this.label5);
this.Controls.Add(this.panel1);
this.Controls.Add(this.dgvLineList);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnEdit);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(381, 234);
this.Name = "LineView";
this.Text = " View Lines";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.LineView_FormClosed);
this.Load += new System.EventHandler(this.LineView_Load);
((System.ComponentModel.ISupportInitialize)(this.dgvLineList)).EndInit();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnEdit;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.ComboBox cboStatusFilter;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtNameFilter;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ComboBox cboUnitFilter;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label label5;
private DataGridViewStd dgvLineList;
private System.Windows.Forms.ToolTip toolTip1;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Windows.Forms;
using System.Text;
using Epi;
using Epi.Data;
using Epi.Windows.Dialogs;
namespace Epi.Windows.Dialogs
{
/// <summary>
/// Dialog for Read command
/// </summary>
public partial class BaseReadDialog : DialogBase
{
#region Private Nested Class
private class ComboBoxItem
{
#region Implementation
private string key;
public string Key
{
get { return key; }
set { key = value; }
}
private object value;
public object Value
{
get { return this.value; }
set { this.value = value; }
}
private string text;
public string Text
{
get { return text; }
set { text = value; }
}
public ComboBoxItem(string key, string text, object value)
{
this.key = key;
this.value = value;
this.text = text;
}
public override string ToString()
{
return text.ToString();
}
#endregion
}
#endregion Private Nested Class
#region Private Attributes
private string selectedDataProvider;
private string mruSelectedDatabaseName;
private Project selectedProject;
private object selectedDataSource;
private bool ignoreDataFormatIndexChange = false;
private string savedConnectionStringDescription = string.Empty;
private string sqlQuery = string.Empty;
private Configuration config;
private object module;
#endregion Private Attributes
#region Constructor
public BaseReadDialog()
{
InitializeComponent();
Construct();
}
public BaseReadDialog(object Module)
{
module = Module;
InitializeComponent();
Construct();
}
public BaseReadDialog(object Module, IDbDriver database)
{
module = Module;
InitializeComponent();
Construct();
selectedDataSource = database;
}
public BaseReadDialog(object Module, Project project)
{
module = Module;
InitializeComponent();
Construct();
selectedDataSource = project;
selectedProject = project;
}
#endregion Constructor
#region Private Methods
private void Construct()
{
config = Configuration.GetNewInstance();
if (!this.DesignMode) // designer throws an error
{
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
}
}
private void btnOK_Click(object sender, System.EventArgs e)
{
OnOK();
}
private void LoadForm()
{
PopulateDataSourcePlugIns();
PopulateRecentDataSources();
try
{
//Project project = null;
//string filePath = System.IO.Directory.GetCurrentDirectory().ToString() + "\\Projects\\Sample.prj";
//if (System.IO.File.Exists(filePath))
//{
// Project prj = new Project(filePath);
// try
// {
// selectedDataSource = prj;
// this.selectedProject = prj;
// this.selectedDataSource = prj;
// }
// catch (Exception ex)
// {
// MessageBox.Show("Could not load project: \n\n" + ex.Message);
// return;
// }
//}
}
catch (CurrentProjectInvalidException ex)
{
Epi.Windows.MsgBox.ShowInformation(ex.Message);
}
RefreshForm();
}
private void RefreshForm()
{
lvDataSourceObjects.Groups.Clear();
lvDataSourceObjects.Items.Clear();
if (selectedDataSource is IDbDriver)
{
IDbDriver db = selectedDataSource as IDbDriver;
this.txtDataSource.Text = db.DataSource;
var SelectedDataSource = db.ConnectionString.Split('@');
if (SelectedDataSource[0].Contains("Epi Info Web Survey") || SelectedDataSource[0].Contains("Epi Info Cloud Data Capture"))
{
this.txtDataSource.Text = "Epi Info Web & Cloud Services";
}
List<string> tableNames = db.GetTableNames();
foreach (string tableName in tableNames)
{
ListViewItem newItem = new ListViewItem(new string[] { tableName, tableName });
this.lvDataSourceObjects.Items.Add(newItem);
}
gbxExplorer.Enabled = true;
}
else if (selectedDataSource is Project)
{
Project project = selectedDataSource as Project;
txtDataSource.Text = (selectedDataSource == selectedProject) ? SharedStrings.CURRENT_PROJECT : project.FullName;
try
{
if (chkViews.Checked)
{
ListViewGroup viewGroup = new ListViewGroup("Forms", "Epi Info Forms");
this.lvDataSourceObjects.Groups.Add(viewGroup);
foreach (string s in project.GetViewNames())
{
ListViewItem newItem = new ListViewItem(new string[] { s, "View" }, viewGroup);
this.lvDataSourceObjects.Items.Add(newItem);
}
}
if (chkTables.Checked)
{
ListViewGroup tablesGroup = new ListViewGroup("Tables", "Tables");
this.lvDataSourceObjects.Groups.Add(tablesGroup);
foreach (string s in project.GetNonViewTableNames())
{
ListViewItem newItem = new ListViewItem(new string[] { s, "Table" }, tablesGroup);
this.lvDataSourceObjects.Items.Add(newItem);
}
}
}
catch (Exception ex)
{
Epi.Windows.MsgBox.ShowException(ex);
txtDataSource.Text = string.Empty;
return;
}
gbxExplorer.Enabled = true;
}
else
{
// Clear ...
this.txtDataSource.Text = "(none)";
this.lvDataSourceObjects.Items.Clear();// DataSource = null;
gbxExplorer.Enabled = false;
}
this.CheckForInputSufficiency();
}
/// <summary>
/// Attach the DataFormats combobox with supported data formats
/// </summary>
private void PopulateDataSourcePlugIns()
{
try
{
ignoreDataFormatIndexChange = true;
if (cmbDataSourcePlugIns.Items.Count == 0)
{
cmbDataSourcePlugIns.Items.Clear();
cmbDataSourcePlugIns.Items.Add(new ComboBoxItem(null, "Epi Info 7 Project", null));
foreach (Epi.DataSets.Config.DataDriverRow row in config.DataDrivers)
{
cmbDataSourcePlugIns.Items.Add(new ComboBoxItem(row.Type,row.DisplayName,null));
}
}
cmbDataSourcePlugIns.SelectedIndex = 0;
}
finally
{
ignoreDataFormatIndexChange = false;
}
}
/// <summary>
/// Attach the Recent data sources combobox with the list of recent sources
/// </summary>
private void PopulateRecentDataSources()
{
try
{
ignoreDataFormatIndexChange = true;
if (cmbRecentSources.Items.Count == 0)
{
cmbRecentSources.Items.Clear();
cmbRecentSources.Items.Add(string.Empty);
foreach (Epi.DataSets.Config.RecentDataSourceRow row in config.RecentDataSources)
{
cmbRecentSources.Items.Add(new ComboBoxItem(row.DataProvider, row.Name, row.ConnectionString));
}
}
cmbRecentSources.SelectedIndex = 0;
}
finally
{
ignoreDataFormatIndexChange = false;
}
}
private void OpenSelectProjectDialog()
{
try
{
Project oldSelectedProject = this.selectedProject;
Project newSelectedProject = base.SelectProject();
if (newSelectedProject != null)
{
this.selectedProject = newSelectedProject;
if (oldSelectedProject != newSelectedProject)
{
SetDataSourceToSelectedProject();
}
this.RefreshForm();
}
}
catch (Exception ex)
{
MsgBox.ShowException(ex);
}
}
private void SetDataSourceToSelectedProject()
{
this.selectedDataSource = selectedProject;
this.cmbDataSourcePlugIns.SelectedIndex = 0;
}
private void OpenSelectDataSourceDialog()
{
bool formNeedsRefresh = false;
ComboBoxItem selectedPlugIn = cmbDataSourcePlugIns.SelectedItem as ComboBoxItem;
if (selectedPlugIn == null)
{
throw new GeneralException("No data source plug-in is selected in combo box.");
}
if (selectedPlugIn.Key == null)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Title = SharedStrings.SELECT_DATA_SOURCE;
openFileDialog.Filter = "Epi Info " + SharedStrings.PROJECT_FILE + " (*.prj)|*.prj";
openFileDialog.InitialDirectory = config.Directories.Project;
openFileDialog.FilterIndex = 1;
openFileDialog.Multiselect = false;
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
string filePath = openFileDialog.FileName.Trim();
if (System.IO.File.Exists(filePath))
{
try
{
selectedDataSource = new Project(filePath);
formNeedsRefresh = true;
}
catch (System.Security.Cryptography.CryptographicException ex)
{
MsgBox.ShowError(string.Format(SharedStrings.ERROR_CRYPTO_KEYS, ex.Message));
return;
}
catch (Exception ex)
{
MsgBox.ShowError(SharedStrings.CANNOT_OPEN_PROJECT_FILE + "\n\nError details: " + ex.Message);
return;
}
}
}
}
else
{
IDbDriverFactory dbFactory = null;
selectedDataProvider = selectedPlugIn.Key;
dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(selectedPlugIn.Key);
if (dbFactory.ArePrerequisitesMet())
{
DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);
IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb();
if (!string.IsNullOrEmpty(savedConnectionStringDescription))
{
int splitIndex = savedConnectionStringDescription.IndexOf("::");
if (splitIndex > -1)
{
string serverName = savedConnectionStringDescription.Substring(0, splitIndex);
string databaseName = savedConnectionStringDescription.Substring(splitIndex + 2, savedConnectionStringDescription.Length - splitIndex - 2);
dialog.SetDatabaseName(databaseName);
dialog.SetServerName(serverName);
}
}
DialogResult result = ((Form)dialog).ShowDialog();
// dialog.UseManagerService
if (result == DialogResult.OK && dialog.DbConnectionStringBuilder!=null)
{
this.savedConnectionStringDescription = dialog.ConnectionStringDescription;
bool success = false;
db.ConnectionString = dialog.DbConnectionStringBuilder.ToString();
try
{
success = db.TestConnection();
}
catch
{
success = false;
MessageBox.Show("Could not connect to selected data source.");
}
if (success)
{
this.selectedDataSource = db;
formNeedsRefresh = true;
}
else
{
this.selectedDataSource = null;
}
}
else
{
if (selectedPlugIn.Text == "Epi Info Web & Cloud Services")
{
}
else
{
this.selectedDataSource = null;
}
}
}
else
{
MessageBox.Show(dbFactory.PrerequisiteMessage, "Prerequisites not found");
}
}
if (formNeedsRefresh)
{
RefreshForm();
}
}
#endregion Private Methods
#region Protected Methods
/// <summary>
/// Validates input
/// </summary>
/// <returns>true if validation passes; else false</returns>
protected override bool ValidateInput()
{
base.ValidateInput ();
if (cmbDataSourcePlugIns.SelectedIndex == -1)
{
ErrorMessages.Add(SharedStrings.SPECIFY_DATAFORMAT);
}
if (string.IsNullOrEmpty(txtDataSource.Text))
{
ErrorMessages.Add(SharedStrings.SPECIFY_DATASOURCE);
}
if (this.lvDataSourceObjects.SelectedIndices.Count == 0 && string.IsNullOrEmpty(SQLQuery))
{
ErrorMessages.Add(SharedStrings.SPECIFY_TABLE_OR_VIEW);
}
return (ErrorMessages.Count == 0);
}
/// <summary>
/// Generate the Read command
/// </summary>
protected void GenerateCommand()
{
if (!(cmbDataSourcePlugIns.SelectedItem.ToString().Equals("Epi Info 7 Project")))
{
selectedProject = null;
}
}
public object SelectedDataSource
{
get
{
return selectedDataSource;
}
}
public string SQLQuery
{
get
{
return this.sqlQuery;
}
set
{
this.sqlQuery = value;
}
}
public string SelectedDataMember
{
get
{
if (string.IsNullOrEmpty(SQLQuery) && lvDataSourceObjects.SelectedItems.Count > 0)
{
return lvDataSourceObjects.SelectedItems[0].Text;
}
else
{
return SQLQuery;
}
}
}
public bool IsFormSelected
{
get
{
ListViewGroup tables = lvDataSourceObjects.Groups["Tables"];
ListViewGroup forms = lvDataSourceObjects.Groups["Forms"];
if (lvDataSourceObjects.SelectedItems[0].Group.Equals(tables))
{
return false;
}
else if (lvDataSourceObjects.SelectedItems[0].Group.Equals(forms))
{
return true;
}
return false;
}
}
public string SelectedDataProvider
{
get
{
return selectedDataProvider;
}
}
/// <summary>
/// Before executing the command, preprocesses information gathered from the dialog.
/// If the current project has changed, updates Global.CurrentProject
/// </summary>
protected void PreProcess()
{
//base.PreProcess();
// dcs0 8/13/2008 the below doesn't seem necessary, the command processor should do all of this
//IProjectHost host = Module.GetService(typeof(IProjectHost)) as IProjectHost;
//if (host == null)
//{
// throw new GeneralException("No project is hosted by service provider.");
//}
//if ((host.CurrentProject == null) || (!host.CurrentProject.Equals(this.selectedProject)))
//{
// Configuration config = Configuration.GetNewInstance();
// host.CurrentProject = this.selectedProject;
// config.CurrentProjectFilePath = selectedProject.FullName;
// Configuration.Save(config);
//}
// add to the config
string name = string.Empty;
string connectionString = string.Empty;
string dataProvider = string.Empty;
if (SelectedDataSource is IDbDriver)
{
IDbDriver db = selectedDataSource as IDbDriver;
name = db.DbName;
connectionString = db.ConnectionString;
dataProvider = SelectedDataProvider;
}
else if (SelectedDataSource is Project)
{
Project project = selectedDataSource as Project;
name = project.FileName;
connectionString = project.FilePath;
dataProvider = project.CollectedDataDriver;
}
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(connectionString))
{
Configuration.OnDataSourceAccessed(name, Configuration.Encrypt(connectionString), dataProvider);
}
}
/// <summary>
/// Checks if the input provided is sufficient and enables control buttons accordingly.
/// </summary>
public override void CheckForInputSufficiency()
{
bool inputValid = ValidateInput();
btnOK.Enabled = inputValid;
if (this.SelectedDataSource is IDbDriver)
{
btnAdvanced.Enabled = true;
}
else
{
btnAdvanced.Enabled = false;
}
}
#endregion Protected Methods
#region Event Handlers
private void ReadDialog_Load(object sender, System.EventArgs e)
{
LoadForm();
}
private void btnFindProject_Click(object sender, System.EventArgs e)
{
OpenSelectProjectDialog();
}
private void cmbDataSourcePlugIns_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (ignoreDataFormatIndexChange) return;
ComboBox CB = (ComboBox) sender;
if (CB.SelectedIndex == 0)
{
chkViews.Enabled = true;
chkTables.Enabled = true;
}
else
{
chkViews.Enabled = false;
chkTables.Enabled = false;
chkViews.Checked = true;
chkTables.Checked = true;
}
this.selectedDataSource = null;
// TODO: Review this code. Select known database driver from configuration or prj file
this.RefreshForm();
}
private void btnClear_Click(object sender, System.EventArgs e)
{
lvDataSourceObjects.SelectedItems.Clear(); //.SelectedIndex = -1;
SetDataSourceToSelectedProject();
}
private void txtCurrentProj_TextChanged(object sender, System.EventArgs e)
{
CheckForInputSufficiency();
}
private void txtDataSource_TextChanged(object sender, System.EventArgs e)
{
CheckForInputSufficiency();
}
private void btnFindDataSource_Click(object sender, System.EventArgs e)
{
OpenSelectDataSourceDialog();
}
private void lvDataSourceObjects_SelectedIndexChanged(object sender, System.EventArgs e)
{
CheckForInputSufficiency();
}
private void lvDataSourceObjects_DataSourceChanged(object sender, System.EventArgs e)
{
if (lvDataSourceObjects.Items.Count > 0)
{
lvDataSourceObjects.SelectedIndices.Clear();
}
}
private void lvDataSourceObjects_Resize(object sender, EventArgs e)
{
// leave space for scroll bar
this.lvDataSourceObjects.Columns[0].Width = this.lvDataSourceObjects.Width - 25;
}
private void lvDataSourceObjects_DoubleClick(object sender, EventArgs e)
{
if (this.btnOK.Enabled)
{
OnOK();
}
}
private void OnOK()
{
if (ValidateInput() == true)
{
GenerateCommand();
PreProcess();
this.DialogResult = DialogResult.OK;
this.Hide();
}
else
{
this.DialogResult = DialogResult.None;
ShowErrorMessages();
}
}
private void CheckBox_CheckedChanged(object sender, EventArgs e)
{
if (!(chkViews.Checked) && !(chkTables.Checked))
{
chkViews.Checked = true;
}
RefreshForm();
}
#endregion Event Handlers
private void cmbRecentSources_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
//this.RefreshForm();
if (cmbRecentSources.SelectedItem != null && !string.IsNullOrEmpty(cmbRecentSources.SelectedItem.ToString()))
{
string connectionString = Configuration.Decrypt(((ComboBoxItem)cmbRecentSources.SelectedItem).Value.ToString());
string name = ((ComboBoxItem)cmbRecentSources.SelectedItem).Text.ToString();
string provider = ((ComboBoxItem)cmbRecentSources.SelectedItem).Key.ToString();
mruSelectedDatabaseName = name;
selectedDataProvider = provider;
if (name.ToLowerInvariant().EndsWith(".prj"))
{
Project project = new Project(connectionString);
try
{
project.CollectedData.TestConnection();
}
catch (Exception ex)
{
Epi.Windows.MsgBox.ShowException(ex);
return;
}
this.selectedDataSource = project;
this.selectedProject = project;
}
else
{
IDbDriverFactory dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(provider);
if (dbFactory.ArePrerequisitesMet())
{
DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder();
IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder);
db.ConnectionString = connectionString;
try
{
db.TestConnection();
}
catch (Exception ex)
{
Epi.Windows.MsgBox.ShowException(ex);
return;
}
this.selectedDataSource = db;
}
}
}
else if (cmbRecentSources.SelectedItem != null && string.IsNullOrEmpty(cmbRecentSources.SelectedItem.ToString()))
{
mruSelectedDatabaseName = string.Empty;
}
RefreshForm();
}
catch (System.IO.DirectoryNotFoundException ex)
{
MsgBox.ShowException(ex);
mruSelectedDatabaseName = string.Empty;
cmbRecentSources.SelectedIndex = -1;
}
catch (System.IO.FileNotFoundException ex)
{
MsgBox.ShowException(ex);
mruSelectedDatabaseName = string.Empty;
cmbRecentSources.SelectedIndex = -1;
}
catch (Exception ex)
{
MsgBox.ShowException(ex);
mruSelectedDatabaseName = string.Empty;
cmbRecentSources.SelectedIndex = -1;
}
}
private void btnAdvanced_Click(object sender, EventArgs e)
{
if (SelectedDataSource is IDbDriver)
{
AdvancedReadDialog advReadDialog = new AdvancedReadDialog(this.SelectedDataSource as IDbDriver);
advReadDialog.SQLQuery = this.SQLQuery;
DialogResult result = advReadDialog.ShowDialog();
if (result == DialogResult.OK)
{
sqlQuery = advReadDialog.SQLQuery;
OnOK();
}
else
{
this.DialogResult = System.Windows.Forms.DialogResult.None;
}
}
}
/// <summary>
/// Opens a process to show the related help topic
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected override void btnHelp_Click(object sender, System.EventArgs e)
{
try
{
if (module != null)
{
string key = module.ToString();
if (key.Contains("Text: Map"))
{
System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/maps/introduction.html");
}
else
if (key.Contains("Text: Dashboard"))
{
System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/visual-dashboard/VisualDashboardIntro.html");
}
else
if (key.Contains("Text: Table-to-Form"))
{
System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/form-designer/how-to-make-form-from-table.html");
}
else
{
System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/support/userguide.html");
}
}
}
catch
{
}
}
}
}
| |
// 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.Xml;
using System.Xml.Linq;
using Microsoft.Test.ModuleCore;
using Xunit;
namespace CoreXml.Test.XLinq
{
public partial class XNodeReaderFunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
//[TestCase(Name = "ReadState", Desc = "ReadState")]
public partial class TCReadState : BridgeHelpers
{
//[Variation("XmlReader ReadState Initial", Priority = 0)]
public void ReadState1()
{
XDocument doc = new XDocument();
XmlReader r = doc.CreateReader();
if (r.ReadState != ReadState.Initial)
throw new TestFailedException("");
}
//[Variation("XmlReader ReadState Interactive", Priority = 0)]
public void ReadState2()
{
XDocument doc = XDocument.Parse("<a/>");
XmlReader r = doc.CreateReader();
while (r.Read())
{
if (r.ReadState != ReadState.Interactive)
throw new TestFailedException("");
else
return;
}
if (r.ReadState != ReadState.EndOfFile)
throw new TestFailedException("");
}
//[Variation("XmlReader ReadState EndOfFile", Priority = 0)]
public void ReadState3()
{
XDocument doc = new XDocument();
XmlReader r = doc.CreateReader();
while (r.Read()) { };
if (r.ReadState != ReadState.EndOfFile)
throw new TestFailedException("");
}
//[Variation("XmlReader ReadState Initial", Priority = 0)]
public void ReadState4()
{
XDocument doc = XDocument.Parse("<a/>");
XmlReader r = doc.CreateReader();
try
{
r.ReadContentAsInt();
}
catch (InvalidOperationException) { }
if (r.ReadState != ReadState.Initial)
throw new TestFailedException("");
}
//[Variation("XmlReader ReadState EndOfFile", Priority = 0)]
public void ReadState5()
{
XDocument doc = XDocument.Parse("<a/>");
XmlReader r = doc.CreateReader();
while (r.Read()) { };
try
{
r.ReadContentAsInt();
}
catch (InvalidOperationException) { }
if (r.ReadState != ReadState.EndOfFile)
throw new TestFailedException("");
}
}
//[TestCase(Name = "ReadInnerXml", Desc = "ReadInnerXml")]
public partial class TCReadInnerXml : BridgeHelpers
{
void VerifyNextNode(XmlReader DataReader, XmlNodeType nt, string name, string value)
{
while (DataReader.NodeType == XmlNodeType.Whitespace ||
DataReader.NodeType == XmlNodeType.SignificantWhitespace)
{
// skip all whitespace nodes
// if EOF is reached NodeType=None
DataReader.Read();
}
TestLog.Compare(VerifyNode(DataReader, nt, name, value), "VerifyNextNode");
}
//[Variation("ReadInnerXml on Empty Tag", Priority = 0)]
public void TestReadInnerXml1()
{
bool bPassed = false;
String strExpected = String.Empty;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY1");
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on non Empty Tag", Priority = 0)]
public void TestReadInnerXml2()
{
bool bPassed = false;
String strExpected = String.Empty;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "EMPTY2");
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on non Empty Tag with text content", Priority = 0)]
public void TestReadInnerXml3()
{
bool bPassed = false;
String strExpected = "ABCDE";
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONEMPTY1");
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml with multiple Level of elements")]
public void TestReadInnerXml6()
{
bool bPassed = false;
String strExpected;
strExpected = "<ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 />";
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "SKIP3");
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
VerifyNextNode(DataReader, XmlNodeType.Element, "AFTERSKIP3", String.Empty);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml with multiple Level of elements, text and attributes", Priority = 0)]
public void TestReadInnerXml7()
{
bool bPassed = false;
String strExpected = "<e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1>";
strExpected = strExpected.Replace('\'', '"');
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "CONTENT");
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml with entity references, EntityHandling = ExpandEntities")]
public void TestReadInnerXml8()
{
bool bPassed = false;
String strExpected = ST_EXPAND_ENTITIES2;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_ENTTEST_NAME);
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
VerifyNextNode(DataReader, XmlNodeType.Element, "ENTITY2", String.Empty);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on attribute node", Priority = 0)]
public void TestReadInnerXml9()
{
bool bPassed = false;
String strExpected = "a1value";
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "ATTRIBUTE2");
bPassed = DataReader.MoveToFirstAttribute();
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
VerifyNextNode(DataReader, XmlNodeType.Attribute, "a1", strExpected);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on attribute node with entity reference in value", Priority = 0)]
public void TestReadInnerXml10()
{
bool bPassed = false;
string strExpected = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES4;
string strExpectedAttValue = ST_ENT1_ATT_EXPAND_ENTITIES;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_ENTTEST_NAME);
bPassed = DataReader.MoveToFirstAttribute();
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
VerifyNextNode(DataReader, XmlNodeType.Attribute, "att1", strExpectedAttValue);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on Text", Priority = 0)]
public void TestReadInnerXml11()
{
XmlNodeType nt;
string name;
string value;
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Text);
TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc);
// save status and compare with Read
nt = DataReader.NodeType;
name = DataReader.Name;
value = DataReader.Value;
DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Text);
DataReader.Read();
TestLog.Compare(VerifyNode(DataReader, nt, name, value), "vn");
}
//[Variation("ReadInnerXml on CDATA")]
public void TestReadInnerXml12()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.CDATA))
{
TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc);
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadInnerXml on ProcessingInstruction")]
public void TestReadInnerXml13()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.ProcessingInstruction))
{
TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc);
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadInnerXml on Comment")]
public void TestReadInnerXml14()
{
XmlReader DataReader = GetReader();
if (FindNodeType(DataReader, XmlNodeType.Comment))
{
TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc);
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadInnerXml on EndElement")]
public void TestReadInnerXml16()
{
XmlReader DataReader = GetReader();
FindNodeType(DataReader, XmlNodeType.EndElement);
TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc);
}
//[Variation("ReadInnerXml on XmlDeclaration")]
public void TestReadInnerXml17()
{
XmlReader DataReader = GetReader();
TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc);
}
//[Variation("Current node after ReadInnerXml on element", Priority = 0)]
public void TestReadInnerXml18()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "SKIP2");
DataReader.ReadInnerXml();
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "AFTERSKIP2", String.Empty), true, "VN");
}
//[Variation("Current node after ReadInnerXml on element")]
public void TestReadInnerXml19()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "MARKUP");
TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, "RIX");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Text, String.Empty, "yyy"), true, "VN");
}
//[Variation("ReadInnerXml with entity references, EntityHandling = ExpandCharEntites")]
public void TestTextReadInnerXml2()
{
bool bPassed = false;
String strExpected = ST_EXPAND_ENTITIES2;
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_ENTTEST_NAME);
bPassed = TestLog.Equals(DataReader.ReadInnerXml(), strExpected, Variation.Desc);
BoolToLTMResult(bPassed);
}
//[Variation("ReadInnerXml on EntityReference")]
public void TestTextReadInnerXml4()
{
XmlReader DataReader = GetReader();
TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc);
}
//[Variation("ReadInnerXml on EndEntity")]
public void TestTextReadInnerXml5()
{
XmlReader DataReader = GetReader();
TestLog.Compare(DataReader.ReadInnerXml(), String.Empty, Variation.Desc);
}
//[Variation("One large element")]
public void TestTextReadInnerXml18()
{
String strp = "a ";
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
string strxml = "<Name a=\"b\">" + strp + "</Name>";
XmlReader DataReader = GetReaderStr(strxml);
DataReader.Read();
TestLog.Compare(DataReader.ReadInnerXml(), strp, "rix");
}
}
//[TestCase(Name = "MoveToContent", Desc = "MoveToContent")]
public partial class TCMoveToContent : BridgeHelpers
{
public const String ST_TEST_NAME1 = "GOTOCONTENT";
public const String ST_TEST_NAME2 = "SKIPCONTENT";
public const String ST_TEST_NAME3 = "MIXCONTENT";
public const String ST_TEST_TEXT = "some text";
public const String ST_TEST_CDATA = "cdata info";
//[Variation("MoveToContent on Skip XmlDeclaration", Priority = 0)]
public void TestMoveToContent1()
{
XmlReader DataReader = GetReader();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc);
TestLog.Compare(DataReader.Name, "PLAY", Variation.Desc);
}
//[Variation("MoveToContent on Read through All valid Content Node(Element, Text, CDATA, and EndElement)", Priority = 0)]
public void TestMoveToContent2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_NAME1);
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc);
TestLog.Compare(DataReader.Name, ST_TEST_NAME1, "Element name");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text");
TestLog.Compare(DataReader.ReadContentAsString(), ST_TEST_TEXT + ST_TEST_CDATA, "Read String");
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.EndElement, "Move to EndElement");
TestLog.Compare(DataReader.Name, ST_TEST_NAME1, "EndElement value");
}
//[Variation("MoveToContent on Read through All invalid Content Node(PI, Comment and whitespace)", Priority = 0)]
public void TestMoveToContent3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_NAME2);
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc);
TestLog.Compare(DataReader.Name, ST_TEST_NAME2, "Element name");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text");
TestLog.Compare(DataReader.Name, "", "EndElement value");
}
//[Variation("MoveToContent on Read through Mix valid and Invalid Content Node")]
public void TestMoveToContent4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_NAME3);
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, Variation.Desc);
TestLog.Compare(DataReader.Name, ST_TEST_NAME3, "Element name");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Text, "Move to Text");
TestLog.Compare(DataReader.Value, ST_TEST_TEXT, "text value");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.CDATA, "Move to CDATA");
TestLog.Compare(DataReader.Name, "", "CDATA value");
DataReader.Read();
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.EndElement, "Move to EndElement");
TestLog.Compare(DataReader.Name, ST_TEST_NAME3, "EndElement value");
}
//[Variation("MoveToContent on Attribute", Priority = 0)]
public void TestMoveToContent5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_NAME1);
PositionOnNodeType(DataReader, XmlNodeType.Attribute);
TestLog.Compare(DataReader.MoveToContent(), XmlNodeType.Element, "Move to EndElement");
TestLog.Compare(DataReader.Name, ST_TEST_NAME2, "EndElement value");
}
}
//[TestCase(Name = "IsStartElement", Desc = "IsStartElement")]
public partial class TCIsStartElement : BridgeHelpers
{
private const String ST_TEST_ELEM = "DOCNAMESPACE";
private const String ST_TEST_EMPTY_ELEM = "NOSPACE";
private const String ST_TEST_ELEM_NS = "NAMESPACE1";
private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1";
//[Variation("IsStartElement on Regular Element, no namespace", Priority = 0)]
public void TestIsStartElement1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_ELEM), true, "IsStartElement(n)");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_ELEM, String.Empty), true, "IsStartElement(n,ns)");
}
//[Variation("IsStartElement on Empty Element, no namespace", Priority = 0)]
public void TestIsStartElement2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM), true, "IsStartElement(n)");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM, String.Empty), true, "IsStartElement(n,ns)");
}
//[Variation("IsStartElement on regular Element, with namespace", Priority = 0)]
public void TestIsStartElement3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement("check", "1"), true, "IsStartElement(n,ns)");
TestLog.Compare(DataReader.IsStartElement("check", String.Empty), false, "IsStartElement(n)");
TestLog.Compare(DataReader.IsStartElement("check"), false, "IsStartElement2(n)");
TestLog.Compare(DataReader.IsStartElement("bar:check"), true, "IsStartElement(qname)");
TestLog.Compare(DataReader.IsStartElement("bar1:check"), false, "IsStartElement(invalid_qname)");
}
//[Variation("IsStartElement on Empty Tag, with default namespace", Priority = 0)]
public void TestIsStartElement4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
TestLog.Compare(DataReader.IsStartElement(), true, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS, "14"), true, "IsStartElement(n,ns)");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS, String.Empty), false, "IsStartElement(n)");
TestLog.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS), true, "IsStartElement2(n)");
}
//[Variation("IsStartElement with Name=String.Empty")]
public void TestIsStartElement5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
TestLog.Compare(DataReader.IsStartElement(String.Empty), false, Variation.Desc);
}
//[Variation("IsStartElement on Empty Element with Name and Namespace=String.Empty")]
public void TestIsStartElement6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
TestLog.Compare(DataReader.IsStartElement(String.Empty, String.Empty), false, Variation.Desc);
}
//[Variation("IsStartElement on CDATA")]
public void TestIsStartElement7()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.CDATA);
TestLog.Compare(DataReader.IsStartElement(), false, Variation.Desc);
}
//[Variation("IsStartElement on EndElement, no namespace")]
public void TestIsStartElement8()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONAMESPACE");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
TestLog.Compare(DataReader.IsStartElement(), false, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement("NONAMESPACE"), false, "IsStartElement(n)");
TestLog.Compare(DataReader.IsStartElement("NONAMESPACE", String.Empty), false, "IsStartElement(n,ns)");
}
//[Variation("IsStartElement on EndElement, with namespace")]
public void TestIsStartElement9()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
TestLog.Compare(DataReader.IsStartElement(), false, "IsStartElement()");
TestLog.Compare(DataReader.IsStartElement("check", "1"), false, "IsStartElement(n,ns)");
TestLog.Compare(DataReader.IsStartElement("bar:check"), false, "IsStartElement(qname)");
}
//[Variation("IsStartElement on Attribute")]
public void TestIsStartElement10()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Attribute);
TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc);
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, Variation.Desc);
}
//[Variation("IsStartElement on Text")]
public void TestIsStartElement11()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Text);
TestLog.Compare(DataReader.IsStartElement(), false, Variation.Desc);
}
//[Variation("IsStartElement on ProcessingInstruction")]
public void TestIsStartElement12()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.ProcessingInstruction);
TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc);
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, Variation.Desc);
}
//[Variation("IsStartElement on Comment")]
public void TestIsStartElement13()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Comment);
TestLog.Compare(DataReader.IsStartElement(), true, Variation.Desc);
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, Variation.Desc);
}
}
//[TestCase(Name = "ReadStartElement", Desc = "ReadStartElement")]
public partial class TCReadStartElement : BridgeHelpers
{
private const String ST_TEST_ELEM = "DOCNAMESPACE";
private const String ST_TEST_EMPTY_ELEM = "NOSPACE";
private const String ST_TEST_ELEM_NS = "NAMESPACE1";
private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1";
//[Variation("ReadStartElement on Regular Element, no namespace", Priority = 0)]
public void TestReadStartElement1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
DataReader.ReadStartElement();
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
DataReader.ReadStartElement(ST_TEST_ELEM);
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
DataReader.ReadStartElement(ST_TEST_ELEM, String.Empty);
}
//[Variation("ReadStartElement on Empty Element, no namespace", Priority = 0)]
public void TestReadStartElement2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
DataReader.ReadStartElement();
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM);
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM, String.Empty);
}
//[Variation("ReadStartElement on regular Element, with namespace", Priority = 0)]
public void TestReadStartElement3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
DataReader.ReadStartElement();
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
DataReader.ReadStartElement("check", "1");
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
DataReader.ReadStartElement("bar:check");
}
//[Variation("Passing ns=String.EmptyErrorCase: ReadStartElement on regular Element, with namespace", Priority = 0)]
public void TestReadStartElement4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
try
{
DataReader.ReadStartElement("check", String.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("Passing no ns: ReadStartElement on regular Element, with namespace", Priority = 0)]
public void TestReadStartElement5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
try
{
DataReader.ReadStartElement("check");
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement on Empty Tag, with namespace")]
public void TestReadStartElement6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
DataReader.ReadStartElement();
DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS, "14");
}
//[Variation("ErrorCase: ReadStartElement on Empty Tag, with namespace, passing ns=String.Empty")]
public void TestReadStartElement7()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
try
{
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS, String.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement on Empty Tag, with namespace, passing no ns")]
public void TestReadStartElement8()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS);
}
//[Variation("ReadStartElement with Name=String.Empty")]
public void TestReadStartElement9()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
try
{
DataReader.ReadStartElement(String.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement on Empty Element with Name and Namespace=String.Empty")]
public void TestReadStartElement10()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
try
{
DataReader.ReadStartElement(String.Empty, String.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement on CDATA")]
public void TestReadStartElement11()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.CDATA);
try
{
DataReader.ReadStartElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement() on EndElement, no namespace")]
public void TestReadStartElement12()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONAMESPACE");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement(n) on EndElement, no namespace")]
public void TestReadStartElement13()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONAMESPACE");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement("NONAMESPACE");
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement(n, String.Empty) on EndElement, no namespace")]
public void TestReadStartElement14()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "NONAMESPACE");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement("NONAMESPACE", String.Empty);
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement() on EndElement, with namespace")]
public void TestReadStartElement15()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadStartElement(n,ns) on EndElement, with namespace")]
public void TestReadStartElement16()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
try
{
DataReader.ReadStartElement("check", "1");
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
}
//[TestCase(Name = "ReadEndElement", Desc = "ReadEndElement")]
public partial class TCReadEndElement : BridgeHelpers
{
private const String ST_TEST_ELEM = "DOCNAMESPACE";
private const String ST_TEST_EMPTY_ELEM = "NOSPACE";
private const String ST_TEST_ELEM_NS = "NAMESPACE1";
private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1";
[Fact]
public void TestReadEndElementOnEndElementWithoutNamespace()
{
using (XmlReader DataReader = GetPGenericXmlReader())
{
PositionOnElement(DataReader, "NONAMESPACE");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
Assert.True(VerifyNode(DataReader, XmlNodeType.EndElement, "NONAMESPACE", String.Empty));
}
}
[Fact]
public void TestReadEndElementOnEndElementWithNamespace()
{
using (XmlReader DataReader = GetPGenericXmlReader())
{
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
PositionOnNodeType(DataReader, XmlNodeType.EndElement);
Assert.True(VerifyNode(DataReader, XmlNodeType.EndElement, "bar:check", String.Empty));
}
}
//[Variation("ReadEndElement on Start Element, no namespace")]
public void TestReadEndElement3()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on Empty Element, no namespace", Priority = 0)]
public void TestReadEndElement4()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on regular Element, with namespace", Priority = 0)]
public void TestReadEndElement5()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_ELEM_NS);
PositionOnElement(DataReader, "bar:check");
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on Empty Tag, with namespace", Priority = 0)]
public void TestReadEndElement6()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, ST_TEST_EMPTY_ELEM_NS);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on CDATA")]
public void TestReadEndElement7()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.CDATA);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on Text")]
public void TestReadEndElement9()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Text);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on ProcessingInstruction")]
public void TestReadEndElement10()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.ProcessingInstruction);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on Comment")]
public void TestReadEndElement11()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Comment);
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on XmlDeclaration")]
public void TestReadEndElement13()
{
XmlReader DataReader = GetReader();
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on EntityReference")]
public void TestTextReadEndElement1()
{
XmlReader DataReader = GetReader();
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadEndElement on EndEntity")]
public void TestTextReadEndElement2()
{
XmlReader DataReader = GetReader();
try
{
DataReader.ReadEndElement();
}
catch (XmlException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
}
public partial class TCMoveToElement : BridgeHelpers
{
//[Variation("Attribute node")]
public void v1()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "elem2");
DataReader.MoveToAttribute(1);
TestLog.Compare(DataReader.MoveToElement(), "MTE on elem2 failed");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "elem2", String.Empty), "MTE moved on wrong node");
}
//[Variation("Element node")]
public void v2()
{
XmlReader DataReader = GetReader();
PositionOnElement(DataReader, "elem2");
TestLog.Compare(!DataReader.MoveToElement(), "MTE on elem2 failed");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "elem2", String.Empty), "MTE moved on wrong node");
}
//[Variation("Comment node")]
public void v5()
{
XmlReader DataReader = GetReader();
PositionOnNodeType(DataReader, XmlNodeType.Comment);
TestLog.Compare(!DataReader.MoveToElement(), "MTE on comment failed");
TestLog.Compare(DataReader.NodeType, XmlNodeType.Comment, "comment");
}
}
}
}
}
| |
//
// TreeViews.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
using Xwt.Drawing;
namespace Samples
{
public class TreeViews: VBox
{
DataField<CheckBoxState> triState = new DataField<CheckBoxState>();
DataField<bool> check = new DataField<bool>();
DataField<bool> option1 = new DataField<bool> ();
DataField<bool> option2 = new DataField<bool> ();
DataField<bool> option3 = new DataField<bool> ();
DataField<string> text = new DataField<string> ();
DataField<string> desc = new DataField<string> ();
public TreeViews ()
{
TreeView view = new TreeView ();
TreeStore store = new TreeStore (triState, check, option1, option2, option3, text, desc);
view.GridLinesVisible = GridLines.Both;
var triStateCellView = new CheckBoxCellView (triState) { Editable = true, AllowMixed = true };
triStateCellView.Toggled += (object sender, WidgetEventArgs e) => {
if (view.CurrentEventRow == null) {
MessageDialog.ShowError("CurrentEventRow is null. This is not supposed to happen");
}
else {
store.GetNavigatorAt(view.CurrentEventRow).SetValue(text, "TriState Toggled");
}
};
var checkCellView = new CheckBoxCellView (check) { Editable = true };
checkCellView.Toggled += (object sender, WidgetEventArgs e) => {
if (view.CurrentEventRow == null) {
MessageDialog.ShowError("CurrentEventRow is null. This is not supposed to happen");
}
else {
store.GetNavigatorAt(view.CurrentEventRow).SetValue(text, "Toggled " + checkCellView.Active);
}
};
var optionCellView1 = new RadioButtonCellView (option1) { Editable = true };
optionCellView1.Toggled += (object sender, WidgetEventArgs e) => {
if (view.CurrentEventRow == null) {
MessageDialog.ShowError ("CurrentEventRow is null. This is not supposed to happen");
} else {
store.GetNavigatorAt (view.CurrentEventRow).SetValue (option2, optionCellView1.Active);
}
};
var optionCellView2 = new RadioButtonCellView (option2) { Editable = true };
optionCellView2.Toggled += (object sender, WidgetEventArgs e) => {
if (view.CurrentEventRow == null) {
MessageDialog.ShowError ("CurrentEventRow is null. This is not supposed to happen");
} else {
store.GetNavigatorAt (view.CurrentEventRow).SetValue (option1, optionCellView2.Active);
}
};
TreePosition initialActive = null;
var optionCellView3 = new RadioButtonCellView (option3) { Editable = true };
optionCellView3.Toggled += (object sender, WidgetEventArgs e) => {
if (view.CurrentEventRow == null) {
MessageDialog.ShowError ("CurrentEventRow is null. This is not supposed to happen");
} else {
if (initialActive != null)
store.GetNavigatorAt (initialActive).SetValue (option3, false);
initialActive = view.CurrentEventRow;
}
};
view.Columns.Add ("TriCheck", triStateCellView);
view.Columns.Add ("Check", checkCellView);
view.Columns.Add ("Radio", optionCellView1, optionCellView2, optionCellView3);
view.Columns.Add ("Item", text);
view.Columns.Add ("Desc", desc);
view.Columns[2].Expands = true; // expand third column, aligning last column to the right side
view.Columns[2].CanResize = true;
view.Columns[3].CanResize = true;
store.AddNode ().SetValue (text, "One").SetValue (desc, "First").SetValue (triState, CheckBoxState.Mixed);
store.AddNode ().SetValue (text, "Two").SetValue (desc, "Second").AddChild ()
.SetValue (text, "Sub two").SetValue (desc, "Sub second");
store.AddNode ().SetValue (text, "Three").SetValue (desc, "Third").AddChild ()
.SetValue (text, "Sub three").SetValue (desc, "Sub third");
PackStart (view, true);
Menu contextMenu = new Menu ();
contextMenu.Items.Add (new MenuItem ("Test menu"));
view.ButtonPressed += delegate(object sender, ButtonEventArgs e) {
TreePosition tmpTreePos;
RowDropPosition tmpRowDrop;
if ((e.Button == PointerButton.Right) && view.GetDropTargetRow (e.X, e.Y, out tmpRowDrop, out tmpTreePos)) {
// Set actual row to selected
view.SelectRow (tmpTreePos);
contextMenu.Popup(view, e.X, e.Y);
}
};
view.DataSource = store;
Label la = new Label ();
PackStart (la);
view.SetDragDropTarget (DragDropAction.All, TransferDataType.Text);
view.SetDragSource (DragDropAction.All, TransferDataType.Text);
view.DragDrop += delegate(object sender, DragEventArgs e) {
TreePosition node;
RowDropPosition pos;
view.GetDropTargetRow (e.Position.X, e.Position.Y, out pos, out node);
var nav = store.GetNavigatorAt (node);
la.Text += "Dropped \"" + e.Data.Text + "\" into \"" + nav.GetValue (text) + "\" " + pos + "\n";
e.Success = true;
};
view.DragOver += delegate(object sender, DragOverEventArgs e) {
TreePosition node;
RowDropPosition pos;
view.GetDropTargetRow (e.Position.X, e.Position.Y, out pos, out node);
if (pos == RowDropPosition.Into)
e.AllowedAction = DragDropAction.None;
else
e.AllowedAction = e.Action;
};
view.DragStarted += delegate(object sender, DragStartedEventArgs e) {
var val = store.GetNavigatorAt (view.SelectedRow).GetValue (text);
e.DragOperation.Data.AddValue (val);
var img = Image.FromResource(GetType(), "class.png");
e.DragOperation.SetDragImage(img, (int)img.Size.Width, (int)img.Size.Height);
e.DragOperation.Finished += delegate(object s, DragFinishedEventArgs args) {
Console.WriteLine ("D:" + args.DeleteSource);
};
};
view.RowExpanding += delegate(object sender, TreeViewRowEventArgs e) {
var val = store.GetNavigatorAt (e.Position).GetValue (text);
Console.WriteLine("Expanding: " + val);
};
view.RowExpanded += delegate(object sender, TreeViewRowEventArgs e) {
var val = store.GetNavigatorAt (e.Position).GetValue (text);
Console.WriteLine("Expanded: " + val);
};
view.RowCollapsing += delegate(object sender, TreeViewRowEventArgs e) {
var val = store.GetNavigatorAt (e.Position).GetValue (text);
Console.WriteLine("Collapsing: " + val);
};
view.RowCollapsed += delegate(object sender, TreeViewRowEventArgs e) {
var val = store.GetNavigatorAt (e.Position).GetValue (text);
Console.WriteLine("Collapsed: " + val);
};
RadioButtonGroup group = new RadioButtonGroup ();
foreach (SelectionMode mode in Enum.GetValues(typeof (SelectionMode))) {
var radio = new RadioButton (mode.ToString ());
radio.Group = group;
radio.Activated += delegate {
view.SelectionMode = mode;
};
PackStart (radio);
}
int addCounter = 0;
view.KeyPressed += (sender, e) => {
if (e.Key == Key.Insert) {
TreeNavigator n;
if (view.SelectedRow != null)
n = store.InsertNodeAfter (view.SelectedRow).SetValue (text, "Inserted").SetValue (desc, "Desc");
else
n = store.AddNode ().SetValue (text, "Inserted").SetValue (desc, "Desc");
view.ExpandToRow (n.CurrentPosition);
view.ScrollToRow (n.CurrentPosition);
view.UnselectAll ();
view.SelectRow (n.CurrentPosition);
view.FocusedRow = n.CurrentPosition;
}
};
Button addButton = new Button ("Add");
addButton.Clicked += delegate(object sender, EventArgs e) {
addCounter++;
TreeNavigator n;
if (view.SelectedRow != null)
n = store.AddNode (view.SelectedRow).SetValue (text, "Added " + addCounter).SetValue (desc, "Desc");
else
n = store.AddNode ().SetValue (text, "Added " + addCounter).SetValue (desc, "Desc");
view.ExpandToRow (n.CurrentPosition);
view.ScrollToRow (n.CurrentPosition);
view.SelectRow (n.CurrentPosition);
};
PackStart (addButton);
Button removeButton = new Button ("Remove Selection");
removeButton.Clicked += delegate(object sender, EventArgs e) {
foreach (TreePosition row in view.SelectedRows) {
store.GetNavigatorAt (row).Remove ();
}
};
PackStart (removeButton);
Button clearButton = new Button("Clear");
clearButton.Clicked += delegate (object sender, EventArgs e) {
store.Clear();
};
PackStart(clearButton);
var label = new Label ();
PackStart (label);
view.RowExpanded += (sender, e) => label.Text = "Row expanded: " + store.GetNavigatorAt (e.Position).GetValue (text);
view.RowCollapsed += (sender, e) => label.Text = "Row collapsed: " + store.GetNavigatorAt (e.Position).GetValue (text);
}
void HandleDragOver (object sender, DragOverEventArgs e)
{
e.AllowedAction = e.Action;
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.CustomMarshalers;
namespace onlyconnect
{
class win32
{
//win32 functions
public const int GW_HWNDFIRST = 0;
public const int GW_HWNDLAST = 1;
public const int GW_HWNDNEXT = 2;
public const int GW_HWNDPREV = 3;
public const int GW_OWNER = 4;
public const int GW_CHILD = 5;
public const int GWL_STYLE = -16;
public const int GWL_EXSTYLE = -20;
public const int WM_SETFOCUS = 0x7;
public const int WM_MOUSEACTIVATE = 0x21;
public const int WM_PARENTNOTIFY = 0x210;
public const int WM_ACTIVATE = 0x6;
public const int WM_KILLFOCUS = 0x8;
public const int WM_CLOSE = 0x10;
public const int WM_DESTROY = 0x2;
public const int WM_KEYDOWN = 0x100;
public const int WM_KEYUP = 0x101;
public const int WM_KEYFIRST = 0x0100;
public const int WM_KEYLAST = 0x0109;
public const int WM_LBUTTONDOWN = 0x0201;
public const int WM_LBUTTONUP = 0x0202;
public const int WM_LBUTTONDBLCLK = 0x0203;
public const int WM_NEXTDLGCTL = 0x0028; // see also GetNextDlgTabItem
public const int WM_RBUTTONDOWN = 0x0204;
public const int WM_RBUTTONUP = 0x0205;
public const int WM_RBUTTONDBLCLK = 0x0206;
public const int WM_MBUTTONDOWN = 0x0207;
public const int WM_MBUTTONUP = 0x0208;
public const int WM_MBUTTONDBLCLK = 0x0209;
public const int WM_XBUTTONDOWN = 0x020B;
public const int WM_XBUTTONUP = 0x020C;
public const int WM_MOUSEMOVE = 0x0200;
public const int WM_MOUSELEAVE = 0x02A3;
public const int WM_MOUSEHOVER = 0x02A1;
public const int WS_TABSTOP = 0x00010000;
public const int MK_LBUTTON = 0x0001;
public const int MK_RBUTTON = 0x0002;
public const int MK_SHIFT = 0x0004;
public const int MK_CONTROL = 0x0008;
public const int MK_MBUTTON = 0x0010;
public const int MK_XBUTTON1 = 0x0020;
public const int MK_XBUTTON2 = 0x0040;
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern Boolean GetClientRect(IntPtr hWnd, [In, Out] RECT rect);
[DllImport("User32.dll")]
public static extern int GetMessageTime();
[DllImport("User32.dll")]
public static extern int GetMessagePos();
[DllImport("User32.dll")]
public static extern int GetWindowLong([In] IntPtr hWnd, [In] int nIndex);
[DllImport("User32.dll")]
public static extern IntPtr GetTopWindow([In] IntPtr hWnd);
[DllImport("User32.dll")]
public static extern Boolean IsWindowVisible([In] IntPtr hWnd);
[DllImport("User32.dll")]
public static extern Boolean IsWindowEnabled([In] IntPtr hWnd);
[DllImport("ole32.dll", PreserveSig = false)]
public static extern void CreateStreamOnHGlobal([In] IntPtr hGlobal,
[In] int fDeleteOnRelease, [Out] out IStream pStream);
[DllImport("ole32.dll", PreserveSig = false)]
public static extern void GetHGlobalFromStream(IStream pStream, [Out] out IntPtr pHGlobal);
[DllImport("kernel32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr GlobalLock(IntPtr handle);
[DllImport("kernel32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool GlobalUnlock(IntPtr handle);
[DllImport("ole32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int CreateBindCtx(int dwReserved, [Out] out IBindCtx ppbc);
[DllImport("urlmon.dll", ExactSpelling = true, CharSet = CharSet.Unicode)]
public static extern int CreateURLMoniker(IMoniker pmkContext, String szURL, [Out]
out IMoniker ppmk);
[DllImport("ole32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int OleRun(
[In, MarshalAs(UnmanagedType.IUnknown)] object pUnknown
);
[DllImport("ole32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int OleLockRunning(
[In, MarshalAs(UnmanagedType.IUnknown)] object pUnknown,
[In, MarshalAs(UnmanagedType.Bool)] bool flock,
[In, MarshalAs(UnmanagedType.Bool)] bool fLastUnlockCloses
);
[DllImport("user32.dll")]
public static extern int SendMessage(
IntPtr hWnd, // handle to destination window
uint Msg, // message
int wParam, // first message parameter
int lParam // second message parameter
);
[DllImport("user32.Dll")]
public static extern IntPtr PostMessage(
IntPtr hWnd,
int msg,
int wParam,
int lParam);
[DllImport("user32.Dll")]
public static extern IntPtr GetFocus();
[DllImport("user32.Dll")]
public static extern IntPtr GetWindow([In] IntPtr hWnd, [In] uint wCmd);
[DllImport("user32.dll")]
public static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern short GetKeyState(int nVirtKey);
}
public enum tagOLECLOSE
{
OLECLOSE_SAVEIFDIRTY = 0,
OLECLOSE_NOSAVE = 1,
OLECLOSE_PROMPTSAVE = 2
}
public struct HRESULT
{
public const int S_OK = 0;
public const int S_FALSE = 1;
public const int E_NOTIMPL = unchecked((int)0x80004001);
public const int E_INVALIDARG = unchecked((int)0x80070057);
public const int E_NOINTERFACE = unchecked((int)0x80004002);
public const int E_FAIL = unchecked((int)0x80004005);
public const int E_UNEXPECTED = unchecked((int)0x8000FFFF);
}
struct DOCHOSTUIDBLCLICK
{
public const int DEFAULT = 0x0;
public const int SHOWPROPERTIES = 0x1;
public const int SHOWCODE = 0x2;
}
public enum DOCHOSTUIFLAG
{
DIALOG = 0x00000001,
DISABLE_HELP_MENU = 0x00000002,
NO3DBORDER = 0x00000004,
SCROLL_NO = 0x00000008,
DISABLE_SCRIPT_INACTIVE = 0x00000010,
OPENNEWWIN = 0x00000020,
DISABLE_OFFSCREEN = 0x00000040,
FLAT_SCROLLBAR = 0x00000080,
DIV_BLOCKDEFAULT = 0x00000100,
ACTIVATE_CLIENTHIT_ONLY = 0x00000200,
OVERRIDEBEHAVIORFACTORY = 0x00000400,
CODEPAGELINKEDFONTS = 0x00000800,
URL_ENCODING_DISABLE_UTF8 = 0x00001000,
URL_ENCODING_ENABLE_UTF8 = 0x00002000,
ENABLE_FORMS_AUTOCOMPLETE = 0x00004000,
ENABLE_INPLACE_NAVIGATION = 0x00010000,
IME_ENABLE_RECONVERSION = 0x00020000,
THEME = 0x00040000,
NOTHEME = 0x00080000,
NOPICS = 0x00100000,
NO3DOUTERBORDER = 0x00200000,
//DELEGATESIDOFDISPATCH = 0x00400000,
DISABLE_EDIT_NS_FIXUP = 0x00400000,
LOCAL_MACHINE_ACCESS_CHECK = 0x00800000,
DISABLE_UNTRUSTEDPROTOCOL = 0x01000000
}
public enum ELEMENT_TAG_ID
{ TAGID_NULL = 0,
TAGID_UNKNOWN = 1,
TAGID_A = 2,
TAGID_ACRONYM = 3,
TAGID_ADDRESS = 4,
TAGID_APPLET = 5,
TAGID_AREA = 6,
TAGID_B = 7,
TAGID_BASE = 8,
TAGID_BASEFONT = 9,
TAGID_BDO = 10,
TAGID_BGSOUND = 11,
TAGID_BIG = 12,
TAGID_BLINK = 13,
TAGID_BLOCKQUOTE = 14,
TAGID_BODY = 15,
TAGID_BR = 16,
TAGID_BUTTON = 17,
TAGID_CAPTION = 18,
TAGID_CENTER = 19,
TAGID_CITE = 20,
TAGID_CODE = 21,
TAGID_COL = 22,
TAGID_COLGROUP = 23,
TAGID_COMMENT = 24,
TAGID_COMMENT_RAW = 25,
TAGID_DD = 26,
TAGID_DEL = 27,
TAGID_DFN = 28,
TAGID_DIR = 29,
TAGID_DIV = 30,
TAGID_DL = 31,
TAGID_DT = 32,
TAGID_EM = 33,
TAGID_EMBED = 34,
TAGID_FIELDSET = 35,
TAGID_FONT = 36,
TAGID_FORM = 37,
TAGID_FRAME = 38,
TAGID_FRAMESET = 39,
TAGID_GENERIC = 40,
TAGID_H1 = 41,
TAGID_H2 = 42,
TAGID_H3 = 43,
TAGID_H4 = 44,
TAGID_H5 = 45,
TAGID_H6 = 46,
TAGID_HEAD = 47,
TAGID_HR = 48,
TAGID_HTML = 49,
TAGID_I = 50,
TAGID_IFRAME = 51,
TAGID_IMG = 52,
TAGID_INPUT = 53,
TAGID_INS = 54,
TAGID_KBD = 55,
TAGID_LABEL = 56,
TAGID_LEGEND = 57,
TAGID_LI = 58,
TAGID_LINK = 59,
TAGID_LISTING = 60,
TAGID_MAP = 61,
TAGID_MARQUEE = 62,
TAGID_MENU = 63,
TAGID_META = 64,
TAGID_NEXTID = 65,
TAGID_NOBR = 66,
TAGID_NOEMBED = 67,
TAGID_NOFRAMES = 68,
TAGID_NOSCRIPT = 69,
TAGID_OBJECT = 70,
TAGID_OL = 71,
TAGID_OPTION = 72,
TAGID_P = 73,
TAGID_PARAM = 74,
TAGID_PLAINTEXT = 75,
TAGID_PRE = 76,
TAGID_Q = 77,
TAGID_RP = 78,
TAGID_RT = 79,
TAGID_RUBY = 80,
TAGID_S = 81,
TAGID_SAMP = 82,
TAGID_SCRIPT = 83,
TAGID_SELECT = 84,
TAGID_SMALL = 85,
TAGID_SPAN = 86,
TAGID_STRIKE = 87,
TAGID_STRONG = 88,
TAGID_STYLE = 89,
TAGID_SUB = 90,
TAGID_SUP = 91,
TAGID_TABLE = 92,
TAGID_TBODY = 93,
TAGID_TC = 94,
TAGID_TD = 95,
TAGID_TEXTAREA = 96,
TAGID_TFOOT = 97,
TAGID_TH = 98,
TAGID_THEAD = 99,
TAGID_TITLE = 100,
TAGID_TR = 101,
TAGID_TT = 102,
TAGID_U = 103,
TAGID_UL = 104,
TAGID_VAR = 105,
TAGID_WBR = 106,
TAGID_XMP = 107,
TAGID_ROOT = 108,
TAGID_OPTGROUP = 109,
TAGID_COUNT = 110,
TAGID_LAST_PREDEFINED = 10000,
ELEMENT_TAG_ID_Max = 2147483647
}
public enum SELECTION_TYPE
{
SELECTION_TYPE_None = 0,
SELECTION_TYPE_Caret = 1,
SELECTION_TYPE_Text = 2,
SELECTION_TYPE_Control = 3,
SELECTION_TYPE_Max = 2147483647
}
public enum CARET_DIRECTION
{
CARET_DIRECTION_INDETERMINATE = 0,
CARET_DIRECTION_SAME = 1,
CARET_DIRECTION_BACKWARD = 2,
CARET_DIRECTION_FORWARD = 3,
CARET_DIRECTION_Max = 2147483647
}
public enum COORD_SYSTEM
{
COORD_SYSTEM_GLOBAL = 0,
COORD_SYSTEM_PARENT = 1,
COORD_SYSTEM_CONTAINER = 2,
COORD_SYSTEM_CONTENT = 3,
COORD_SYSTEM_FRAME = 4,
COORD_SYSTEM_Max = 2147483647
}
public enum ELEMENT_CORNER
{
ELEMENT_CORNER_NONE = 0,
ELEMENT_CORNER_TOP = 1,
ELEMENT_CORNER_LEFT = 2,
ELEMENT_CORNER_BOTTOM = 3,
ELEMENT_CORNER_RIGHT = 4,
ELEMENT_CORNER_TOPLEFT = 5,
ELEMENT_CORNER_TOPRIGHT = 6,
ELEMENT_CORNER_BOTTOMLEFT = 7,
ELEMENT_CORNER_BOTTOMRIGHT = 8,
ELEMENT_CORNER_Max = 2147483647
}
public enum OLECMDF : int
{
OLECMDF_SUPPORTED = 1,
OLECMDF_ENABLED = 2,
OLECMDF_LATCHED = 4,
OLECMDF_NINCHED = 8
}
struct WM
{
public const int KEYFIRST = 0x0100;
public const int KEYLAST = 0x0108;
public const int KEYDOWN = 0x0100;
public const int KEYUP = 0x0101;
}
struct OLEIVERB
{
public const int PRIMARY = 0;
public const int SHOW = -1;
public const int OPEN = -2;
public const int HIDE = -3;
public const int UIACTIVATE = -4;
public const int INPLACEACTIVATE = -5;
public const int DISCARDUNDOSTATE = -6;
public const int PROPERTIES = -7;
}
[ComVisible(true), StructLayout(LayoutKind.Sequential)]
public class DOCHOSTUIINFO
{
[MarshalAs(UnmanagedType.U4)]
public int cbSize = 0;
[MarshalAs(UnmanagedType.I4)]
public int dwFlags = 0;
[MarshalAs(UnmanagedType.I4)]
public int dwDoubleClick = 0;
[MarshalAs(UnmanagedType.I4)]
public int dwReserved1 = 0;
[MarshalAs(UnmanagedType.I4)]
public int dwReserved2 = 0;
}
[ComVisible(false), StructLayout(LayoutKind.Sequential)]
public class MSG
{
public IntPtr hwnd = IntPtr.Zero;
public int message = 0;
public IntPtr wParam = IntPtr.Zero;
public IntPtr lParam = IntPtr.Zero;
public int time = 0;
public int pt_x = 0;
public int pt_y = 0;
}
[ComVisible(true), StructLayout(LayoutKind.Sequential)]
public class RECT
{
public int left = 0;
public int top = 0;
public int right = 0;
public int bottom = 0;
}
[ComVisible(false), StructLayout(LayoutKind.Sequential)]
public class tagOIFI
{
[MarshalAs(UnmanagedType.U4)]
public int cb;
[MarshalAs(UnmanagedType.I4)]
public int fMDIApp;
public IntPtr hwndFrame;
public IntPtr hAccel;
[MarshalAs(UnmanagedType.U4)]
public int cAccelEntries;
}
[ComVisible(false), StructLayout(LayoutKind.Sequential)]
public class tagOleMenuGroupWidths
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public int[] widths = new int[6];
}
[ComVisible(true), StructLayout(LayoutKind.Sequential)]
public struct OLECMD
{
[MarshalAs(UnmanagedType.U4)]
public int cmdID;
[MarshalAs(UnmanagedType.U4)]
public int cmdf;
}
[StructLayout(LayoutKind.Sequential)]
public struct OLECMDTEXT
{
public UInt32 cmdtextf;
public UInt32 cwActual;
public UInt32 cwBuf;
public Char rgwz;
}
[ComVisible(true), StructLayout(LayoutKind.Sequential)]
public struct win32POINT
{
public int x;
public int y;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NG.Easing
{
public static class Easing
{
// Adapted from source : http://www.robertpenner.com/easing/
// Reference curves: DocumentationResources/easing.png
#region Basic Easing
public static float Ease(double linearStep, float acceleration, EasingType type)
{
float easedStep = acceleration > 0 ? EaseIn(linearStep, type) :
acceleration < 0 ? EaseOut(linearStep, type) :
(float)linearStep;
return MathHelper.Lerp(linearStep, easedStep, Math.Abs(acceleration));
}
public static float EaseIn(double linearStep, EasingType type)
{
switch (type)
{
case EasingType.Step: return linearStep < 0.5 ? 0 : 1;
case EasingType.Linear: return (float)linearStep;
case EasingType.Sine: return Sine.EaseIn(linearStep);
case EasingType.Quadratic: return Power.EaseIn(linearStep, 2);
case EasingType.Cubic: return Power.EaseIn(linearStep, 3);
case EasingType.Quartic: return Power.EaseIn(linearStep, 4);
case EasingType.Quintic: return Power.EaseIn(linearStep, 5);
}
throw new NotImplementedException();
}
public static float EaseOut(double linearStep, EasingType type)
{
switch (type)
{
case EasingType.Step: return linearStep < 0.5 ? 0 : 1;
case EasingType.Linear: return (float)linearStep;
case EasingType.Sine: return Sine.EaseOut(linearStep);
case EasingType.Quadratic: return Power.EaseOut(linearStep, 2);
case EasingType.Cubic: return Power.EaseOut(linearStep, 3);
case EasingType.Quartic: return Power.EaseOut(linearStep, 4);
case EasingType.Quintic: return Power.EaseOut(linearStep, 5);
}
throw new NotImplementedException();
}
public static float EaseInOut(double linearStep, EasingType easeInType, EasingType easeOutType)
{
return linearStep < 0.5 ? EaseInOut(linearStep, easeInType) : EaseInOut(linearStep, easeOutType);
}
public static float EaseInOut(double linearStep, EasingType type)
{
switch (type)
{
case EasingType.Step: return linearStep < 0.5 ? 0 : 1;
case EasingType.Linear: return (float)linearStep;
case EasingType.Sine: return Sine.EaseInOut(linearStep);
case EasingType.Quadratic: return Power.EaseInOut(linearStep, 2);
case EasingType.Cubic: return Power.EaseInOut(linearStep, 3);
case EasingType.Quartic: return Power.EaseInOut(linearStep, 4);
case EasingType.Quintic: return Power.EaseInOut(linearStep, 5);
}
throw new NotImplementedException();
}
static class Sine
{
public static float EaseIn(double s)
{
return (float)Math.Sin(s * MathHelper.HalfPi - MathHelper.HalfPi) + 1;
}
public static float EaseOut(double s)
{
return (float)Math.Sin(s * MathHelper.HalfPi);
}
public static float EaseInOut(double s)
{
return (float)(Math.Sin(s * MathHelper.Pi - MathHelper.HalfPi) + 1) / 2;
}
}
static class Power
{
public static float EaseIn(double s, int power)
{
return (float)Math.Pow(s, power);
}
public static float EaseOut(double s, int power)
{
var sign = power % 2 == 0 ? -1 : 1;
return (float)(sign * (Math.Pow(s - 1, power) + sign));
}
public static float EaseInOut(double s, int power)
{
s *= 2;
if (s < 1) return EaseIn(s, power) / 2;
var sign = power % 2 == 0 ? -1 : 1;
return (float)(sign / 2.0 * (Math.Pow(s - 2, power) + sign * 2));
}
}
#endregion
#region Sigmoid
public static float SigmoidEaseInOut(float k, float t)
{
float correction = 0.5f / SigmoidBase(k, 1);
t = SigmoidClamp(t, 0, 1);
return correction * SigmoidBase(k, (2 * t - 1)) + 0.5f;
}
public static float SigmoidEaseOut(float k, float t)
{
k = (k == 0) ? 1e-7f : k;
t = SigmoidClamp(t, 0, 1);
return SigmoidBase(k, t) / SigmoidBase(k, 1);
}
public static float SigmoidEaseIn(float k, float t)
{
k = (k == 0) ? 1e-7f : k;
t = SigmoidClamp(t, 0, 1);
return SigmoidBase(k, t - 0.5f) / SigmoidBase(k, 1) + 1;
}
static float SigmoidBase(float k, float t)
{
return (1f / (1f + (float)Math.Exp(-k * t))) - 0.5f;
}
static float SigmoidClamp(float value, float lower, float upper)
{
return Math.Max(Math.Min(value, upper), lower);
}
#endregion
#region Elastic
/// <summary>
/// Easing equation function for an elastic (exponentially decaying sine wave) easing out:
/// decelerating from zero velocity.
/// </summary>
/// <param name="t">Current time in seconds.</param>
/// <param name="b">Starting value.</param>
/// <param name="c">Final value.</param>
/// <param name="d">Duration of animation.</param>
/// <returns>The correct value.</returns>
public static float ElasticEaseOut(float t, float b, float c, float d)
{
if ((t /= d) == 1)
return b + c;
float p = d * .3f;
float s = p / 4.0f;
return (c * (float)Math.Pow(2, -10 * t) * (float)Math.Sin((t * d - s) * (2 * Math.PI) / p) + c + b);
}
/// <summary>
/// Easing equation function for an elastic (exponentially decaying sine wave) easing in:
/// accelerating from zero velocity.
/// </summary>
/// <param name="t">Current time in seconds.</param>
/// <param name="b">Starting value.</param>
/// <param name="c">Final value.</param>
/// <param name="d">Duration of animation.</param>
/// <returns>The correct value.</returns>
public static float ElasticEaseIn(float t, float b, float c, float d)
{
if ((t /= d) == 1)
return b + c;
float p = d * .3f;
float s = p / 4;
return -(c * (float)Math.Pow(2, 10 * (t -= 1)) * (float)Math.Sin((t * d - s) * (2 * Math.PI) / p)) + b;
}
/// <summary>
/// Easing equation function for an elastic (exponentially decaying sine wave) easing in/out:
/// acceleration until halfway, then deceleration.
/// </summary>
/// <param name="t">Current time in seconds.</param>
/// <param name="b">Starting value.</param>
/// <param name="c">Final value.</param>
/// <param name="d">Duration of animation.</param>
/// <returns>The correct value.</returns>
public static float ElasticEaseInOut(float t, float b, float c, float d)
{
if ((t /= d / 2) == 2)
return b + c;
float p = d * (.3f * 1.5f);
float s = p / 4;
if (t < 1)
return -.5f * (c * (float)Math.Pow(2, 10 * (t -= 1)) * (float)Math.Sin((t * d - s) * (2 * Math.PI) / p)) + b;
return c * (float)Math.Pow(2, -10 * (t -= 1)) * (float)Math.Sin((t * d - s) * (2 * Math.PI) / p) * .5f + c + b;
}
/// <summary>
/// Easing equation function for an elastic (exponentially decaying sine wave) easing out/in:
/// deceleration until halfway, then acceleration.
/// </summary>
/// <param name="t">Current time in seconds.</param>
/// <param name="b">Starting value.</param>
/// <param name="c">Final value.</param>
/// <param name="d">Duration of animation.</param>
/// <returns>The correct value.</returns>
public static float ElasticEaseOutIn(float t, float b, float c, float d)
{
if (t < d / 2)
return ElasticEaseOut(t * 2, b, c / 2, d);
return ElasticEaseIn((t * 2) - d, b + c / 2, c / 2, d);
}
#endregion
public class Elastic
{
public static float In(float k)
{
if (k <= 0) return 0;
if (k >= 1) return 1;
return (float)(-Math.Pow(2f, 10f * (k -= 1f)) * Math.Sin((k - 0.1f) * (2f * Math.PI) / 0.4f));
}
public static float Out(float k)
{
if (k <= 0) return 0;
if (k >= 1) return 1;
return (float)(Math.Pow(2f, -10f * k) * Math.Sin((k - 0.1f) * (2f * Math.PI) / 0.4f) + 1f);
}
public static float InOut(float k)
{
if ((k *= 2f) < 1f)
return -0.5f * (float)(Math.Pow(2f, 10f * (k -= 1f)) * Math.Sin((k - 0.1f) * (2f * Math.PI) / 0.4f));
return (float)(Math.Pow(2f, -10f * (k -= 1f)) * Math.Sin((k - 0.1f) * (2f * Math.PI) / 0.4f) * 0.5f + 1f);
}
};
}
public enum EasingType
{
Step,
Linear,
Sine,
Quadratic,
Cubic,
Quartic,
Quintic,
}
public static class MathHelper
{
public const float Pi = (float)Math.PI;
public const float HalfPi = (float)(Math.PI / 2);
public static float Lerp(double from, double to, double step)
{
return (float)((to - from) * step + from);
}
}
}
| |
namespace Incoding.ExpressionSerialization
{
#region << Using >>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using System.Reflection;
#endregion
////ncrunch: no coverage start
/// <summary>
/// ExpressionUtility
/// </summary>
public static class ExpressionUtility
{
#region "privates"
static MemberBinding EnsureBinding(MemberBinding binding)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
return EnsureMemberAssignment((MemberAssignment)binding);
case MemberBindingType.MemberBinding:
return EnsureMemberMemberBinding((MemberMemberBinding)binding);
case MemberBindingType.ListBinding:
return EnsureMemberListBinding((MemberListBinding)binding);
default:
throw new NotSupportedException();
}
}
static ElementInit EnsureElementInitializer(ElementInit initializer)
{
var arguments = EnsureExpressionList(initializer.Arguments);
return arguments != initializer.Arguments ? Expression.ElementInit(initializer.AddMethod, arguments) : initializer;
}
static Expression EnsureUnary(UnaryExpression expression)
{
var operand = Ensure(expression.Operand);
return operand != expression.Operand ? Expression.MakeUnary(expression.NodeType, operand, expression.Type, expression.Method) : expression;
}
static Expression EnsureBinary(BinaryExpression expression)
{
var left = Ensure(expression.Left);
dynamic right = Ensure(expression.Right);
if (right is MemberExpression)
{
var info = (FieldInfo)right.Member;
var constant = Expression.Constant(info.GetValue(((ConstantExpression)right.Expression).Value));
return Expression.MakeBinary(expression.NodeType, expression.Left, constant);
}
right = Ensure(expression.Right);
var conversion = Ensure(expression.Conversion);
if (left != expression.Left || right != expression.Right || conversion != expression.Conversion)
{
if (expression.NodeType == ExpressionType.Coalesce && expression.Conversion != null)
return Expression.Coalesce(left, right, conversion as LambdaExpression);
return Expression.MakeBinary(expression.NodeType, left, right, expression.IsLiftedToNull, expression.Method);
}
return expression;
}
static Expression EnsureTypeIs(TypeBinaryExpression expression)
{
var expr = Ensure(expression.Expression);
return expr != expression.Expression ? Expression.TypeIs(expr, expression.TypeOperand) : expression;
}
static Expression EnsureConstant(Expression expression)
{
if (expression == null)
throw new ArgumentNullException("expression");
return expression;
}
static Expression EnsureConditional(ConditionalExpression expression)
{
var test = Ensure(expression.Test);
var ifTrue = Ensure(expression.IfTrue);
var ifFalse = Ensure(expression.IfFalse);
return test != expression.Test || ifTrue != expression.IfTrue || ifFalse != expression.IfFalse
? Expression.Condition(test, ifTrue, ifFalse)
: expression;
}
static Expression EnsureParameter(Expression expression)
{
if (expression == null)
throw new ArgumentNullException("expression");
return expression;
}
static Expression EnsureMemberAccess(MemberExpression expression)
{
var exp = Ensure(expression.Expression);
return exp != expression.Expression ? Expression.MakeMemberAccess(exp, expression.Member) : expression;
}
static Expression EnsureMethodCall(MethodCallExpression expression)
{
var obj = Ensure(expression.Object);
var args = EnsureExpressionList(expression.Arguments);
return obj != expression.Object || args != expression.Arguments
? Expression.Call(obj, expression.Method, args)
: expression;
}
static IEnumerable<Expression> EnsureExpressionList(ReadOnlyCollection<Expression> original)
{
List<Expression> list = null;
int n = original.Count;
for (int i = 0; i < n; i++)
{
var p = Ensure(original[i]);
if (list != null)
list.Add(p);
else if (p != original[i])
{
list = new List<Expression>(n);
for (int j = 0; j < i; j++)
list.Add(original[j]);
list.Add(p);
}
}
return list != null ? list.AsReadOnly() : original;
}
static MemberAssignment EnsureMemberAssignment(MemberAssignment assignment)
{
var e = Ensure(assignment.Expression);
return e != assignment.Expression ? Expression.Bind(assignment.Member, e) : assignment;
}
static MemberMemberBinding EnsureMemberMemberBinding(MemberMemberBinding binding)
{
var bindings = EnsureBindingList(binding.Bindings);
return bindings != binding.Bindings ? Expression.MemberBind(binding.Member, bindings) : binding;
}
static MemberListBinding EnsureMemberListBinding(MemberListBinding binding)
{
var initializers = EnsureElementInitializerList(binding.Initializers);
return initializers != binding.Initializers ? Expression.ListBind(binding.Member, initializers) : binding;
}
static IEnumerable<MemberBinding> EnsureBindingList(ReadOnlyCollection<MemberBinding> original)
{
List<MemberBinding> list = null;
int n = original.Count;
for (int i = 0; i < n; i++)
{
var b = EnsureBinding(original[i]);
if (list != null)
list.Add(b);
else if (b != original[i])
{
list = new List<MemberBinding>(n);
for (int j = 0; j < i; j++)
list.Add(original[j]);
list.Add(b);
}
}
return list != null ? (IEnumerable<MemberBinding>)list : original;
}
static IEnumerable<ElementInit> EnsureElementInitializerList(ReadOnlyCollection<ElementInit> original)
{
List<ElementInit> list = null;
int n = original.Count;
for (int i = 0; i < n; i++)
{
var init = EnsureElementInitializer(original[i]);
if (list != null)
list.Add(init);
else if (init != original[i])
{
list = new List<ElementInit>(n);
for (int j = 0; j < i; j++)
list.Add(original[j]);
list.Add(init);
}
}
return list != null ? (IEnumerable<ElementInit>)list : original;
}
static Expression EnsureLambda(LambdaExpression expression)
{
var body = Ensure(expression.Body);
return body != expression.Body ? Expression.Lambda(expression.Type, body, expression.Parameters) : expression;
}
static NewExpression EnsureNew(NewExpression expression)
{
var args = EnsureExpressionList(expression.Arguments);
if (args != expression.Arguments)
return expression.Members != null ? Expression.New(expression.Constructor, args, expression.Members) : Expression.New(expression.Constructor, args);
return expression;
}
static Expression EnsureMemberInit(MemberInitExpression expression)
{
var n = EnsureNew(expression.NewExpression);
var bindings = EnsureBindingList(expression.Bindings);
return n != expression.NewExpression || bindings != expression.Bindings
? Expression.MemberInit(n, bindings)
: expression;
}
static Expression EnsureListInit(ListInitExpression expression)
{
var n = EnsureNew(expression.NewExpression);
var initializers = EnsureElementInitializerList(expression.Initializers);
return n != expression.NewExpression || initializers != expression.Initializers
? Expression.ListInit(n, initializers)
: expression;
}
static Expression EnsureNewArray(NewArrayExpression expression)
{
var exprs = EnsureExpressionList(expression.Expressions);
if (exprs != expression.Expressions)
return expression.NodeType == ExpressionType.NewArrayInit ? Expression.NewArrayInit(expression.Type.GetElementType(), exprs) : Expression.NewArrayBounds(expression.Type.GetElementType(), exprs);
return expression;
}
static Expression EnsureInvocation(InvocationExpression expression)
{
var args = EnsureExpressionList(expression.Arguments);
var expr = Ensure(expression.Expression);
return args != expression.Arguments || expr != expression.Expression
? Expression.Invoke(expr, args)
: expression;
}
#endregion
#region Factory constructors
/// <summary>
/// Ensure
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static Expression Ensure(Expression expression)
{
if (expression == null)
return expression;
switch (expression.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
return EnsureUnary((UnaryExpression)expression);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
return EnsureBinary((BinaryExpression)expression);
case ExpressionType.TypeIs:
return EnsureTypeIs((TypeBinaryExpression)expression);
case ExpressionType.Conditional:
return EnsureConditional((ConditionalExpression)expression);
case ExpressionType.Constant:
return EnsureConstant(expression);
case ExpressionType.Parameter:
return EnsureParameter(expression);
case ExpressionType.MemberAccess:
return EnsureMemberAccess((MemberExpression)expression);
case ExpressionType.Call:
return EnsureMethodCall((MethodCallExpression)expression);
case ExpressionType.Lambda:
return EnsureLambda((LambdaExpression)expression);
case ExpressionType.New:
return EnsureNew((NewExpression)expression);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return EnsureNewArray((NewArrayExpression)expression);
case ExpressionType.Invoke:
return EnsureInvocation((InvocationExpression)expression);
case ExpressionType.MemberInit:
return EnsureMemberInit((MemberInitExpression)expression);
case ExpressionType.ListInit:
return EnsureListInit((ListInitExpression)expression);
default:
throw new NotSupportedException();
}
}
#endregion
}
////ncrunch: no coverage end
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using Moq.Protected;
using Xunit;
namespace Moq.Tests
{
public partial class ProtectedMockFixture
{
[Fact]
public void ThrowsIfNullMock()
{
Assert.Throws<ArgumentNullException>(() => ProtectedExtension.Protected((Mock<string>)null));
}
[Fact]
public void ThrowsIfSetupNullVoidMethodName()
{
Assert.Throws<ArgumentNullException>(() => new Mock<FooBase>().Protected().Setup(null));
Assert.Throws<ArgumentNullException>(() => new Mock<FooBase>().Protected().Setup<int>(null));
}
[Fact]
public void ThrowsIfSetupEmptyVoidMethodName()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().Setup(string.Empty));
}
[Fact]
public void ThrowsIfSetupResultNullMethodName()
{
Assert.Throws<ArgumentNullException>(() => new Mock<FooBase>().Protected().Setup<int>(null));
}
[Fact]
public void ThrowsIfSetupResultEmptyMethodName()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().Setup<int>(string.Empty));
}
[Fact]
public void ThrowsIfSetupVoidMethodNotFound()
{
var actual = Record.Exception(() =>
{
new Mock<FooBase>().Protected().Setup("Foo");
});
Assert.IsType<ArgumentException>(actual);
Assert.Equal("No protected method FooBase.Foo found whose signature is compatible with the provided arguments ().", actual.Message);
}
[Fact]
public void ThrowsIfSetupResultMethodNotFound()
{
var actual = Record.Exception(() =>
{
new Mock<FooBase>().Protected().Setup<int>("Foo");
});
Assert.IsType<ArgumentException>(actual);
Assert.Equal("No protected method FooBase.Foo found whose signature is compatible with the provided arguments ().", actual.Message);
}
[Fact]
public void ThrowsIfSetupIncompatibleArgumentSupplied()
{
var actual = Record.Exception(() =>
{
new Mock<FooBase>().Protected().Setup<string>("StringArg", ItExpr.IsAny<int>());
});
Assert.IsType<ArgumentException>(actual);
Assert.Equal("No protected method FooBase.StringArg found whose signature is compatible with the provided arguments (int).", actual.Message);
}
[Fact]
public void ThrowsIfSetupPublicVoidMethod()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().Setup("Public"));
}
[Fact]
public void ThrowsIfSetupPublicResultMethod()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().Setup<int>("PublicInt"));
}
[Fact]
public void ThrowsIfSetupNonVirtualVoidMethod()
{
Assert.Throws<NotSupportedException>(() => new Mock<FooBase>().Protected().Setup("NonVirtual"));
}
[Fact]
public void ThrowsIfSetupNonVirtualResultMethod()
{
Assert.Throws<NotSupportedException>(() => new Mock<FooBase>().Protected().Setup<int>("NonVirtualInt"));
}
[Fact]
public void SetupAllowsProtectedInternalVoidMethod()
{
var mock = new Mock<FooBase>();
mock.Protected().Setup("ProtectedInternal");
mock.Object.ProtectedInternal();
mock.Protected().Setup("ProtectedInternalGeneric", new[] { typeof(int) }, false);
mock.Object.ProtectedInternalGeneric<int>();
mock.VerifyAll();
}
[Fact]
public void SetupAllowsProtectedInternalResultMethod()
{
var mock = new Mock<FooBase>();
mock.Protected()
.Setup<int>("ProtectedInternalInt")
.Returns(5);
Assert.Equal(5, mock.Object.ProtectedInternalInt());
mock.Protected()
.Setup<int>("ProtectedInternalReturnGeneric", new[] { typeof(int) }, false)
.Returns(5);
Assert.Equal(5, mock.Object.ProtectedInternalReturnGeneric<int>());
}
[Fact]
public void SetupAllowsProtectedVoidMethod()
{
var mock = new Mock<FooBase>();
mock.Protected().Setup("Protected");
mock.Object.DoProtected();
mock.Protected().Setup("ProtectedGeneric", new[] { typeof(int) }, false);
mock.Object.DoProtectedGeneric<int>();
mock.VerifyAll();
}
[Fact]
public void SetupAllowsProtectedResultMethod()
{
var mock = new Mock<FooBase>();
mock.Protected()
.Setup<int>("ProtectedInt")
.Returns(5);
Assert.Equal(5, mock.Object.DoProtectedInt());
mock.Protected()
.Setup<int>("ProtectedReturnGeneric", new[] { typeof(int) }, false)
.Returns(5);
Assert.Equal(5, mock.Object.DoProtectedReturnGeneric<int>());
}
[Fact]
public void SetupAllowsProtectedMethodWithNullableParameters()
{
int? input = 5;
int expectedOutput = 6;
var mock = new Mock<FooBase>();
mock.Protected()
.Setup<int>("ProtectedWithNullableIntParam", input)
.Returns(expectedOutput);
Assert.Equal(expectedOutput, mock.Object.DoProtectedWithNullableIntParam(input));
mock.Protected()
.Setup<int?>("ProtectedWithGenericParam", new[] { typeof(int?) }, false, input)
.Returns(expectedOutput);
Assert.Equal(expectedOutput, mock.Object.DoProtectedWithGenericParam<int?>(input));
}
[Fact]
public void SetupAllowsGenericProtectedMethodWithDiffrentGenericArguments()
{
var mock = new Mock<FooBase>();
mock.Protected().Setup("ProtectedGeneric", new[] { typeof(int) }, false);
mock.Protected().Setup("ProtectedGeneric", new[] { typeof(string) }, false);
mock.Object.DoProtectedGeneric<int>();
mock.Object.DoProtectedGeneric<string>();
mock.VerifyAll();
mock.Protected()
.Setup<int>("ProtectedInternalReturnGeneric", new[] { typeof(int) }, false)
.Returns(5);
mock.Protected()
.Setup<string>("ProtectedInternalReturnGeneric", new[] { typeof(string) }, false)
.Returns("s");
Assert.Equal(5, mock.Object.ProtectedInternalReturnGeneric<int>());
Assert.Equal("s", mock.Object.ProtectedInternalReturnGeneric<string>());
}
[Fact]
public void ThrowsIfSetupVoidMethodIsProperty()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().Setup("ProtectedValue"));
}
[Fact]
public void SetupResultAllowsProperty()
{
var mock = new Mock<FooBase>();
mock.Protected()
.Setup<string>("ProtectedValue")
.Returns("foo");
Assert.Equal("foo", mock.Object.GetProtectedValue());
}
[Fact]
public void ThrowsIfSetupGetNullPropertyName()
{
Assert.Throws<ArgumentNullException>(() => new Mock<FooBase>().Protected().SetupGet<string>(null));
}
[Fact]
public void ThrowsIfSetupGetEmptyPropertyName()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().SetupGet<string>(string.Empty));
}
[Fact]
public void ThrowsIfSetupGetPropertyNotFound()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().SetupGet<int>("Foo"));
}
[Fact]
public void ThrowsIfSetupGetPropertyWithoutPropertyGet()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().SetupGet<int>("OnlySet"));
}
[Fact]
public void ThrowsIfSetupGetPublicPropertyGet()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().SetupGet<int>("PublicValue"));
}
[Fact]
public void ThrowsIfSetupGetNonVirtualProperty()
{
Assert.Throws<NotSupportedException>(() => new Mock<FooBase>().Protected().SetupGet<string>("NonVirtualValue"));
}
[Fact]
public void SetupGetAllowsProtectedInternalPropertyGet()
{
var mock = new Mock<FooBase>();
mock.Protected()
.SetupGet<string>("ProtectedInternalValue")
.Returns("foo");
Assert.Equal("foo", mock.Object.ProtectedInternalValue);
}
[Fact]
public void SetupGetAllowsProtectedPropertyGet()
{
var mock = new Mock<FooBase>();
mock.Protected()
.SetupGet<string>("ProtectedValue")
.Returns("foo");
Assert.Equal("foo", mock.Object.GetProtectedValue());
}
[Fact]
public void ThrowsIfSetupSetNullPropertyName()
{
Assert.Throws<ArgumentNullException>(
() => new Mock<FooBase>().Protected().SetupSet<string>(null, ItExpr.IsAny<string>()));
}
[Fact]
public void ThrowsIfSetupSetEmptyPropertyName()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().SetupSet<string>(string.Empty, ItExpr.IsAny<string>()));
}
[Fact]
public void ThrowsIfSetupSetPropertyNotFound()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().SetupSet<int>("Foo", ItExpr.IsAny<int>()));
}
[Fact]
public void ThrowsIfSetupSetPropertyWithoutPropertySet()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().SetupSet<int>("OnlyGet", ItExpr.IsAny<int>()));
}
[Fact]
public void ThrowsIfSetupSetPublicPropertySet()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().SetupSet<int>("PublicValue", ItExpr.IsAny<int>()));
}
[Fact]
public void ThrowsIfSetupSetNonVirtualProperty()
{
Assert.Throws<NotSupportedException>(
() => new Mock<FooBase>().Protected().SetupSet<string>("NonVirtualValue", ItExpr.IsAny<string>()));
}
[Fact]
public void SetupSetAllowsProtectedInternalPropertySet()
{
var mock = new Mock<FooBase>();
var value = string.Empty;
mock.Protected()
.SetupSet<string>("ProtectedInternalValue", ItExpr.IsAny<string>())
.Callback(v => value = v);
mock.Object.ProtectedInternalValue = "foo";
Assert.Equal("foo", value);
mock.VerifyAll();
}
[Fact]
public void SetupSetAllowsProtectedPropertySet()
{
var mock = new Mock<FooBase>();
var value = string.Empty;
mock.Protected()
.SetupSet<string>("ProtectedValue", ItExpr.IsAny<string>())
.Callback(v => value = v);
mock.Object.SetProtectedValue("foo");
Assert.Equal("foo", value);
mock.VerifyAll();
}
[Fact]
public void ThrowsIfNullArgs()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected()
.Setup<string>("StringArg", null)
.Returns("null"));
}
[Fact]
public void AllowMatchersForArgs()
{
var mock = new Mock<FooBase>();
mock.Protected()
.Setup<string>("StringArg", ItExpr.IsNull<string>())
.Returns("null");
Assert.Equal("null", mock.Object.DoStringArg(null));
mock.Protected()
.Setup<string>("StringArg", ItExpr.Is<string>(s => s == "bar"))
.Returns("baz");
Assert.Equal("baz", mock.Object.DoStringArg("bar"));
mock = new Mock<FooBase>();
mock.Protected()
.Setup<string>("StringArg", ItExpr.Is<string>(s => s.Length >= 2))
.Returns("long");
mock.Protected()
.Setup<string>("StringArg", ItExpr.Is<string>(s => s.Length < 2))
.Returns("short");
Assert.Equal("short", mock.Object.DoStringArg("f"));
Assert.Equal("long", mock.Object.DoStringArg("foo"));
mock = new Mock<FooBase>();
mock.CallBase = true;
mock.Protected()
.Setup<string>("TwoArgs", ItExpr.IsAny<string>(), 5)
.Returns("done");
Assert.Equal("done", mock.Object.DoTwoArgs("foobar", 5));
Assert.Equal("echo", mock.Object.DoTwoArgs("echo", 15));
mock = new Mock<FooBase>();
mock.CallBase = true;
mock.Protected()
.Setup<string>("TwoArgs", ItExpr.IsAny<string>(), ItExpr.IsInRange(1, 3, Range.Inclusive))
.Returns("inrange");
Assert.Equal("inrange", mock.Object.DoTwoArgs("foobar", 2));
Assert.Equal("echo", mock.Object.DoTwoArgs("echo", 4));
}
[Fact]
public void ResolveOverloads()
{
// NOTE: There are two overloads named "Do" and "DoReturn"
var mock = new Mock<MethodOverloads>();
mock.Protected().Setup("Do", 1, 2).Verifiable();
mock.Protected().Setup("Do", new[] { typeof(int) }, false, 1, 3).Verifiable();
mock.Protected().Setup<string>("DoReturn", "1", "2").Returns("3").Verifiable();
mock.Protected().Setup<string>("DoReturn", new[] { typeof(int), typeof(string) }, false, 1, "2")
.Returns("4").Verifiable();
mock.Object.ExecuteDo(1, 2);
mock.Object.ExecuteDo<int>(1, 3);
Assert.Equal("3", mock.Object.ExecuteDoReturn("1", "2"));
Assert.Equal("4", mock.Object.ExecuteDoReturn<int, string>(1, "2"));
mock.Verify();
}
[Fact]
public void ResolveOverloadsSameFirstParameterType()
{
var mock = new Mock<MethodOverloads>();
mock.Protected().Setup("SameFirstParameter", new object(), new object()).Verifiable();
mock.Protected().Setup("SameFirstParameter", new object()).Verifiable();
mock.Object.ExecuteSameFirstParameter(new object());
}
[Fact]
public void ThrowsIfSetReturnsForVoidMethod()
{
Assert.Throws<ArgumentException>(
() => new Mock<MethodOverloads>().Protected().Setup<string>("Do", "1", "2").Returns("3"));
}
[Fact]
public void SetupResultAllowsProtectedMethodInBaseClass()
{
var mock = new Mock<FooDerived>();
mock.Protected()
.Setup<int>("ProtectedInt")
.Returns(5);
Assert.Equal(5, mock.Object.DoProtectedInt());
mock.Protected()
.Setup<int>("ProtectedReturnGeneric", new[] { typeof(int) }, false)
.Returns(5);
Assert.Equal(5, mock.Object.DoProtectedReturnGeneric<int>());
}
[Fact]
public void SetupResultDefaulTwoOverloadsWithDerivedClassThrowsInvalidOperationException()
{
var mock = new Mock<MethodOverloads>();
Assert.Throws<InvalidOperationException>(() => mock.Protected()
.Setup<FooBase>("Overloaded", ItExpr.IsAny<MyDerived>())
.Returns(new FooBase()));
}
[Fact]
public void SetupResultExactParameterMatchTwoOverloadsWithDerivedClassShouldNotThrow()
{
var mock = new Mock<MethodOverloads>();
var fooBase = new FooBase();
mock.Protected()
.Setup<FooBase>("Overloaded", true, ItExpr.IsAny<MyDerived>())
.Returns(fooBase);
}
[Fact]
public void ThrowsIfVerifyNullVoidMethodName()
{
Assert.Throws<ArgumentNullException>(() => new Mock<FooBase>().Protected().Verify(null, Times.Once()));
}
[Fact]
public void ThrowsIfVerifyEmptyVoidMethodName()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().Verify(string.Empty, Times.Once()));
}
[Fact]
public void ThrowsIfVerifyNullResultMethodName()
{
Assert.Throws<ArgumentNullException>(() => new Mock<FooBase>().Protected().Verify<int>(null, Times.Once()));
}
[Fact]
public void ThrowsIfVerifyEmptyResultMethodName()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().Verify<int>(string.Empty, Times.Once()));
}
[Fact]
public void ThrowsIfVerifyVoidMethodNotFound()
{
var actual = Record.Exception(() =>
{
new Mock<FooBase>().Protected().Verify("Foo", Times.Once());
});
Assert.IsType<ArgumentException>(actual);
Assert.Equal("No protected method FooBase.Foo found whose signature is compatible with the provided arguments ().", actual.Message);
}
[Fact]
public void ThrowsIfVerifyResultMethodNotFound()
{
var actual = Record.Exception(() =>
{
new Mock<FooBase>().Protected().Verify<int>("Foo", Times.Once());
});
Assert.IsType<ArgumentException>(actual);
Assert.Equal("No protected method FooBase.Foo found whose signature is compatible with the provided arguments ().", actual.Message);
}
[Fact]
public void ThrowsIfVerifyIncompatibleArgumentSupplied()
{
var actual = Record.Exception(() =>
{
new Mock<FooBase>().Protected().Verify<string>("StringArg", Times.Once(), ItExpr.IsAny<int>());
});
Assert.IsType<ArgumentException>(actual);
Assert.Equal("No protected method FooBase.StringArg found whose signature is compatible with the provided arguments (int).", actual.Message);
}
[Fact]
public void ThrowsIfVerifyPublicVoidMethod()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().Verify("Public", Times.Once()));
}
[Fact]
public void ThrowsIfVerifyPublicResultMethod()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().Verify<int>("PublicInt", Times.Once()));
}
[Fact]
public void ThrowsIfVerifyNonVirtualVoidMethod()
{
Assert.Throws<NotSupportedException>(() => new Mock<FooBase>().Protected().Verify("NonVirtual", Times.Once()));
}
[Fact]
public void ThrowsIfVerifyNonVirtualResultMethod()
{
Assert.Throws<NotSupportedException>(
() => new Mock<FooBase>().Protected().Verify<int>("NonVirtualInt", Times.Once()));
}
[Fact]
public void VerifyAllowsProtectedInternalVoidMethod()
{
var mock = new Mock<FooBase>();
mock.Object.ProtectedInternal();
mock.Protected().Verify("ProtectedInternal", Times.Once());
mock.Object.ProtectedInternalGeneric<int>();
mock.Protected().Verify("ProtectedInternalGeneric", new[] { typeof(int) }, Times.Once());
}
[Fact]
public void VerifyAllowsProtectedInternalResultMethod()
{
var mock = new Mock<FooBase>();
mock.Object.ProtectedInternalInt();
mock.Protected().Verify<int>("ProtectedInternalInt", Times.Once());
mock.Object.ProtectedInternalReturnGeneric<int>();
mock.Protected().Verify<int>("ProtectedInternalReturnGeneric", new[] { typeof(int) }, Times.Once());
}
[Fact]
public void VerifyAllowsProtectedVoidMethod()
{
var mock = new Mock<FooBase>();
mock.Object.DoProtected();
mock.Protected().Verify("Protected", Times.Once());
mock.Object.DoProtectedGeneric<int>();
mock.Protected().Verify("ProtectedGeneric", new[] { typeof(int) }, Times.Once());
}
[Fact]
public void VerifyAllowsProtectedResultMethod()
{
var mock = new Mock<FooBase>();
mock.Object.DoProtectedInt();
mock.Protected().Verify<int>("ProtectedInt", Times.Once());
mock.Object.DoProtectedReturnGeneric<int>();
mock.Protected().Verify<int>("ProtectedReturnGeneric", new[] { typeof(int) }, Times.Once());
}
[Fact]
public void ThrowsIfVerifyVoidMethodIsProperty()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().Verify("ProtectedValue", Times.Once()));
}
[Fact]
public void VerifyResultAllowsProperty()
{
var mock = new Mock<FooBase>();
mock.Object.GetProtectedValue();
mock.Protected().Verify<string>("ProtectedValue", Times.Once());
}
[Fact]
public void ThrowsIfVerifyVoidMethodTimesNotReached()
{
var mock = new Mock<FooBase>();
mock.Object.DoProtected();
Assert.Throws<MockException>(() => mock.Protected().Verify("Protected", Times.Exactly(2)));
}
[Fact]
public void ThrowsIfVerifyResultMethodTimesNotReached()
{
var mock = new Mock<FooBase>();
mock.Object.DoProtectedInt();
Assert.Throws<MockException>(() => mock.Protected().Verify("ProtectedInt", Times.Exactly(2)));
}
[Fact]
public void DoesNotThrowIfVerifyVoidMethodTimesReached()
{
var mock = new Mock<FooBase>();
mock.Object.DoProtected();
mock.Object.DoProtected();
mock.Protected().Verify("Protected", Times.Exactly(2));
}
[Fact]
public void DoesNotThrowIfVerifyReturnMethodTimesReached()
{
var mock = new Mock<FooBase>();
mock.Object.DoProtectedInt();
mock.Object.DoProtectedInt();
mock.Protected().Verify<int>("ProtectedInt", Times.Exactly(2));
}
[Fact]
public void ThrowsIfVerifyPropertyTimesNotReached()
{
var mock = new Mock<FooBase>();
mock.Object.GetProtectedValue();
Assert.Throws<MockException>(() => mock.Protected().Verify<string>("ProtectedValue", Times.Exactly(2)));
}
[Fact]
public void DoesNotThrowIfVerifyPropertyTimesReached()
{
var mock = new Mock<FooBase>();
mock.Object.GetProtectedValue();
mock.Object.GetProtectedValue();
mock.Protected().Verify<string>("ProtectedValue", Times.Exactly(2));
}
[Fact]
public void ThrowsIfVerifyGetNullPropertyName()
{
Assert.Throws<ArgumentNullException>(() => new Mock<FooBase>().Protected().VerifyGet<int>(null, Times.Once()));
}
[Fact]
public void ThrowsIfVerifyGetEmptyPropertyName()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().VerifyGet<int>(string.Empty, Times.Once()));
}
[Fact]
public void ThrowsIfVerifyGetPropertyNotFound()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().VerifyGet<int>("Foo", Times.Once()));
}
[Fact]
public void ThrowsIfVerifyGetPropertyWithoutPropertyGet()
{
Assert.Throws<ArgumentException>(() => new Mock<FooBase>().Protected().VerifyGet<int>("OnlySet", Times.Once()));
}
[Fact]
public void ThrowsIfVerifyGetIsPublicPropertyGet()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().VerifyGet<string>("PublicValue", Times.Once()));
}
[Fact]
public void VerifyGetAllowsProtectedInternalPropertyGet()
{
var mock = new Mock<FooBase>();
var value = mock.Object.ProtectedInternalValue;
mock.Protected().VerifyGet<string>("ProtectedInternalValue", Times.Once());
}
[Fact]
public void VerifyGetAllowsProtectedPropertyGet()
{
var mock = new Mock<FooBase>();
mock.Object.GetProtectedValue();
mock.Protected().VerifyGet<string>("ProtectedValue", Times.Once());
}
[Fact]
public void ThrowsIfVerifyGetNonVirtualPropertyGet()
{
Assert.Throws<NotSupportedException>(
() => new Mock<FooBase>().Protected().VerifyGet<string>("NonVirtualValue", Times.Once()));
}
[Fact]
public void ThrowsIfVerifyGetTimesNotReached()
{
var mock = new Mock<FooBase>();
mock.Object.GetProtectedValue();
Assert.Throws<MockException>(() => mock.Protected().VerifyGet<string>("ProtectedValue", Times.Exactly(2)));
}
[Fact]
public void DoesNotThrowIfVerifyGetPropertyTimesReached()
{
var mock = new Mock<FooBase>();
mock.Object.GetProtectedValue();
mock.Object.GetProtectedValue();
mock.Protected().VerifyGet<string>("ProtectedValue", Times.Exactly(2));
}
[Fact]
public void ThrowsIfVerifySetNullPropertyName()
{
Assert.Throws<ArgumentNullException>(
() => new Mock<FooBase>().Protected().VerifySet<string>(null, Times.Once(), ItExpr.IsAny<string>()));
}
[Fact]
public void ThrowsIfVerifySetEmptyPropertyName()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().VerifySet<string>(string.Empty, Times.Once(), ItExpr.IsAny<int>()));
}
[Fact]
public void ThrowsIfVerifySetPropertyNotFound()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().VerifySet<int>("Foo", Times.Once(), ItExpr.IsAny<int>()));
}
[Fact]
public void ThrowsIfVerifySetPropertyWithoutPropertySet()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().VerifySet<int>("OnlyGet", Times.Once(), ItExpr.IsAny<int>()));
}
[Fact]
public void ThrowsIfVerifySetPublicPropertySet()
{
Assert.Throws<ArgumentException>(
() => new Mock<FooBase>().Protected().VerifySet<int>("PublicValue", Times.Once(), ItExpr.IsAny<int>()));
}
[Fact]
public void ThrowsIfVerifySetNonVirtualPropertySet()
{
Assert.Throws<NotSupportedException>(
() => new Mock<FooBase>().Protected().VerifySet<string>("NonVirtualValue", Times.Once(), ItExpr.IsAny<string>()));
}
[Fact]
public void VerifySetAllowsProtectedInternalPropertySet()
{
var mock = new Mock<FooBase>();
mock.Object.ProtectedInternalValue = "foo";
mock.Protected().VerifySet<string>("ProtectedInternalValue", Times.Once(), "bar");
}
[Fact]
public void VerifySetAllowsProtectedPropertySet()
{
var mock = new Mock<FooBase>();
mock.Object.SetProtectedValue("foo");
mock.Protected().VerifySet<string>("ProtectedValue", Times.Once(), ItExpr.IsAny<string>());
}
[Fact]
public void ThrowsIfVerifySetTimesNotReached()
{
var mock = new Mock<FooBase>();
mock.Object.SetProtectedValue("Foo");
Assert.Throws<MockException>(
() => mock.Protected().VerifySet<string>("ProtectedValue", Times.Exactly(2), ItExpr.IsAny<string>()));
}
[Fact]
public void DoesNotThrowIfVerifySetPropertyTimesReached()
{
var mock = new Mock<FooBase>();
mock.Object.SetProtectedValue("foo");
mock.Object.SetProtectedValue("foo");
mock.Protected().VerifySet<string>("ProtectedValue", Times.Exactly(2), ItExpr.IsAny<int>());
}
public class MethodOverloads
{
public void ExecuteDo(int a, int b)
{
this.Do(a, b);
}
public void ExecuteDo(string a, string b)
{
this.Do(a, b);
}
public void ExecuteDo<T>(T a, T b)
{
this.Do<T>(a, b);
}
public void ExecuteDo<T, T2>(T a, T2 b)
{
this.Do<T, T2>(a, b);
}
public int ExecuteDoReturn(int a, int b)
{
return this.DoReturn(a, b);
}
protected virtual void Do(int a, int b)
{
}
protected virtual void Do(string a, string b)
{
}
protected virtual void Do<T>(T a, T b)
{
}
protected virtual void Do<T, T2>(T a, T2 b)
{
}
protected virtual int DoReturn(int a, int b)
{
return a + b;
}
public string ExecuteDoReturn(string a, string b)
{
return DoReturn(a, b);
}
public T ExecuteDoReturn<T>(T a, T b)
{
return DoReturn<T>(a, b);
}
public T2 ExecuteDoReturn<T, T2>(T a, T2 b)
{
return DoReturn(a, b);
}
protected virtual string DoReturn(string a, string b)
{
return a + b;
}
protected virtual T DoReturn<T>(T a, T b)
{
return a;
}
protected virtual T2 DoReturn<T, T2>(T a, T2 b)
{
return b;
}
public void ExecuteSameFirstParameter(object a) { }
protected virtual void SameFirstParameter(object a) { }
protected virtual void SameFirstParameter(object a, object b) { }
protected virtual FooBase Overloaded(MyBase myBase)
{
return null;
}
protected virtual FooBase Overloaded(MyDerived myBase)
{
return null;
}
}
public class FooBase
{
public virtual string PublicValue { get; set; }
protected internal virtual string ProtectedInternalValue { get; set; }
protected string NonVirtualValue { get; set; }
protected virtual int OnlyGet
{
get { return 0; }
}
protected virtual int OnlySet
{
set { }
}
protected virtual string ProtectedValue { get; set; }
protected virtual int this[int index]
{
get { return 0; }
set { }
}
public void DoProtected()
{
this.Protected();
}
public void DoProtectedGeneric<T>()
{
this.ProtectedGeneric<T>();
}
public int DoProtectedInt()
{
return this.ProtectedInt();
}
public T DoProtectedReturnGeneric<T>()
{
return this.ProtectedReturnGeneric<T>();
}
public int DoProtectedWithNullableIntParam(int? value)
{
return this.ProtectedWithNullableIntParam(value);
}
public T DoProtectedWithGenericParam<T>(T value)
{
return this.ProtectedWithGenericParam(value);
}
public string DoStringArg(string arg)
{
return this.StringArg(arg);
}
public string DoTwoArgs(string arg, int arg1)
{
return this.TwoArgs(arg, arg1);
}
public string GetProtectedValue()
{
return this.ProtectedValue;
}
public virtual void Public()
{
}
public virtual int PublicInt()
{
return 10;
}
public void SetProtectedValue(string value)
{
this.ProtectedValue = value;
}
internal protected virtual void ProtectedInternal()
{
}
internal protected virtual void ProtectedInternalGeneric<T>()
{
}
internal protected virtual int ProtectedInternalInt()
{
return 0;
}
internal protected virtual T ProtectedInternalReturnGeneric<T>()
{
return default(T);
}
protected virtual void Protected()
{
}
protected virtual void ProtectedGeneric<T>()
{
}
protected virtual int ProtectedInt()
{
return 2;
}
protected virtual T ProtectedReturnGeneric<T>()
{
return default(T);
}
protected virtual int ProtectedWithNullableIntParam(int? value)
{
return value ?? 0;
}
protected virtual T ProtectedWithGenericParam<T>(T value)
{
return value;
}
protected void NonVirtual()
{
}
protected int NonVirtualInt()
{
return 2;
}
protected virtual string StringArg(string arg)
{
return arg;
}
protected virtual string TwoArgs(string arg, int arg1)
{
return arg;
}
}
public class FooDerived : FooBase
{
}
public class MyBase { }
public class MyDerived : MyBase { }
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Web.UI.WebControls;
using Rainbow.Framework;
using Rainbow.Framework.Content.Data;
using Rainbow.Framework.Data;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Helpers;
using Rainbow.Framework.Security;
using Rainbow.Framework.Users.Data;
using Rainbow.Framework.Web.UI.WebControls;
namespace Rainbow.Content.Web.Modules
{
/// <summary>
/// Articles
/// </summary>
public class Articles : PortalModuleControl
{
/// <summary>
///
/// </summary>
protected DataList myDataList;
/// <summary>
/// Gets a value indicating whether [show date].
/// </summary>
/// <value><c>true</c> if [show date]; otherwise, <c>false</c>.</value>
protected bool ShowDate
{
get
{
// Hide/show date
return bool.Parse(Settings["ShowDate"].ToString());
}
}
/// <summary>
/// The Page_Load event handler on this User Control is used to
/// obtain a DataReader of Article information from the Articles
/// table, and then databind the results to a templated DataList
/// server control. It uses the Rainbow.ArticleDB()
/// data component to encapsulate all data functionality.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
// Obtain Articles information from the Articles table
// and bind to the datalist control
ArticlesDB Articles = new ArticlesDB();
if (PortalSecurity.IsInRoles(Settings["EXPIRED_PERMISSION_ROLE"].ToString()))
myDataList.DataSource = Articles.GetArticlesAll(ModuleID, Version);
else
myDataList.DataSource = Articles.GetArticles(ModuleID, Version);
myDataList.DataBind();
}
/// <summary>
/// Initializes a new instance of the <see cref="T:Articles"/> class.
/// </summary>
public Articles()
{
SupportsWorkflow = true;
if (portalSettings != null) //check for avoid design time errors
{
// modified by Hongwei Shen(hongwei.shen@gmail.com) 12/9/2005
SettingItemGroup group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
int groupBase = (int) group;
// end of modification
// Set Editor Settings jviladiu@portalservices.net 2004/07/30
// modified by Hongwei Shen
//HtmlEditorDataType.HtmlEditorSettings (this._baseSettings, SettingItemGroup.MODULE_SPECIAL_SETTINGS);
HtmlEditorDataType.HtmlEditorSettings(_baseSettings, group);
// end of modification
//Switches date display on/off
SettingItem ShowDate = new SettingItem(new BooleanDataType());
ShowDate.Value = "True";
ShowDate.EnglishName = "Show Date";
// modified by Hongwei Shen
// ShowDate.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
// ShowDate.Order = 10;
ShowDate.Group = group;
ShowDate.Order = groupBase + 20;
// end of midification
_baseSettings.Add("ShowDate", ShowDate);
//Added by Rob Siera
SettingItem DefaultVisibleDays = new SettingItem(new IntegerDataType());
DefaultVisibleDays.Value = "90";
DefaultVisibleDays.EnglishName = "Default Days Visible";
// modified by Hongwei Shen
// DefaultVisibleDays.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
// DefaultVisibleDays.Order = 20;
DefaultVisibleDays.Group = group;
DefaultVisibleDays.Order = groupBase + 25;
// end of midification
_baseSettings.Add("DefaultVisibleDays", DefaultVisibleDays);
SettingItem RichAbstract = new SettingItem(new BooleanDataType());
RichAbstract.Value = "True";
RichAbstract.EnglishName = "Rich Abstract";
RichAbstract.Description = "User rich editor for abstract";
// modified by Hongwei Shen
// RichAbstract.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
// RichAbstract.Order = 30;
RichAbstract.Group = group;
RichAbstract.Order = groupBase + 30;
// end of midification
_baseSettings.Add("ARTICLES_RICHABSTRACT", RichAbstract);
UsersDB users = new UsersDB();
SettingItem RolesViewExpiredItems =
new SettingItem(
new CheckBoxListDataType(users.GetPortalRoles(portalSettings.PortalAlias), "RoleName", "RoleName"));
RolesViewExpiredItems.Value = "Admins";
RolesViewExpiredItems.EnglishName = "Expired items visible to";
RolesViewExpiredItems.Description = "Role that can see expire items";
// modified by Hongwei Shen
// RolesViewExpiredItems.Group = SettingItemGroup.MODULE_SPECIAL_SETTINGS;
// RolesViewExpiredItems.Order = 40;
RolesViewExpiredItems.Group = group;
RolesViewExpiredItems.Order = groupBase + 40;
// end of midification
_baseSettings.Add("EXPIRED_PERMISSION_ROLE", RolesViewExpiredItems);
}
}
#region General Implementation
/// <summary>
/// GUID of module (mandatory)
/// </summary>
/// <value></value>
public override Guid GuidID
{
get { return new Guid("{87303CF7-76D0-49B1-A7E7-A5C8E26415BA}"); }
}
#region Search Implementation
/// <summary>
/// Searchable module
/// </summary>
/// <value></value>
public override bool Searchable
{
get { return true; }
}
/// <summary>
/// Searchable module implementation
/// </summary>
/// <param name="portalID">The portal ID</param>
/// <param name="userID">ID of the user is searching</param>
/// <param name="searchString">The text to search</param>
/// <param name="searchField">The fields where perfoming the search</param>
/// <returns>
/// The SELECT sql to perform a search on the current module
/// </returns>
public override string SearchSqlSelect(int portalID, int userID, string searchString, string searchField)
{
SearchDefinition s =
new SearchDefinition("rb_Articles", "Title", "Abstract", "CreatedByUser", "CreatedDate", searchField);
//Add extra search fields here, this way
s.ArrSearchFields.Add("itm.Description");
return s.SearchSqlSelect(portalID, userID, searchString);
}
#endregion
# region Install / Uninstall Implementation
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Install(IDictionary stateSaver)
{
string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "install.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
/// <summary>
/// Unknown
/// </summary>
/// <param name="stateSaver"></param>
public override void Uninstall(IDictionary stateSaver)
{
string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "uninstall.sql");
ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true);
if (errors.Count > 0)
{
// Call rollback
throw new Exception("Error occurred:" + errors[0].ToString());
}
}
# endregion
#endregion
#region Web Form Designer generated code
/// <summary>
/// Raises Init event
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
this.Load += new EventHandler(Page_Load);
// View state is not needed here, so we are disabling. - jminond
this.myDataList.EnableViewState = false;
// Add support for the edit page
this.AddText = "ADD_ARTICLE";
this.AddUrl = "~/DesktopModules/Articles/ArticlesEdit.aspx";
base.OnInit(e);
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Windows;
using Microsoft.Practices.ServiceLocation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Prism.Events;
using Prism.Logging;
using Prism.Mef.Modularity;
using Prism.Modularity;
using Prism.Regions;
using Prism.Regions.Behaviors;
namespace Prism.Mef.Wpf.Tests
{
[TestClass]
public class MefBootstrapperFixture
{
[TestMethod]
public void ContainerDefaultsToNull()
{
var bootstrapper = new DefaultMefBootstrapper();
var container = bootstrapper.BaseContainer;
Assert.IsNull(container);
}
[TestMethod]
public void CanCreateConcreteBootstrapper()
{
new DefaultMefBootstrapper();
}
[TestMethod]
public void AggregateCatalogDefaultsToNull()
{
var bootstrapper = new DefaultMefBootstrapper();
Assert.IsNull(bootstrapper.BaseAggregateCatalog);
}
[TestMethod]
public void CreateAggregateCatalogShouldInitializeCatalog()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.CallCreateAggregateCatalog();
Assert.IsNotNull(bootstrapper.BaseAggregateCatalog);
}
[TestMethod]
public void CreateContainerShouldInitializeContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.CallCreateContainer();
Assert.IsNotNull(bootstrapper.BaseContainer);
Assert.IsInstanceOfType(bootstrapper.BaseContainer, typeof(CompositionContainer));
}
[TestMethod]
public void CreateContainerShouldNotInitializeContainerProviders()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.CallCreateContainer();
Assert.AreEqual(0, bootstrapper.BaseContainer.Providers.Count);
}
[TestMethod]
public void ConfigureContainerAddsMefServiceLocatorAdapterToContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.CallCreateLogger();
bootstrapper.CallCreateAggregateCatalog();
bootstrapper.CallCreateModuleCatalog();
bootstrapper.CallCreateContainer();
bootstrapper.CallConfigureContainer();
var returnedServiceLocatorAdapter = bootstrapper.BaseContainer.GetExportedValue<IServiceLocator>();
Assert.IsNotNull(returnedServiceLocatorAdapter);
Assert.AreEqual(typeof(MefServiceLocatorAdapter), returnedServiceLocatorAdapter.GetType());
}
[TestMethod]
public void ConfigureContainerAddsAggregateCatalogToContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.CallCreateLogger();
bootstrapper.CallCreateAggregateCatalog();
bootstrapper.CallCreateModuleCatalog();
bootstrapper.CallCreateContainer();
bootstrapper.CallConfigureContainer();
var returnedCatalog = bootstrapper.BaseContainer.GetExportedValue<AggregateCatalog>();
Assert.IsNotNull(returnedCatalog);
Assert.AreEqual(typeof(AggregateCatalog), returnedCatalog.GetType());
}
[TestMethod]
public void ConfigureContainerAddsModuleCatalogToContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.CallCreateLogger();
bootstrapper.CallCreateAggregateCatalog();
bootstrapper.CallCreateModuleCatalog();
bootstrapper.CallCreateContainer();
bootstrapper.CallConfigureContainer();
var returnedCatalog = bootstrapper.BaseContainer.GetExportedValue<IModuleCatalog>();
Assert.IsNotNull(returnedCatalog);
Assert.IsTrue(returnedCatalog is IModuleCatalog);
}
[TestMethod]
public void ConfigureContainerAddsLoggerFacadeToContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.CallCreateLogger();
bootstrapper.CallCreateAggregateCatalog();
bootstrapper.CallCreateModuleCatalog();
bootstrapper.CallCreateContainer();
bootstrapper.CallConfigureContainer();
var returnedCatalog = bootstrapper.BaseContainer.GetExportedValue<ILoggerFacade>();
Assert.IsNotNull(returnedCatalog);
Assert.IsTrue(returnedCatalog is ILoggerFacade);
}
[TestMethod]
public void InitializeShellComposesShell()
{
var bootstrapper = new DefaultMefBootstrapper();
var container = new CompositionContainer();
var shell = new DefaultShell();
bootstrapper.BaseContainer = container;
bootstrapper.BaseShell = shell;
bootstrapper.CallInitializeShell();
Assert.IsTrue(shell.AreImportsSatisfied);
}
[TestMethod]
public void ModuleManagerRunCalled()
{
var bootstrapper = new DefaultMefBootstrapper();
var container = new CompositionContainer();
Mock<IModuleManager> mockModuleManager = SetupModuleManager(container);
bootstrapper.BaseContainer = container;
bootstrapper.CallInitializeModules();
mockModuleManager.Verify(mm => mm.Run(), Times.Once());
}
[TestMethod]
public void SingleIModuleManagerIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<IModuleManager>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleSelectorItemsSourceSyncBehaviorIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<SelectorItemsSourceSyncBehavior>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleMefFileModuleTypeLoaderIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<MefFileModuleTypeLoader>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleIRegionViewRegistryIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<IRegionViewRegistry>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleContentControlRegionAdapterIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<ContentControlRegionAdapter>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleIModuleInitializerIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<IModuleInitializer>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleIEventAggregatorIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<IEventAggregator>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleSelectorRegionAdapterIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<SelectorRegionAdapter>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleBindRegionContextToDependencyObjectBehaviorIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<BindRegionContextToDependencyObjectBehavior>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleIRegionManagerIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<IRegionManager>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleRegionAdapterMappingsIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<RegionAdapterMappings>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleItemsControlRegionAdapterIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<ItemsControlRegionAdapter>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleSyncRegionContextWithHostBehaviorIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<SyncRegionContextWithHostBehavior>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleRegionManagerRegistrationBehaviorIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<RegionManagerRegistrationBehavior>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleDelayedRegionCreationBehaviorIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<DelayedRegionCreationBehavior>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleAutoPopulateRegionBehaviorIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<AutoPopulateRegionBehavior>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleRegionActiveAwareBehaviorIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<RegionActiveAwareBehavior>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void SingleIRegionBehaviorFactoryIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<IRegionBehaviorFactory>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void RegionLifetimeBehaviorIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<RegionMemberLifetimeBehavior>();
Assert.IsNotNull(exported);
}
[TestMethod]
public void RegionNavigationServiceIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var actual1 = bootstrapper.BaseContainer.GetExportedValue<IRegionNavigationService>();
var actual2 = bootstrapper.BaseContainer.GetExportedValue<IRegionNavigationService>();
Assert.IsNotNull(actual1);
Assert.IsNotNull(actual2);
Assert.AreNotSame(actual1, actual2);
}
[TestMethod]
public void RegionNavigationJournalIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var actual1 = bootstrapper.BaseContainer.GetExportedValue<IRegionNavigationJournal>();
var actual2 = bootstrapper.BaseContainer.GetExportedValue<IRegionNavigationJournal>();
Assert.IsNotNull(actual1);
Assert.IsNotNull(actual2);
Assert.AreNotSame(actual1, actual2);
}
[TestMethod]
public void RegionNavigationJournalEntryIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var actual1 = bootstrapper.BaseContainer.GetExportedValue<IRegionNavigationJournalEntry>();
var actual2 = bootstrapper.BaseContainer.GetExportedValue<IRegionNavigationJournalEntry>();
Assert.IsNotNull(actual1);
Assert.IsNotNull(actual2);
Assert.AreNotSame(actual1, actual2);
}
[TestMethod]
public void SingleNavigationTargetHandlerIsRegisteredWithContainer()
{
var bootstrapper = new DefaultMefBootstrapper();
bootstrapper.Run();
var exported = bootstrapper.BaseContainer.GetExportedValue<IRegionNavigationContentLoader>();
Assert.IsNotNull(exported);
}
private static Mock<IModuleManager> SetupModuleManager(CompositionContainer container)
{
Mock<IModuleManager> mockModuleManager = new Mock<IModuleManager>();
container.ComposeExportedValue<IModuleManager>(mockModuleManager.Object);
return mockModuleManager;
}
private static void SetupRegionBehaviorAdapters(CompositionContainer container)
{
var regionBehaviorFactory = new RegionBehaviorFactory(new MefServiceLocatorAdapter(container));
container.ComposeExportedValue<SelectorRegionAdapter>(new SelectorRegionAdapter(regionBehaviorFactory));
container.ComposeExportedValue<ItemsControlRegionAdapter>(new ItemsControlRegionAdapter(regionBehaviorFactory));
container.ComposeExportedValue<ContentControlRegionAdapter>(new ContentControlRegionAdapter(regionBehaviorFactory));
container.ComposeExportedValue<RegionAdapterMappings>(new RegionAdapterMappings());
}
private class DefaultShell : DependencyObject, IPartImportsSatisfiedNotification
{
public bool AreImportsSatisfied { get; set; }
public void OnImportsSatisfied()
{
this.AreImportsSatisfied = true;
}
}
}
internal class DefaultMefBootstrapper : MefBootstrapper
{
public bool InitializeModulesCalled;
public bool CreateAggregateCatalogCalled;
public bool CreateModuleCatalogCalled;
public bool ConfigureRegionAdapterMappingsCalled;
public bool ConfigureAggregateCatalogCalled;
public bool ConfigureModuleCatalogCalled;
public bool CreateContainerCalled;
public bool ConfigureContainerCalled;
public bool ConfigureViewModelLocatorCalled;
public bool ConfigureDefaultRegionBehaviorsCalled;
public bool RegisterFrameworkExceptionTypesCalled;
public bool CreateShellCalled;
public bool InitializeShellCalled;
public bool CreateLoggerCalled;
public TestLogger TestLog = new TestLogger();
public DependencyObject ShellObject = null;
public List<string> MethodCalls = new List<string>();
public RegionAdapterMappings DefaultRegionAdapterMappings;
public IRegionBehaviorFactory DefaultRegionBehaviorTypes;
public bool ConfigureServiceLocatorCalled;
public DefaultMefBootstrapper()
{
}
public ILoggerFacade BaseLogger
{
get
{
return base.Logger;
}
}
public CompositionContainer BaseContainer
{
get { return base.Container; }
set { base.Container = value; }
}
public AggregateCatalog BaseAggregateCatalog
{
get { return base.AggregateCatalog; }
set { base.AggregateCatalog = value; }
}
public IModuleCatalog BaseModuleCatalog
{
get { return base.ModuleCatalog; }
set { base.ModuleCatalog = value; }
}
public DependencyObject BaseShell
{
get { return base.Shell; }
set { base.Shell = value; }
}
protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
this.ConfigureRegionAdapterMappingsCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
DefaultRegionAdapterMappings = base.ConfigureRegionAdapterMappings();
return DefaultRegionAdapterMappings;
}
protected override DependencyObject CreateShell()
{
this.CreateShellCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
return this.ShellObject;
}
protected override IRegionBehaviorFactory ConfigureDefaultRegionBehaviors()
{
this.ConfigureDefaultRegionBehaviorsCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
this.DefaultRegionBehaviorTypes = base.ConfigureDefaultRegionBehaviors();
return this.DefaultRegionBehaviorTypes;
}
public void CallInitializeModules()
{
base.InitializeModules();
}
public CompositionContainer CallCreateContainer()
{
this.Container = base.CreateContainer();
return this.Container;
}
public void CallCreateAggregateCatalog()
{
this.AggregateCatalog = base.CreateAggregateCatalog();
}
public void CallCreateModuleCatalog()
{
this.ModuleCatalog = base.CreateModuleCatalog();
}
public void CallCreateLogger()
{
this.Logger = this.CreateLogger();
}
protected override ILoggerFacade CreateLogger()
{
this.CreateLoggerCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
return this.TestLog;
}
public void CallConfigureContainer()
{
base.ConfigureContainer();
}
public void CallInitializeShell()
{
base.InitializeShell();
}
public void CallConfigureServiceLocator()
{
base.ConfigureServiceLocator();
}
protected override AggregateCatalog CreateAggregateCatalog()
{
this.CreateAggregateCatalogCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
return base.CreateAggregateCatalog();
}
protected override void ConfigureAggregateCatalog()
{
this.ConfigureAggregateCatalogCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
// no op
}
protected override void ConfigureModuleCatalog()
{
this.ConfigureModuleCatalogCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
base.ConfigureModuleCatalog();
}
protected override CompositionContainer CreateContainer()
{
this.CreateContainerCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
return base.CreateContainer();
}
protected override void ConfigureContainer()
{
this.ConfigureContainerCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
base.ConfigureContainer();
}
protected override void RegisterFrameworkExceptionTypes()
{
this.RegisterFrameworkExceptionTypesCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
}
protected override void InitializeShell()
{
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
this.InitializeShellCalled = true;
base.InitializeShell();
}
protected override void InitializeModules()
{
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
this.InitializeModulesCalled = true;
base.InitializeModules();
}
protected override IModuleCatalog CreateModuleCatalog()
{
this.CreateModuleCatalogCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
return base.CreateModuleCatalog();
}
protected override void ConfigureServiceLocator()
{
this.ConfigureServiceLocatorCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
base.ConfigureServiceLocator();
}
protected override void ConfigureViewModelLocator()
{
this.ConfigureViewModelLocatorCalled = true;
this.MethodCalls.Add(System.Reflection.MethodBase.GetCurrentMethod().Name);
base.ConfigureViewModelLocator();
}
}
}
| |
// 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.AppDomain.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
{
sealed public partial class AppDomain : MarshalByRefObject, _AppDomain, System.Security.IEvidenceFactory
{
#region Methods and constructors
internal AppDomain()
{
}
public void AppendPrivatePath(string path)
{
}
public string ApplyPolicy(string assemblyName)
{
return default(string);
}
public void ClearPrivatePath()
{
}
public void ClearShadowCopyPath()
{
}
public System.Runtime.Remoting.ObjectHandle CreateComInstanceFrom(string assemblyName, string typeName)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public System.Runtime.Remoting.ObjectHandle CreateComInstanceFrom(string assemblyFile, string typeName, byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static AppDomain CreateDomain(string friendlyName, System.Security.Policy.Evidence securityInfo)
{
return default(AppDomain);
}
public static AppDomain CreateDomain(string friendlyName, System.Security.Policy.Evidence securityInfo, string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles, AppDomainInitializer adInit, string[] adInitArgs)
{
return default(AppDomain);
}
public static AppDomain CreateDomain(string friendlyName)
{
return default(AppDomain);
}
public static AppDomain CreateDomain(string friendlyName, System.Security.Policy.Evidence securityInfo, string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)
{
return default(AppDomain);
}
public static AppDomain CreateDomain(string friendlyName, System.Security.Policy.Evidence securityInfo, AppDomainSetup info, System.Security.PermissionSet grantSet, System.Security.Policy.StrongName[] fullTrustAssemblies)
{
Contract.Ensures((fullTrustAssemblies.Length - Contract.OldValue(fullTrustAssemblies.Length)) <= 0);
return default(AppDomain);
}
public static AppDomain CreateDomain(string friendlyName, System.Security.Policy.Evidence securityInfo, AppDomainSetup info)
{
return default(AppDomain);
}
public System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName, Object[] activationAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public Object CreateInstanceAndUnwrap(string assemblyName, string typeName)
{
return default(Object);
}
public Object CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes)
{
return default(Object);
}
public Object CreateInstanceAndUnwrap(string assemblyName, string typeName, Object[] activationAttributes)
{
return default(Object);
}
public Object CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes)
{
return default(Object);
}
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, Object[] activationAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public Object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes)
{
return default(Object);
}
public Object CreateInstanceFromAndUnwrap(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes)
{
return default(Object);
}
public Object CreateInstanceFromAndUnwrap(string assemblyName, string typeName)
{
return default(Object);
}
public Object CreateInstanceFromAndUnwrap(string assemblyName, string typeName, Object[] activationAttributes)
{
return default(Object);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, bool isSynchronized, IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions, bool isSynchronized)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions, bool isSynchronized, IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes, System.Security.SecurityContextSource securityContextSource)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, IEnumerable<System.Reflection.Emit.CustomAttributeBuilder> assemblyAttributes)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly(System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence)
{
return default(System.Reflection.Emit.AssemblyBuilder);
}
public void DoCallBack(CrossAppDomainDelegate callBackDelegate)
{
}
public int ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args)
{
return default(int);
}
public int ExecuteAssembly(string assemblyFile, string[] args, byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm)
{
Contract.Ensures((args.Length - Contract.OldValue(args.Length)) <= 0);
return default(int);
}
public int ExecuteAssembly(string assemblyFile, string[] args)
{
Contract.Ensures((args.Length - Contract.OldValue(args.Length)) <= 0);
return default(int);
}
public int ExecuteAssembly(string assemblyFile)
{
return default(int);
}
public int ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args, byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm)
{
Contract.Ensures((args.Length - Contract.OldValue(args.Length)) <= 0);
return default(int);
}
public int ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity)
{
return default(int);
}
public int ExecuteAssemblyByName(string assemblyName, System.Security.Policy.Evidence assemblySecurity)
{
return default(int);
}
public int ExecuteAssemblyByName(string assemblyName)
{
return default(int);
}
public int ExecuteAssemblyByName(System.Reflection.AssemblyName assemblyName, System.Security.Policy.Evidence assemblySecurity, string[] args)
{
Contract.Ensures((args.Length - Contract.OldValue(args.Length)) <= 0);
return default(int);
}
public int ExecuteAssemblyByName(System.Reflection.AssemblyName assemblyName, string[] args)
{
Contract.Ensures((args.Length - Contract.OldValue(args.Length)) <= 0);
return default(int);
}
public int ExecuteAssemblyByName(string assemblyName, System.Security.Policy.Evidence assemblySecurity, string[] args)
{
Contract.Ensures((args.Length - Contract.OldValue(args.Length)) <= 0);
return default(int);
}
public int ExecuteAssemblyByName(string assemblyName, string[] args)
{
Contract.Ensures((args.Length - Contract.OldValue(args.Length)) <= 0);
return default(int);
}
public System.Reflection.Assembly[] GetAssemblies()
{
return default(System.Reflection.Assembly[]);
}
public static int GetCurrentThreadId()
{
return default(int);
}
public Object GetData(string name)
{
return default(Object);
}
public Type GetType()
{
return default(Type);
}
public override Object InitializeLifetimeService()
{
return default(Object);
}
public Nullable<bool> IsCompatibilitySwitchSet(string value)
{
return default(Nullable<bool>);
}
public bool IsDefaultAppDomain()
{
return default(bool);
}
public bool IsFinalizingForUnload()
{
return default(bool);
}
public System.Reflection.Assembly Load(string assemblyString, System.Security.Policy.Evidence assemblySecurity)
{
return default(System.Reflection.Assembly);
}
public System.Reflection.Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore)
{
return default(System.Reflection.Assembly);
}
public System.Reflection.Assembly Load(byte[] rawAssembly, byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence)
{
return default(System.Reflection.Assembly);
}
public System.Reflection.Assembly Load(System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity)
{
return default(System.Reflection.Assembly);
}
public System.Reflection.Assembly Load(byte[] rawAssembly)
{
return default(System.Reflection.Assembly);
}
public System.Reflection.Assembly Load(System.Reflection.AssemblyName assemblyRef)
{
return default(System.Reflection.Assembly);
}
public System.Reflection.Assembly Load(string assemblyString)
{
return default(System.Reflection.Assembly);
}
public System.Reflection.Assembly[] ReflectionOnlyGetAssemblies()
{
return default(System.Reflection.Assembly[]);
}
public void SetAppDomainPolicy(System.Security.Policy.PolicyLevel domainPolicy)
{
}
public void SetCachePath(string path)
{
}
public void SetData(string name, Object data, System.Security.IPermission permission)
{
}
public void SetData(string name, Object data)
{
}
public void SetDynamicBase(string path)
{
}
public void SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy policy)
{
}
public void SetShadowCopyFiles()
{
}
public void SetShadowCopyPath(string path)
{
}
public void SetThreadPrincipal(System.Security.Principal.IPrincipal principal)
{
}
void System._AppDomain.GetIDsOfNames(ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
}
void System._AppDomain.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
}
void System._AppDomain.GetTypeInfoCount(out uint pcTInfo)
{
pcTInfo = default(uint);
}
void System._AppDomain.Invoke(uint dispIdMember, ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
}
public override string ToString()
{
return default(string);
}
public static void Unload(AppDomain domain)
{
}
#endregion
#region Properties and indexers
public ActivationContext ActivationContext
{
get
{
return default(ActivationContext);
}
}
public ApplicationIdentity ApplicationIdentity
{
get
{
return default(ApplicationIdentity);
}
}
public System.Security.Policy.ApplicationTrust ApplicationTrust
{
get
{
return default(System.Security.Policy.ApplicationTrust);
}
}
public string BaseDirectory
{
get
{
return default(string);
}
}
public static System.AppDomain CurrentDomain
{
get
{
return default(System.AppDomain);
}
}
public AppDomainManager DomainManager
{
get
{
return default(AppDomainManager);
}
}
public string DynamicDirectory
{
get
{
return default(string);
}
}
public System.Security.Policy.Evidence Evidence
{
get
{
return default(System.Security.Policy.Evidence);
}
}
public string FriendlyName
{
get
{
return default(string);
}
}
public int Id
{
get
{
return default(int);
}
}
public bool IsFullyTrusted
{
get
{
return default(bool);
}
}
public bool IsHomogenous
{
get
{
return default(bool);
}
}
public static bool MonitoringIsEnabled
{
get
{
return default(bool);
}
set
{
}
}
public long MonitoringSurvivedMemorySize
{
get
{
return default(long);
}
}
public static long MonitoringSurvivedProcessMemorySize
{
get
{
return default(long);
}
}
public long MonitoringTotalAllocatedMemorySize
{
get
{
return default(long);
}
}
public TimeSpan MonitoringTotalProcessorTime
{
get
{
return default(TimeSpan);
}
}
public System.Security.PermissionSet PermissionSet
{
get
{
return default(System.Security.PermissionSet);
}
}
public string RelativeSearchPath
{
get
{
return default(string);
}
}
public AppDomainSetup SetupInformation
{
get
{
Contract.Ensures(Contract.Result<System.AppDomainSetup>() != null);
return default(AppDomainSetup);
}
}
public bool ShadowCopyFiles
{
get
{
return default(bool);
}
}
#endregion
#region Events
public event AssemblyLoadEventHandler AssemblyLoad
{
add
{
}
remove
{
}
}
public event ResolveEventHandler AssemblyResolve
{
add
{
}
remove
{
}
}
public event EventHandler DomainUnload
{
add
{
}
remove
{
}
}
public event EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException
{
add
{
}
remove
{
}
}
public event EventHandler ProcessExit
{
add
{
}
remove
{
}
}
public event ResolveEventHandler ReflectionOnlyAssemblyResolve
{
add
{
}
remove
{
}
}
public event ResolveEventHandler ResourceResolve
{
add
{
}
remove
{
}
}
public event ResolveEventHandler TypeResolve
{
add
{
}
remove
{
}
}
public event UnhandledExceptionEventHandler UnhandledException
{
add
{
}
remove
{
}
}
#endregion
}
}
| |
//
// System.Web.UI.WebControls.DropDownList.cs
//
// Authors:
// Gaurav Vaish (gvaish@iitk.ac.in)
// Andreas Nahr (ClassDevelopment@A-SoftTech.com)
//
// (C) Gaurav Vaish (2002)
// (C) 2003 Andreas Nahr
//
//
// 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.Specialized;
using System.ComponentModel;
using System.Drawing;
using System.Web;
using System.Web.UI;
namespace System.Web.UI.WebControls
{
[ValidationProperty("SelectedItem")]
public class DropDownList : ListControl, IPostBackDataHandler
#if NET_2_0
, IEditableTextControl
#endif
{
public DropDownList(): base()
{
}
[Browsable (false)]
public override Color BorderColor
{
get
{
return base.BorderColor;
}
set
{
base.BorderColor = value;
}
}
[Browsable (false)]
public override BorderStyle BorderStyle
{
get
{
return base.BorderStyle;
}
set
{
base.BorderStyle = value;
}
}
[Browsable (false)]
public override Unit BorderWidth
{
get
{
return base.BorderWidth;
}
set
{
base.BorderWidth = value;
}
}
[DefaultValue (0), WebCategory ("Misc")]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription ("The index number of the currently selected ListItem.")]
public override int SelectedIndex
{
get
{
int index = base.SelectedIndex;
if (index < 0 && Items.Count > 0) {
index = 0;
Items [0].Selected = true;
}
return index;
}
set
{
base.SelectedIndex = value;
}
}
#if !NET_2_0
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[Bindable (false), EditorBrowsable (EditorBrowsableState.Never)]
public override string ToolTip
{
// MS ignores the tooltip for this one
get {
return String.Empty;
}
set {
}
}
#endif
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
if(Page != null)
{
Page.VerifyRenderingInServerForm(this);
}
writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);
base.AddAttributesToRender(writer);
if(AutoPostBack && Page != null)
{
writer.AddAttribute(HtmlTextWriterAttribute.Onchange, Page.ClientScript.GetPostBackClientEvent(this,""));
writer.AddAttribute("language", "javascript");
}
}
protected override ControlCollection CreateControlCollection()
{
return new EmptyControlCollection(this);
}
#if !NET_2_0
protected override void RenderContents(HtmlTextWriter writer)
{
if(Items != null)
{
bool selected = false;
foreach(ListItem current in Items)
{
writer.WriteBeginTag("option");
if(current.Selected)
{
if(selected)
{
throw new HttpException(HttpRuntime.FormatResourceString("Cannot_Multiselect_In_DropDownList"));
}
selected = true;
writer.WriteAttribute("selected", "selected", false);
}
writer.WriteAttribute("value", current.Value, true);
writer.Write('>');
HttpUtility.HtmlEncode(current.Text, writer);
writer.WriteEndTag("option");
writer.WriteLine();
}
}
}
#else
protected internal override void VerifyMultiSelect ()
{
throw new HttpException(HttpRuntime.FormatResourceString("Cannot_Multiselect_In_DropDownList"));
}
#endif
#if NET_2_0
bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
{
return LoadPostData (postDataKey, postCollection);
}
protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
#else
bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
#endif
{
string[] vals = postCollection.GetValues(postDataKey);
if(vals != null)
{
int index = Items.FindByValueInternal(vals[0]);
if(index != SelectedIndex)
{
SelectedIndex = index;
return true;
}
}
return false;
}
#if NET_2_0
void IPostBackDataHandler.RaisePostDataChangedEvent ()
{
RaisePostDataChangedEvent ();
}
protected virtual void RaisePostDataChangedEvent ()
{
if (CausesValidation)
Page.Validate (ValidationGroup);
OnSelectedIndexChanged (EventArgs.Empty);
}
#else
void IPostBackDataHandler.RaisePostDataChangedEvent ()
{
OnSelectedIndexChanged (EventArgs.Empty);
}
#endif
}
}
| |
/***************************************************************************
* PodcastManagerSource.cs
*
* Copyright (C) 2007 Michael C. Urbanski
* Written by Mike Urbanski <michael.c.urbanski@gmail.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections.Generic;
using Gtk;
using Gdk;
using Mono.Unix;
using Hyena;
using Hyena.Data;
using Hyena.Data.Gui;
using Hyena.Data.Sqlite;
using Banshee.Gui;
using Banshee.Base;
using Banshee.Query;
using Banshee.Database;
using Banshee.Collection;
using Banshee.ServiceStack;
using Banshee.Collection.Database;
using Banshee.Sources;
using Banshee.Sources.Gui;
using Banshee.Podcasting.Data;
using Migo.Syndication;
namespace Banshee.Podcasting.Gui
{
public class PodcastSource : Banshee.Library.LibrarySource
{
private PodcastFeedModel feed_model;
private PodcastUnheardFilterModel new_filter;
public override string DefaultBaseDirectory {
get {
// HACK there isn't an XDG_PODCASTS_DIR; propose it?
return XdgBaseDirectorySpec.GetUserDirectory ("XDG_PODCASTS_DIR", "Podcasts");
}
}
public override bool CanRename {
get { return false; }
}
public override bool CanAddTracks {
get { return true; }
}
public override bool CanRemoveTracks {
get { return false; }
}
public override bool CanDeleteTracks {
get { return false; }
}
public override bool CanShuffle {
get { return false; }
}
public PodcastFeedModel FeedModel {
get { return feed_model; }
}
public PodcastUnheardFilterModel NewFilter { get { return new_filter; } }
public override string PreferencesPageId {
get { return UniqueId; }
}
protected override string SectionName {
get { return Catalog.GetString ("Podcasts Folder"); }
}
class FeedMessage : SourceMessage
{
public Feed Feed { get; set; }
public bool Valid { get; private set; }
public FeedMessage (Source src, Feed feed) : base (src)
{
Feed = feed;
Update ();
}
public void Update ()
{
ClearActions ();
CanClose = Feed.LastDownloadError != FeedDownloadError.None;
IsSpinning = !CanClose;
var title = Feed.Title == Feed.UnknownPodcastTitle ? Feed.Url : Feed.Title;
if (CanClose) {
Text = String.Format (GetErrorText (), title);
SetIconName ("dialog-error");
AddAction (new MessageAction (Catalog.GetString ("Remove Podcast"), delegate {
Feed.Delete (true);
IsHidden = true;
}));
AddAction (new MessageAction (Catalog.GetString ("Disable Auto Updates"), delegate {
Feed.IsSubscribed = false;
Feed.Save ();
IsHidden = true;
}));
} else {
Text = String.Format (Catalog.GetString ("Loading {0}"), title);
}
// TODO Avoid nagging about an error more than once
Valid = true;//Feed.LastDownloadTime == DateTime.MinValue || Feed.LastDownloadTime > last_feed_nag;
}
private string GetErrorText ()
{
switch (Feed.LastDownloadError) {
case FeedDownloadError.DoesNotExist:
case FeedDownloadError.DownloadFailed:
return Catalog.GetString ("Network error updating {0}");
case FeedDownloadError.InvalidFeedFormat:
case FeedDownloadError.NormalizationFailed:
case FeedDownloadError.UnsupportedMsXml:
case FeedDownloadError.UnsupportedDtd:
return Catalog.GetString ("Parsing error updating {0}");
case FeedDownloadError.UnsupportedAuth:
return Catalog.GetString ("Authentication error updating {0}");
default:
return Catalog.GetString ("Error updating {0}");
}
}
}
//private static DateTime last_feed_nag = DateTime.MinValue;
private List<FeedMessage> feed_messages = new List<FeedMessage> ();
public void UpdateFeedMessages ()
{
var feeds = Feed.Provider.FetchAllMatching (
"IsSubscribed = 1 AND (LastDownloadTime = 0 OR LastDownloadError != 0) ORDER BY LastDownloadTime ASC").ToList ();
lock (feed_messages) {
var msgs = new List<FeedMessage> ();
var cur = CurrentMessage as FeedMessage;
if (cur != null && feeds.Contains (cur.Feed)) {
cur.Update ();
feeds.Remove (cur.Feed);
feed_messages.Remove (cur);
msgs.Add (cur);
}
feed_messages.ForEach (RemoveMessage);
feed_messages.Clear ();
foreach (var feed in feeds) {
var msg = new FeedMessage (this, feed);
if (msg.Valid) {
msgs.Add (msg);
PushMessage (msg);
}
}
feed_messages = msgs;
//last_feed_nag = DateTime.Now;
// If there's at least one new message, notify the user
if (msgs.Count > ((cur != null) ? 1 : 0)) {
NotifyUser ();
}
}
}
#region Constructors
public PodcastSource () : base (Catalog.GetString ("Podcasts"), "PodcastLibrary", 51)
{
TrackExternalObjectHandler = GetPodcastInfoObject;
TrackArtworkIdHandler = GetTrackArtworkId;
MediaTypes = TrackMediaAttributes.Podcast;
NotMediaTypes = TrackMediaAttributes.AudioBook;
SyncCondition = String.Format ("(substr({0}, 0, 4) != 'http' AND {1} = 0)",
BansheeQuery.UriField.Column, BansheeQuery.PlayCountField.Column);
TrackModel.Reloaded += OnReloaded;
Properties.SetString ("Icon.Name", "podcast");
Properties.Set<string> ("SearchEntryDescription", Catalog.GetString ("Search your podcasts"));
Properties.Set<string> ("SelectedTracksPropertiesActionLabel", Catalog.GetString ("Episode Properties"));
Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml");
Properties.Set<bool> ("ActiveSourceUIResourcePropagate", true);
Properties.Set<System.Reflection.Assembly> ("ActiveSourceUIResource.Assembly", typeof(PodcastSource).Assembly);
Properties.SetString ("GtkActionPath", "/PodcastSourcePopup");
Properties.Set<ISourceContents> ("Nereid.SourceContents", new LazyLoadSourceContents<PodcastSourceContents> ());
Properties.Set<bool> ("Nereid.SourceContentsPropagate", true);
Properties.SetString ("TrackView.ColumnControllerXml", String.Format (@"
<column-controller>
<add-all-defaults />
<column modify-default=""IndicatorColumn"">
<renderer type=""Banshee.Podcasting.Gui.ColumnCellPodcastStatusIndicator"" />
</column>
<remove-default column=""TrackColumn"" />
<remove-default column=""DiscColumn"" />
<remove-default column=""ComposerColumn"" />
<remove-default column=""ArtistColumn"" />
<column modify-default=""AlbumColumn"">
<title>{0}</title>
<long-title>{0}</long-title>
<sort-key>PodcastTitle</sort-key>
<renderer property=""ExternalObject.PodcastTitle""/>
</column>
<column modify-default=""DurationColumn"">
<visible>false</visible>
</column>
<column>
<visible>false</visible>
<title>{4}</title>
<renderer type=""Hyena.Data.Gui.ColumnCellText"" property=""ExternalObject.Description"" />
<sort-key>Description</sort-key>
</column>
<column>
<visible>false</visible>
<title>{2}</title>
<renderer type=""Banshee.Podcasting.Gui.ColumnCellYesNo"" property=""ExternalObject.IsNew"" />
<sort-key>IsNew</sort-key>
</column>
<column>
<visible>false</visible>
<title>{3}</title>
<renderer type=""Banshee.Podcasting.Gui.ColumnCellYesNo"" property=""ExternalObject.IsDownloaded"" />
<sort-key>IsDownloaded</sort-key>
</column>
<column>
<visible>true</visible>
<title>{1}</title>
<renderer type=""Banshee.Podcasting.Gui.ColumnCellPublished"" property=""ExternalObject.PublishedDate"" />
<sort-key>PublishedDate</sort-key>
</column>
<sort-column direction=""desc"">published_date</sort-column>
</column-controller>
",
Catalog.GetString ("Podcast"), Catalog.GetString ("Published"), Catalog.GetString ("New"),
Catalog.GetString ("Downloaded"), Catalog.GetString ("Description")
));
}
#endregion
private object GetPodcastInfoObject (DatabaseTrackInfo track)
{
return new PodcastTrackInfo (track);
}
private string GetTrackArtworkId (DatabaseTrackInfo track)
{
return PodcastService.ArtworkIdFor (PodcastTrackInfo.From (track).Feed);
}
protected override bool HasArtistAlbum {
get { return false; }
}
public override bool HasEditableTrackProperties {
get { return false; }
}
public override string GetPluralItemCountString (int count)
{
return Catalog.GetPluralString ("{0} episode", "{0} episodes", count);
}
public override bool AcceptsInputFromSource (Source source)
{
return false;
}
public PodcastTrackListModel PodcastTrackModel { get; private set; }
protected override DatabaseTrackListModel CreateTrackModelFor (DatabaseSource src)
{
var model = new PodcastTrackListModel (ServiceManager.DbConnection, DatabaseTrackInfo.Provider, src);
if (PodcastTrackModel == null) {
PodcastTrackModel = model;
}
return model;
}
protected override IEnumerable<IFilterListModel> CreateFiltersFor (DatabaseSource src)
{
PodcastFeedModel feed_model;
yield return new_filter = new PodcastUnheardFilterModel (src.DatabaseTrackModel);
yield return feed_model = new PodcastFeedModel (src, src.DatabaseTrackModel, ServiceManager.DbConnection, String.Format ("PodcastFeeds-{0}", src.UniqueId));
if (src == this) {
this.feed_model = feed_model;
AfterInitialized ();
}
}
void OnReloaded(object sender, EventArgs e)
{
for (int i=0; i < TrackModel.Count; i++) {
PodcastTrackInfo.From (TrackModel[i]);
}
}
// Probably don't want this -- do we want to allow actually removing the item? It will be
// repopulated the next time we update the podcast feed...
/*protected override void DeleteTrack (DatabaseTrackInfo track)
{
PodcastTrackInfo episode = track as PodcastTrackInfo;
if (episode != null) {
if (episode.Uri.IsFile)
base.DeleteTrack (track);
episode.Delete ();
episode.Item.Delete (false);
}
}*/
/*protected override void AddTrack (DatabaseTrackInfo track)
{
// TODO
// Need to create a Feed, FeedItem, and FeedEnclosure for this track for it to be
// considered a Podcast item
base.AddTrack (track);
}*/
public override bool ShowBrowser {
get { return true; }
}
/*public override IEnumerable<SmartPlaylistDefinition> DefaultSmartPlaylists {
get { return default_smart_playlists; }
}
private static SmartPlaylistDefinition [] default_smart_playlists = new SmartPlaylistDefinition [] {
new SmartPlaylistDefinition (
Catalog.GetString ("Favorites"),
Catalog.GetString ("Videos rated four and five stars"),
"rating>=4"),
new SmartPlaylistDefinition (
Catalog.GetString ("Unwatched"),
Catalog.GetString ("Videos that haven't been played yet"),
"plays=0"),
};*/
}
}
| |
/********************************************************************--
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Web.Services;
using System.Web.Services.Description;
using System.Web.Services.Discovery;
using System.Management;
using System.Management.Automation;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.CSharp;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using Dbg = System.Management.Automation;
using System.Runtime.InteropServices;
using System.Resources;
using Microsoft.Win32;
using System.Text.RegularExpressions;
namespace Microsoft.PowerShell.Commands
{
#region New-WebServiceProxy
/// <summary>
/// Cmdlet for new-WebService Proxy
/// </summary>
[Cmdlet(VerbsCommon.New, "WebServiceProxy", DefaultParameterSetName = "NoCredentials", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=135238")]
public sealed class NewWebServiceProxy : PSCmdlet
{
#region Parameters
/// <summary>
/// URI of the web service
/// </summary>
[Parameter(Mandatory = true, Position = 0)]
[ValidateNotNullOrEmpty]
[Alias("WL", "WSDL", "Path")]
public System.Uri Uri
{
get { return _uri; }
set
{
_uri = value;
}
}
private System.Uri _uri;
/// <summary>
/// Parameter Class name
/// </summary>
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty]
[Alias("FileName", "FN")]
public string Class
{
get { return _class; }
set
{
_class = value;
}
}
private string _class;
/// <summary>
/// namespace
/// </summary>
[Parameter(Position = 2)]
[ValidateNotNullOrEmpty]
[Alias("NS")]
public string Namespace
{
get { return _namespace; }
set
{
_namespace = value;
}
}
private string _namespace;
/// <summary>
/// Credential
/// </summary>
[Parameter(ParameterSetName = "Credential")]
[ValidateNotNullOrEmpty]
[Credential]
[Alias("Cred")]
public PSCredential Credential
{
get { return _credential; }
set
{
_credential = value;
}
}
private PSCredential _credential;
/// <summary>
/// use default credential..
/// </summary>
[Parameter(ParameterSetName = "UseDefaultCredential")]
[ValidateNotNull]
[Alias("UDC")]
public SwitchParameter UseDefaultCredential
{
get { return _usedefaultcredential; }
set
{
_usedefaultcredential = value;
}
}
private SwitchParameter _usedefaultcredential;
#endregion
#region overrides
/// <summary>
/// Cache for storing URIs.
/// </summary>
private static Dictionary<Uri, string> s_uriCache = new Dictionary<Uri, string>();
/// <summary>
/// Cache for storing sourcecodehashes.
/// </summary>
private static Dictionary<int, object> s_srccodeCache = new Dictionary<int, object>();
/// <summary>
/// holds the hash code of the source generated.
/// </summary>
private int _sourceHash;
/// <summary>
/// Random class
/// </summary>
private object _cachelock = new object();
private static Random s_rnd = new Random();
/// <summary>
/// BeginProcessing code
/// </summary>
protected override void BeginProcessing()
{
if (_uri.ToString().Trim().Length == 0)
{
Exception ex = new ArgumentException(WebServiceResources.InvalidUri);
ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidOperation, null);
ThrowTerminatingError(er);
}
//check if system.web is available.This assembly is not available in win server core.
string AssemblyString = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
try
{
Assembly webAssembly = Assembly.Load(AssemblyString);
}
catch (FileNotFoundException ex)
{
ErrorRecord er = new ErrorRecord(ex, "SystemWebAssemblyNotFound", ErrorCategory.ObjectNotFound, null);
er.ErrorDetails = new ErrorDetails(WebServiceResources.NotSupported);
ThrowTerminatingError(er);
}
int sourceCache = 0;
lock (s_uriCache)
{
if (s_uriCache.ContainsKey(_uri))
{
//if uri is present in the cache
string ns;
s_uriCache.TryGetValue(_uri, out ns);
string[] data = ns.Split('|');
if (string.IsNullOrEmpty(_namespace))
{
if (data[0].StartsWith("Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.", StringComparison.OrdinalIgnoreCase))
{
_namespace = data[0];
_class = data[1];
}
}
sourceCache = Int32.Parse(data[2].ToString(), CultureInfo.InvariantCulture);
}
}
if (string.IsNullOrEmpty(_namespace))
{
_namespace = "Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy" + GenerateRandomName();
}
//if class is null,generate a name for it
if (string.IsNullOrEmpty(_class))
{
_class = "MyClass" + GenerateRandomName();
}
Assembly webserviceproxy = GenerateWebServiceProxyAssembly(_namespace, _class);
if (webserviceproxy == null)
return;
Object instance = InstantinateWebServiceProxy(webserviceproxy);
//to set the credentials into the generated webproxy Object
PropertyInfo[] pinfo = instance.GetType().GetProperties();
foreach (PropertyInfo pr in pinfo)
{
if (pr.Name.Equals("UseDefaultCredentials", StringComparison.OrdinalIgnoreCase))
{
if (UseDefaultCredential.IsPresent)
{
bool flag = true;
pr.SetValue(instance, flag as object, null);
}
}
if (pr.Name.Equals("Credentials", StringComparison.OrdinalIgnoreCase))
{
if (Credential != null)
{
NetworkCredential cred = Credential.GetNetworkCredential();
pr.SetValue(instance, cred as object, null);
}
}
}
//disposing the entries in a cache
//Adding to Cache
lock (s_uriCache)
{
s_uriCache.Remove(_uri);
}
if (sourceCache > 0)
{
lock (_cachelock)
{
s_srccodeCache.Remove(sourceCache);
}
}
string key = string.Join("|", new string[] { _namespace, _class, _sourceHash.ToString(System.Globalization.CultureInfo.InvariantCulture) });
lock (s_uriCache)
{
s_uriCache.Add(_uri, key);
}
lock (_cachelock)
{
s_srccodeCache.Add(_sourceHash, instance);
}
WriteObject(instance, true);
}//End BeginProcessing()
#endregion
#region private
private static ulong s_sequenceNumber = 1;
private static object s_sequenceNumberLock = new object();
/// <summary>
/// Generates a random name
/// </summary>
/// <returns>string </returns>
private string GenerateRandomName()
{
string rndname = null;
string givenuri = _uri.ToString();
for (int i = 0; i < givenuri.Length; i++)
{
Int32 val = System.Convert.ToInt32(givenuri[i], CultureInfo.InvariantCulture);
if ((val >= 65 && val <= 90) || (val >= 48 && val <= 57) || (val >= 97 && val <= 122))
{
rndname += givenuri[i];
}
else
{
rndname += "_";
}
}
string sequenceString;
lock (s_sequenceNumberLock)
{
sequenceString = (s_sequenceNumber++).ToString(CultureInfo.InvariantCulture);
}
if (rndname.Length > 30)
{
return (sequenceString + rndname.Substring(rndname.Length - 30));
}
return (sequenceString + rndname);
}
/// <summary>
/// Generates the Assembly
/// </summary>
/// <param name="NameSpace"></param>
/// <param name="ClassName"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
private Assembly GenerateWebServiceProxyAssembly(string NameSpace, string ClassName)
{
DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
//if paramset is defualtcredential, set the flag in wcclient
if (_usedefaultcredential.IsPresent)
dcp.UseDefaultCredentials = true;
//if paramset is credential, assign the crdentials
if (ParameterSetName.Equals("Credential", StringComparison.OrdinalIgnoreCase))
dcp.Credentials = _credential.GetNetworkCredential();
try
{
dcp.AllowAutoRedirect = true;
dcp.DiscoverAny(_uri.ToString());
dcp.ResolveAll();
}
catch (WebException ex)
{
ErrorRecord er = new ErrorRecord(ex, "WebException", ErrorCategory.ObjectNotFound, _uri);
if (ex.InnerException != null)
er.ErrorDetails = new ErrorDetails(ex.InnerException.Message);
WriteError(er);
return null;
}
catch (InvalidOperationException ex)
{
ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _uri);
WriteError(er);
return null;
}
// create the namespace
CodeNamespace codeNS = new CodeNamespace();
if (!string.IsNullOrEmpty(NameSpace))
codeNS.Name = NameSpace;
//create the class and add it to the namespace
if (!string.IsNullOrEmpty(ClassName))
{
CodeTypeDeclaration codeClass = new CodeTypeDeclaration(ClassName);
codeClass.IsClass = true;
codeClass.Attributes = MemberAttributes.Public;
codeNS.Types.Add(codeClass);
}
//create a web reference to the uri docs
WebReference wref = new WebReference(dcp.Documents, codeNS);
WebReferenceCollection wrefs = new WebReferenceCollection();
wrefs.Add(wref);
//create a codecompileunit and add the namespace to it
CodeCompileUnit codecompileunit = new CodeCompileUnit();
codecompileunit.Namespaces.Add(codeNS);
WebReferenceOptions wrefOptions = new WebReferenceOptions();
wrefOptions.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateNewAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync | System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
wrefOptions.Verbose = true;
//create a csharpprovider and compile it
CSharpCodeProvider csharpprovider = new CSharpCodeProvider();
StringCollection Warnings = ServiceDescriptionImporter.GenerateWebReferences(wrefs, csharpprovider, codecompileunit, wrefOptions);
StringBuilder codegenerator = new StringBuilder();
StringWriter writer = new StringWriter(codegenerator, CultureInfo.InvariantCulture);
try
{
csharpprovider.GenerateCodeFromCompileUnit(codecompileunit, writer, null);
}
catch (NotImplementedException ex)
{
ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
WriteError(er);
}
//generate the hashcode of the CodeCompileUnit
_sourceHash = codegenerator.ToString().GetHashCode();
//if the sourcehash matches the hashcode in the cache,the proxy hasnt changed and so
// return the instance of th eproxy in the cache
if (s_srccodeCache.ContainsKey(_sourceHash))
{
object obj;
s_srccodeCache.TryGetValue(_sourceHash, out obj);
WriteObject(obj, true);
return null;
}
CompilerParameters options = new CompilerParameters();
CompilerResults results = null;
foreach (string warning in Warnings)
{
this.WriteWarning(warning);
}
// add the refernces to the required assemblies
options.ReferencedAssemblies.Add("System.dll");
options.ReferencedAssemblies.Add("System.Data.dll");
options.ReferencedAssemblies.Add("System.Xml.dll");
options.ReferencedAssemblies.Add("System.Web.Services.dll");
options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
GetReferencedAssemblies(typeof(Cmdlet).Assembly, options);
options.GenerateInMemory = true;
options.TreatWarningsAsErrors = false;
options.WarningLevel = 4;
options.GenerateExecutable = false;
try
{
results = csharpprovider.CompileAssemblyFromSource(options, codegenerator.ToString());
}
catch (NotImplementedException ex)
{
ErrorRecord er = new ErrorRecord(ex, "NotImplementedException", ErrorCategory.ObjectNotFound, _uri);
WriteError(er);
}
return results.CompiledAssembly;
}
/// <summary>
/// Function to add all the assemblies required to generate the web proxy
/// </summary>
/// <param name="assembly"></param>
/// <param name="parameters"></param>
private void GetReferencedAssemblies(Assembly assembly, CompilerParameters parameters)
{
if (!parameters.ReferencedAssemblies.Contains(assembly.Location))
{
string location = Path.GetFileName(assembly.Location);
if (!parameters.ReferencedAssemblies.Contains(location))
{
parameters.ReferencedAssemblies.Add(assembly.Location);
foreach (AssemblyName referencedAssembly in assembly.GetReferencedAssemblies())
GetReferencedAssemblies(Assembly.Load(referencedAssembly.FullName), parameters);
}
}
}
/// <summary>
/// Instantiates the object
/// if a type of WebServiceBindingAttribute is not found, throw an exception
/// </summary>
/// <param name="assembly"></param>
/// <returns></returns>
private object InstantinateWebServiceProxy(Assembly assembly)
{
Type proxyType = null;
//loop through the types of the assembly and identify the type having
// a web service binding attribute
foreach (Type type in assembly.GetTypes())
{
Object[] obj = type.GetCustomAttributes(typeof(WebServiceBindingAttribute), false);
if (obj.Length > 0)
{
proxyType = type;
break;
}
if (proxyType != null) break;
}
System.Management.Automation.Diagnostics.Assert(
proxyType != null,
"Proxy class should always get generated unless there were some errors earlier (in that case we shouldn't get here)");
return assembly.CreateInstance(proxyType.ToString());
}
#endregion
}//end class
#endregion
}//Microsoft.Powershell.commands
| |
// <copyright file="UserSvdTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// 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.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Factorization
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Svd factorization tests for a user matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class UserSvdTests
{
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = UserDefinedMatrix.Identity(order);
var factorSvd = matrixI.Svd();
var u = factorSvd.U;
var vt = factorSvd.VT;
var w = factorSvd.W;
Assert.AreEqual(matrixI.RowCount, u.RowCount);
Assert.AreEqual(matrixI.RowCount, u.ColumnCount);
Assert.AreEqual(matrixI.ColumnCount, vt.RowCount);
Assert.AreEqual(matrixI.ColumnCount, vt.ColumnCount);
Assert.AreEqual(matrixI.RowCount, w.RowCount);
Assert.AreEqual(matrixI.ColumnCount, w.ColumnCount);
for (var i = 0; i < w.RowCount; i++)
{
for (var j = 0; j < w.ColumnCount; j++)
{
Assert.AreEqual(i == j ? Complex.One : Complex.Zero, w[i, j]);
}
}
}
/// <summary>
/// Can factorize a random matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(10, 6)]
[TestCase(50, 48)]
[TestCase(100, 98)]
public void CanFactorizeRandomMatrix(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(row, column, 1).ToArray());
var factorSvd = matrixA.Svd();
var u = factorSvd.U;
var vt = factorSvd.VT;
var w = factorSvd.W;
// Make sure the U has the right dimensions.
Assert.AreEqual(row, u.RowCount);
Assert.AreEqual(row, u.ColumnCount);
// Make sure the VT has the right dimensions.
Assert.AreEqual(column, vt.RowCount);
Assert.AreEqual(column, vt.ColumnCount);
// Make sure the W has the right dimensions.
Assert.AreEqual(row, w.RowCount);
Assert.AreEqual(column, w.ColumnCount);
// Make sure the U*W*VT is the original matrix.
var matrix = u*w*vt;
for (var i = 0; i < matrix.RowCount; i++)
{
for (var j = 0; j < matrix.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(matrixA[i, j], matrix[i, j], 9);
}
}
}
/// <summary>
/// Can check rank of a non-square matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(10, 8)]
[TestCase(48, 52)]
[TestCase(100, 93)]
public void CanCheckRankOfNonSquare(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(row, column, 1).ToArray());
var factorSvd = matrixA.Svd();
var mn = Math.Min(row, column);
Assert.AreEqual(factorSvd.Rank, mn);
}
/// <summary>
/// Can check rank of a square matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(9)]
[TestCase(50)]
[TestCase(90)]
public void CanCheckRankSquare(int order)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(order, order, 1).ToArray());
var factorSvd = matrixA.Svd();
if (factorSvd.Determinant != 0)
{
Assert.AreEqual(factorSvd.Rank, order);
}
else
{
Assert.AreEqual(factorSvd.Rank, order - 1);
}
}
/// <summary>
/// Can check rank of a square singular matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanCheckRankOfSquareSingular(int order)
{
var matrixA = new UserDefinedMatrix(order, order);
matrixA[0, 0] = 1;
matrixA[order - 1, order - 1] = 1;
for (var i = 1; i < order - 1; i++)
{
matrixA[i, i - 1] = 1;
matrixA[i, i + 1] = 1;
matrixA[i - 1, i] = 1;
matrixA[i + 1, i] = 1;
}
var factorSvd = matrixA.Svd();
Assert.AreEqual(factorSvd.Determinant, Complex.Zero);
Assert.AreEqual(factorSvd.Rank, order - 1);
}
/// <summary>
/// Solve for matrix if vectors are not computed throws <c>InvalidOperationException</c>.
/// </summary>
[Test]
public void SolveMatrixIfVectorsNotComputedThrowsInvalidOperationException()
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(10, 9, 1).ToArray());
var factorSvd = matrixA.Svd(false);
var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(10, 9, 1).ToArray());
Assert.That(() => factorSvd.Solve(matrixB), Throws.InvalidOperationException);
}
/// <summary>
/// Solve for vector if vectors are not computed throws <c>InvalidOperationException</c>.
/// </summary>
[Test]
public void SolveVectorIfVectorsNotComputedThrowsInvalidOperationException()
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(10, 9, 1).ToArray());
var factorSvd = matrixA.Svd(false);
var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(9, 1).ToArray());
Assert.That(() => factorSvd.Solve(vectorb), Throws.InvalidOperationException);
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(9, 10)]
[TestCase(50, 50)]
[TestCase(90, 100)]
public void CanSolveForRandomVector(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(row, 1).ToArray());
var resultx = factorSvd.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(4, 4)]
[TestCase(7, 8)]
[TestCase(10, 10)]
[TestCase(45, 50)]
[TestCase(80, 100)]
public void CanSolveForRandomMatrix(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(row, column, 1).ToArray());
var matrixX = factorSvd.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(2, 2)]
[TestCase(5, 5)]
[TestCase(9, 10)]
[TestCase(50, 50)]
[TestCase(90, 100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var vectorb = new UserDefinedVector(Vector<Complex>.Build.Random(row, 1).ToArray());
var vectorbCopy = vectorb.Clone();
var resultx = new UserDefinedVector(column);
factorSvd.Solve(vectorb, resultx);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
AssertHelpers.AlmostEqual(vectorb[i], matrixBReconstruct[i], 10);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="row">Matrix row number.</param>
/// <param name="column">Matrix column number.</param>
[TestCase(1, 1)]
[TestCase(4, 4)]
[TestCase(7, 8)]
[TestCase(10, 10)]
[TestCase(45, 50)]
[TestCase(80, 100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int column)
{
var matrixA = new UserDefinedMatrix(Matrix<Complex>.Build.Random(row, column, 1).ToArray());
var matrixACopy = matrixA.Clone();
var factorSvd = matrixA.Svd();
var matrixB = new UserDefinedMatrix(Matrix<Complex>.Build.Random(row, column, 1).ToArray());
var matrixBCopy = matrixB.Clone();
var matrixX = new UserDefinedMatrix(column, column);
factorSvd.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
AssertHelpers.AlmostEqual(matrixB[i, j], matrixBReconstruct[i, j], 10);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
}
}
| |
/**
* Copyright 2010-present Facebook.
*
* 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 Android.App;
using Android.Content;
using Android.Graphics;
using Android.Locations;
using Android.OS;
using Android.Runtime;
using Android.Text;
using Android.Views;
using Android.Widget;
using Xamarin.Facebook;
using Xamarin.Facebook.Share.Widget;
using Xamarin.Facebook.Login.Widget;
using Xamarin.Facebook.AppEvents;
using Xamarin.Facebook.Share.Model;
using Xamarin.Facebook.Share;
using Xamarin.Facebook.Login;
using AndroidX.Fragment.App;
[assembly:Permission (Name = Android.Manifest.Permission.Internet)]
[assembly:Permission (Name = Android.Manifest.Permission.WriteExternalStorage)]
[assembly:MetaData ("com.facebook.sdk.ApplicationId", Value ="@string/app_id")]
[assembly:MetaData ("com.facebook.sdk.ApplicationName", Value ="@string/app_name")]
namespace HelloFacebookSample
{
[Activity (Label = "@string/app_name", MainLauncher = true, WindowSoftInputMode = SoftInput.AdjustResize)]
public class HelloFacebookSampleActivity : FragmentActivity
{
static readonly string [] PERMISSIONS = new [] { "publish_actions" };
static readonly Location SEATTLE_LOCATION = new Location ("") {
Latitude = (47.6097),
Longitude = (-122.3331)
};
const String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";
Button postStatusUpdateButton;
Button postPhotoButton;
ProfilePictureView profilePictureView;
TextView greeting;
PendingAction pendingAction = PendingAction.NONE;
bool canPresentShareDialog;
bool canPresentShareDialogWithPhotos;
ICallbackManager callbackManager;
ProfileTracker profileTracker;
ShareDialog shareDialog;
FacebookCallback<SharerResult> shareCallback;
enum PendingAction
{
NONE,
POST_PHOTO,
POST_STATUS_UPDATE
}
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
FacebookSdk.SdkInitialize (this.ApplicationContext);
callbackManager = CallbackManagerFactory.Create ();
var loginCallback = new FacebookCallback<LoginResult> {
HandleSuccess = loginResult => {
HandlePendingAction ();
UpdateUI ();
},
HandleCancel = () => {
if (pendingAction != PendingAction.NONE) {
ShowAlert (
GetString (Resource.String.cancelled),
GetString (Resource.String.permission_not_granted));
pendingAction = PendingAction.NONE;
}
UpdateUI ();
},
HandleError = loginError => {
if (pendingAction != PendingAction.NONE
&& loginError is FacebookAuthorizationException) {
ShowAlert (
GetString (Resource.String.cancelled),
GetString (Resource.String.permission_not_granted));
pendingAction = PendingAction.NONE;
}
UpdateUI ();
}
};
LoginManager.Instance.RegisterCallback (callbackManager, loginCallback);
shareCallback = new FacebookCallback<SharerResult> {
HandleSuccess = shareResult => {
Console.WriteLine ("HelloFacebook: Success!");
if (shareResult.PostId != null) {
var title = Parent.GetString (Resource.String.error);
var id = shareResult.PostId;
var alertMsg = Parent.GetString (Resource.String.successfully_posted_post, id);
ShowAlert (title, alertMsg);
}
},
HandleCancel = () => {
Console.WriteLine ("HelloFacebook: Canceled");
},
HandleError = shareError => {
Console.WriteLine ("HelloFacebook: Error: {0}", shareError);
var title = Parent.GetString (Resource.String.error);
var alertMsg = shareError.Message;
ShowAlert (title, alertMsg);
}
};
shareDialog = new ShareDialog (this);
shareDialog.RegisterCallback (callbackManager, shareCallback);
if (savedInstanceState != null) {
var name = savedInstanceState.GetString (PENDING_ACTION_BUNDLE_KEY);
pendingAction = (PendingAction)Enum.Parse (typeof(PendingAction), name);
}
SetContentView (Resource.Layout.main);
profileTracker = new CustomProfileTracker {
HandleCurrentProfileChanged = (oldProfile, currentProfile) => {
UpdateUI ();
HandlePendingAction ();
}
};
profilePictureView = FindViewById <ProfilePictureView> (Resource.Id.profilePicture);
greeting = FindViewById<TextView> (Resource.Id.greeting);
postStatusUpdateButton = FindViewById<Button> (Resource.Id.postStatusUpdateButton);
postStatusUpdateButton.Click += (sender, e) => {
PerformPublish (PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
};
postPhotoButton = FindViewById<Button> (Resource.Id.postPhotoButton);
postPhotoButton.Click += (sender, e) => {
PerformPublish (PendingAction.POST_PHOTO, canPresentShareDialogWithPhotos);
};
// Can we present the share dialog for regular links?
canPresentShareDialog = ShareDialog.CanShow (Java.Lang.Class.FromType (typeof(ShareLinkContent)));
// Can we present the share dialog for photos?
canPresentShareDialogWithPhotos = ShareDialog.CanShow (Java.Lang.Class.FromType (typeof(SharePhotoContent)));
}
void ShowAlert (string title, string msg, string buttonText = null)
{
new AlertDialog.Builder (Parent)
.SetTitle (title)
.SetMessage (msg)
.SetPositiveButton (buttonText, (s2, e2) => { })
.Show ();
}
protected override void OnResume ()
{
base.OnResume ();
AppEventsLogger.ActivateApp (this);
UpdateUI ();
}
protected override void OnSaveInstanceState (Bundle outState)
{
base.OnSaveInstanceState (outState);
outState.PutString (PENDING_ACTION_BUNDLE_KEY, pendingAction.ToString ());
}
protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult (requestCode, resultCode, data);
callbackManager.OnActivityResult (requestCode, (int)resultCode, data);
}
protected override void OnPause ()
{
base.OnPause ();
AppEventsLogger.DeactivateApp (this);
}
protected override void OnDestroy ()
{
base.OnDestroy ();
profileTracker.StopTracking ();
}
private void UpdateUI ()
{
var enableButtons = AccessToken.CurrentAccessToken != null;
postStatusUpdateButton.Enabled = (enableButtons || canPresentShareDialog);
postPhotoButton.Enabled = (enableButtons || canPresentShareDialogWithPhotos);
var profile = Profile.CurrentProfile;
if (enableButtons && profile != null) {
profilePictureView.ProfileId = profile.Id;
greeting.Text = GetString (Resource.String.hello_user, new Java.Lang.String (profile.FirstName));
} else {
profilePictureView.ProfileId = null;
greeting.Text = null;
}
}
private void HandlePendingAction ()
{
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case PendingAction.POST_PHOTO:
PostPhoto ();
break;
case PendingAction.POST_STATUS_UPDATE:
PostStatusUpdate ();
break;
}
}
void PostStatusUpdate ()
{
var profile = Profile.CurrentProfile;
var linkContent = new ShareLinkContent.Builder ()
.SetContentTitle ("Hello Facebook")
.SetContentDescription ("The 'Hello Facebook' sample showcases simple Facebook integration")
.SetContentUrl (Android.Net.Uri.Parse ("http://developer.facebook.com/docs/android"))
.JavaCast<ShareLinkContent.Builder> ()
.Build ();
if (canPresentShareDialog)
shareDialog.Show (linkContent);
else if (profile != null && HasPublishPermission ())
ShareApi.Share (linkContent, shareCallback);
else
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
private void PostPhoto ()
{
var image = BitmapFactory.DecodeResource (this.Resources, Resource.Drawable.icon);
var sharePhoto = new SharePhoto.Builder ()
.SetBitmap (image).Build ().JavaCast<SharePhoto> ();
var photos = new List<SharePhoto> ();
photos.Add (sharePhoto);
var sharePhotoContent = new SharePhotoContent.Builder ()
.SetPhotos (photos).Build ();
if (canPresentShareDialogWithPhotos)
shareDialog.Show (sharePhotoContent);
else if (HasPublishPermission ())
ShareApi.Share (sharePhotoContent, shareCallback);
else
pendingAction = PendingAction.POST_PHOTO;
}
bool HasPublishPermission ()
{
var accessToken = AccessToken.CurrentAccessToken;
return accessToken != null && accessToken.Permissions.Contains ("publish_actions");
}
void PerformPublish (PendingAction action, bool allowNoToken)
{
var accessToken = AccessToken.CurrentAccessToken;
if (accessToken != null) {
pendingAction = action;
if (HasPublishPermission ()) {
HandlePendingAction ();
return;
} else {
LoginManager.Instance.LogInWithPublishPermissions (this, PERMISSIONS);
return;
}
}
if (allowNoToken) {
pendingAction = action;
HandlePendingAction ();
}
}
}
class FacebookCallback<TResult> : Java.Lang.Object, IFacebookCallback where TResult : Java.Lang.Object
{
public Action HandleCancel { get; set; }
public Action<FacebookException> HandleError { get; set; }
public Action<TResult> HandleSuccess { get; set; }
public void OnCancel ()
{
var c = HandleCancel;
if (c != null)
c ();
}
public void OnError (FacebookException error)
{
var c = HandleError;
if (c != null)
c (error);
}
public void OnSuccess (Java.Lang.Object result)
{
var c = HandleSuccess;
if (c != null)
c (result.JavaCast<TResult> ());
}
}
class CustomProfileTracker : ProfileTracker
{
public delegate void CurrentProfileChangedDelegate (Profile oldProfile, Profile currentProfile);
public CurrentProfileChangedDelegate HandleCurrentProfileChanged { get; set; }
protected override void OnCurrentProfileChanged (Profile oldProfile, Profile currentProfile)
{
var p = HandleCurrentProfileChanged;
if (p != null)
p (oldProfile, currentProfile);
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// PrimitiveBatch.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
#endregion
namespace Othelis
{
// PrimitiveBatch is a class that handles efficient rendering automatically for its
// users, in a similar way to SpriteBatch. PrimitiveBatch can render lines, points,
// and triangles to the screen. In this sample, it is used to draw a spacewars
// retro scene.
public class PrimitiveBatch : IDisposable
{
#region Constants and Fields
// this constant controls how large the vertices buffer is. Larger buffers will
// require flushing less often, which can increase performance. However, having
// buffer that is unnecessarily large will waste memory.
const int DefaultBufferSize = 500;
// a block of vertices that calling AddVertex will fill. Flush will draw using
// this array, and will determine how many primitives to draw from
// positionInBuffer.
VertexPositionColor[] vertices = new VertexPositionColor[DefaultBufferSize];
// keeps track of how many vertices have been added. this value increases until
// we run out of space in the buffer, at which time Flush is automatically
// called.
int positionInBuffer = 0;
// a basic effect, which contains the shaders that we will use to draw our
// primitives.
BasicEffect basicEffect;
// the device that we will issue draw calls to.
GraphicsDevice device;
// this value is set by Begin, and is the type of primitives that we are
// drawing.
PrimitiveType primitiveType;
// how many verts does each of these primitives take up? points are 1,
// lines are 2, and triangles are 3.
int numVertsPerPrimitive;
// hasBegun is flipped to true once Begin is called, and is used to make
// sure users don't call End before Begin is called.
bool hasBegun = false;
bool isDisposed = false;
#endregion
// the constructor creates a new PrimitiveBatch and sets up all of the internals
// that PrimitiveBatch will need.
public PrimitiveBatch(GraphicsDevice graphicsDevice)
{
if (graphicsDevice == null)
{
throw new ArgumentNullException("graphicsDevice");
}
device = graphicsDevice;
// set up a new basic effect, and enable vertex colors.
basicEffect = new BasicEffect(graphicsDevice);
basicEffect.VertexColorEnabled = true;
// projection uses CreateOrthographicOffCenter to create 2d projection
// matrix with 0,0 in the upper left.
basicEffect.Projection = Matrix.CreateOrthographicOffCenter
(0, graphicsDevice.Viewport.Width,
graphicsDevice.Viewport.Height, 0,
0, 1);
this.basicEffect.World = Matrix.Identity;
this.basicEffect.View = Matrix.CreateLookAt(Vector3.Zero, Vector3.Forward,
Vector3.Up);
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing && !isDisposed)
{
if (basicEffect != null)
basicEffect.Dispose();
isDisposed = true;
}
}
// Begin is called to tell the PrimitiveBatch what kind of primitives will be
// drawn, and to prepare the graphics card to render those primitives.
public void Begin(PrimitiveType primitiveType)
{
if (hasBegun)
{
throw new InvalidOperationException
("End must be called before Begin can be called again.");
}
// these three types reuse vertices, so we can't flush properly without more
// complex logic. Since that's a bit too complicated for this sample, we'll
// simply disallow them.
if (primitiveType == PrimitiveType.LineStrip ||
primitiveType == PrimitiveType.TriangleStrip)
{
throw new NotSupportedException
("The specified primitiveType is not supported by PrimitiveBatch.");
}
this.primitiveType = primitiveType;
// how many verts will each of these primitives require?
this.numVertsPerPrimitive = NumVertsPerPrimitive(primitiveType);
//tell our basic effect to begin.
basicEffect.CurrentTechnique.Passes[0].Apply();
// flip the error checking boolean. It's now ok to call AddVertex, Flush,
// and End.
hasBegun = true;
}
// AddVertex is called to add another vertex to be rendered. To draw a point,
// AddVertex must be called once. for lines, twice, and for triangles 3 times.
// this function can only be called once begin has been called.
// if there is not enough room in the vertices buffer, Flush is called
// automatically.
public void AddVertex(Vector2 vertex, Color color)
{
if (!hasBegun)
{
throw new InvalidOperationException
("Begin must be called before AddVertex can be called.");
}
// are we starting a new primitive? if so, and there will not be enough room
// for a whole primitive, flush.
bool newPrimitive = ((positionInBuffer % numVertsPerPrimitive) == 0);
if (newPrimitive &&
(positionInBuffer + numVertsPerPrimitive) >= vertices.Length)
{
Flush();
}
// once we know there's enough room, set the vertex in the buffer,
// and increase position.
vertices[positionInBuffer].Position = new Vector3(vertex, 0);
vertices[positionInBuffer].Color = color;
positionInBuffer++;
}
// End is called once all the primitives have been drawn using AddVertex.
// it will call Flush to actually submit the draw call to the graphics card, and
// then tell the basic effect to end.
public void End()
{
if (!hasBegun)
{
throw new InvalidOperationException
("Begin must be called before End can be called.");
}
// Draw whatever the user wanted us to draw
Flush();
hasBegun = false;
}
// Flush is called to issue the draw call to the graphics card. Once the draw
// call is made, positionInBuffer is reset, so that AddVertex can start over
// at the beginning. End will call this to draw the primitives that the user
// requested, and AddVertex will call this if there is not enough room in the
// buffer.
private void Flush()
{
if (!hasBegun)
{
throw new InvalidOperationException
("Begin must be called before Flush can be called.");
}
// no work to do
if (positionInBuffer == 0)
{
return;
}
// how many primitives will we draw?
int primitiveCount = positionInBuffer / numVertsPerPrimitive;
// submit the draw call to the graphics card
device.DrawUserPrimitives<VertexPositionColor>(primitiveType, vertices, 0,
primitiveCount);
// now that we've drawn, it's ok to reset positionInBuffer back to zero,
// and write over any vertices that may have been set previously.
positionInBuffer = 0;
}
#region Helper functions
// NumVertsPerPrimitive is a boring helper function that tells how many vertices
// it will take to draw each kind of primitive.
static private int NumVertsPerPrimitive(PrimitiveType primitive)
{
int numVertsPerPrimitive;
switch (primitive)
{
case PrimitiveType.LineList:
numVertsPerPrimitive = 2;
break;
case PrimitiveType.TriangleList:
numVertsPerPrimitive = 3;
break;
default:
throw new InvalidOperationException("primitive is not valid");
}
return numVertsPerPrimitive;
}
#endregion
}
}
| |
//
// Authors:
// Ben Motmans <ben.motmans@gmail.com>
//
// Copyright (c) 2007 Ben Motmans
//
// 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 Gtk;
using System;
using System.Collections.Generic;
using MonoDevelop.Database.Sql;
namespace MonoDevelop.Database.Components
{
public class SortedTableListStore
{
public event EventHandler TableToggled;
protected TableSchemaCollection tables;
protected ListStore store;
public const int ColSelectIndex = 0;
public const int ColNameIndex = 1;
public const int ColObjIndex = 2;
protected bool singleCheck;
public SortedTableListStore (TableSchemaCollection tables)
{
if (tables == null)
throw new ArgumentNullException ("tables");
this.tables = tables;
store = new ListStore (typeof (bool), typeof (string), typeof (TableSchema));
store.SetSortColumnId (ColNameIndex, SortType.Ascending);
store.SetSortFunc (ColNameIndex, new TreeIterCompareFunc (SortName));
foreach (TableSchema table in tables)
AddTable (table);
tables.ItemAdded += new SortedCollectionItemEventHandler<TableSchema> (OnTableAdded);
tables.ItemRemoved += new SortedCollectionItemEventHandler<TableSchema> (OnTableRemoved);
}
public ListStore Store {
get { return store; }
}
public virtual bool SingleCheck {
get { return singleCheck; }
set {
if (value != singleCheck) {
singleCheck = value;
if (value)
DeselectAll ();
}
}
}
public virtual TableSchema GetTableSchema (TreeIter iter)
{
if (!iter.Equals (TreeIter.Zero))
return store.GetValue (iter, ColObjIndex) as TableSchema;
return null;
}
public virtual IEnumerable<TableSchema> CheckedTables {
get {
TreeIter iter;
if (store.GetIterFirst (out iter)) {
do {
bool chk = (bool)store.GetValue (iter, ColSelectIndex);
if (chk)
yield return store.GetValue (iter, ColObjIndex) as TableSchema;
} while (store.IterNext (ref iter));
}
}
}
public virtual bool IsTableChecked {
get {
TreeIter iter;
if (store.GetIterFirst (out iter)) {
do {
bool chk = (bool)store.GetValue (iter, ColSelectIndex);
if (chk)
return true;
} while (store.IterNext (ref iter));
}
return false;
}
}
public virtual void SelectAll ()
{
SetSelectState (true);
OnTableToggled ();
}
public virtual void DeselectAll ()
{
SetSelectState (false);
OnTableToggled ();
}
public virtual void Select (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
TableSchema table = tables.Search (name);
if (table != null)
Select (table);
}
public virtual void Select (TableSchema table)
{
if (table == null)
throw new ArgumentNullException ("table");
TreeIter iter = GetTreeIter (table);
if (!iter.Equals (TreeIter.Zero)) {
if (singleCheck)
SetSelectState (false);
store.SetValue (iter, ColSelectIndex, true);
OnTableToggled ();
}
}
public virtual void ToggleSelect (TreeIter iter)
{
bool val = (bool) store.GetValue (iter, ColSelectIndex);
bool newVal = !val;
if (newVal && singleCheck)
SetSelectState (false);
store.SetValue (iter, ColSelectIndex, !val);
OnTableToggled ();
}
protected virtual void SetSelectState (bool state)
{
TreeIter iter;
if (store.GetIterFirst (out iter)) {
do {
store.SetValue (iter, ColSelectIndex, state);
} while (store.IterNext (ref iter));
}
}
protected virtual TreeIter GetTreeIter (TableSchema table)
{
TreeIter iter;
if (store.GetIterFirst (out iter)) {
do {
object obj = store.GetValue (iter, ColObjIndex);
if (obj == table)
return iter;
} while (store.IterNext (ref iter));
}
return TreeIter.Zero;
}
protected virtual void OnTableAdded (object sender, SortedCollectionItemEventArgs<TableSchema> args)
{
AddTable (args.Item);
}
protected virtual void AddTable (TableSchema table)
{
store.AppendValues (false, table.Name, table);
table.Changed += delegate (object sender, EventArgs args) {
TreeIter iter = GetTreeIter (sender as TableSchema);
if (!iter.Equals (TreeIter.Zero))
store.SetValue (iter, ColNameIndex, table.Name);
};
}
protected virtual void OnTableRemoved (object sender, SortedCollectionItemEventArgs<TableSchema> args)
{
TreeIter iter = GetTreeIter (args.Item);
if (!iter.Equals (TreeIter.Zero))
store.Remove (ref iter);
}
protected virtual int SortName (TreeModel model, TreeIter iter1, TreeIter iter2)
{
string name1 = model.GetValue (iter1, ColNameIndex) as string;
string name2 = model.GetValue (iter2, ColNameIndex) as string;
if (name1 == null && name2 == null) return 0;
else if (name1 == null) return -1;
else if (name2 == null) return 1;
return name1.CompareTo (name2);
}
protected virtual void OnTableToggled ()
{
if (TableToggled != null)
TableToggled (this, EventArgs.Empty);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentAssertions.Equivalency;
#if !OLD_MSTEST
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace FluentAssertions.Specs
{
/// <summary>
/// Test Class containing specs over the extensibility points of ShouldBeEquivalentTo
/// </summary>
[TestClass]
public class ExtensibilityRelatedEquivalencySpecs
{
#region Selection Rules
[TestMethod]
public void When_a_selection_rule_is_added_it_should_be_evaluated_after_all_existing_rules()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
NameId = "123",
SomeValue = "hello"
};
var expected = new
{
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ExcludeForeignKeysSelectionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_a_selection_rule_is_added_it_should_appear_in_the_exception_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Name = "123",
};
var expected = new
{
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ExcludeForeignKeysSelectionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(string.Format("*{0}*", typeof(ExcludeForeignKeysSelectionRule).Name));
}
internal class ExcludeForeignKeysSelectionRule : IMemberSelectionRule
{
public bool OverridesStandardIncludeRules
{
get { return false; }
}
public IEnumerable<SelectedMemberInfo> SelectMembers(IEnumerable<SelectedMemberInfo> selectedMembers, ISubjectInfo context, IEquivalencyAssertionOptions config)
{
return selectedMembers.Where(pi => !pi.Name.EndsWith("Id")).ToArray();
}
bool IMemberSelectionRule.IncludesMembers
{
get { return OverridesStandardIncludeRules; }
}
}
#region Obsolete
[TestMethod]
[Obsolete]
public void When_an_obsolete_selection_rule_is_added_it_should_be_evaluated_after_all_existing_rules()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
NameId = "123",
SomeValue = "hello"
};
var expected = new
{
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ObsoleteExcludeForeignKeysSelectionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
[Obsolete]
public void When_an_obsolete_selection_rule_is_added_it_should_appear_in_the_exception_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Name = "123",
};
var expected = new
{
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ObsoleteExcludeForeignKeysSelectionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(string.Format("*{0}*", typeof(ExcludeForeignKeysSelectionRule).Name));
}
[Obsolete]
internal class ObsoleteExcludeForeignKeysSelectionRule : ISelectionRule
{
public IEnumerable<PropertyInfo> SelectProperties(IEnumerable<PropertyInfo> selectedProperties, ISubjectInfo context)
{
return selectedProperties.Where(pi => !pi.Name.EndsWith("Id")).ToArray();
}
}
#endregion
#endregion
#region Matching Rules
[TestMethod]
public void When_a_matching_rule_is_added_it_should_preceed_all_existing_rules()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
NameId = "123",
SomeValue = "hello"
};
var expected = new
{
Name = "123",
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ForeignKeyMatchingRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_a_matching_rule_is_added_it_should_appear_in_the_exception_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
NameId = "123",
SomeValue = "hello"
};
var expected = new
{
Name = "1234",
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ForeignKeyMatchingRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(string.Format("*{0}*", typeof(ForeignKeyMatchingRule).Name));
}
internal class ForeignKeyMatchingRule : IMemberMatchingRule
{
public SelectedMemberInfo Match(SelectedMemberInfo subjectMember, object expectation, string memberPath, IEquivalencyAssertionOptions config)
{
string name = subjectMember.Name;
if (name.EndsWith("Id"))
{
name = name.Replace("Id", "");
}
#if !WINRT && !WINDOWS_PHONE_APP
return SelectedMemberInfo.Create(expectation.GetType().GetProperty(name));
#else
return SelectedMemberInfo.Create(expectation.GetType()
.GetRuntimeProperty(name));
#endif
}
}
#region Obsolete
[TestMethod]
[Obsolete]
public void When_an_obsolete_matching_rule_is_added_it_should_preceed_all_existing_rules()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
NameId = "123",
SomeValue = "hello"
};
var expected = new
{
Name = "123",
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ObsoleteForeignKeyMatchingRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
[Obsolete]
public void When_an_obsolete_matching_rule_is_added_it_should_appear_in_the_exception_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
NameId = "123",
SomeValue = "hello"
};
var expected = new
{
Name = "1234",
SomeValue = "hello"
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new ObsoleteForeignKeyMatchingRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(string.Format("*{0}*", typeof(ObsoleteForeignKeyMatchingRule).Name));
}
[Obsolete]
internal class ObsoleteForeignKeyMatchingRule : IMatchingRule
{
public PropertyInfo Match(PropertyInfo subjectProperty, object expectation, string propertyPath)
{
string name = subjectProperty.Name;
if (name.EndsWith("Id"))
{
name = name.Replace("Id", "");
}
#if !WINRT && !WINDOWS_PHONE_APP
return expectation.GetType().GetProperty(name);
#else
return expectation.GetType()
.GetRuntimeProperty(name);
#endif
}
}
#endregion
#endregion
#region Assertion Rules
[TestMethod]
public void When_equally_named_properties_are_type_incompatible_and_assertion_rule_exists_it_should_not_throw()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Type = typeof(String),
};
var other = new
{
Type = typeof(String).AssemblyQualifiedName,
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(other,
o => o
.Using<object>(c => ((Type)c.Subject).AssemblyQualifiedName.Should().Be((string)c.Expectation))
.When(si => si.SelectedMemberPath == "Type"));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_an_assertion_is_overridden_for_a_predicate_it_should_use_the_provided_action()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Date = 14.July(2012).At(12, 59, 59)
};
var expectation = new
{
Date = 14.July(2012).At(13, 0, 0)
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(expectation, options => options
.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation, 1000))
.When(info => info.SelectedMemberPath.EndsWith("Date")));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_an_assertion_is_overridden_for_all_types_it_should_use_the_provided_action_for_all_properties()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Date = 21.July(2012).At(11, 8, 59),
Nested = new
{
NestedDate = 14.July(2012).At(12, 59, 59)
}
};
var expectation = new
{
Date = 21.July(2012).At(11, 9, 0),
Nested = new
{
NestedDate = 14.July(2012).At(13, 0, 0)
}
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(expectation, options =>
options
.Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation, 1000))
.WhenTypeIs<DateTime>());
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_a_nullable_property_is_overriden_with_a_custom_asserrtion_it_should_use_it()
{
var actual = new SimpleWithNullable
{
nullableIntegerProperty = 1,
strProperty = "I haz a string!"
};
var expected = new SimpleWithNullable
{
strProperty = "I haz a string!"
};
actual.ShouldBeEquivalentTo(expected,
opt => opt.Using<Int64>(c => c.Subject.Should().BeInRange(0, 10)).WhenTypeIs<Int64>());
}
internal class SimpleWithNullable
{
public Int64? nullableIntegerProperty { get; set; }
public string strProperty { get; set; }
}
[TestMethod]
public void When_an_assertion_rule_is_added_it_should_preceed_all_existing_rules()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Created = 8.July(2012).At(22, 9)
};
var expected = new
{
Created = 8.July(2012).At(22, 10)
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new RelaxingDateTimeAssertionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_an_assertion_rule_is_added_it_appear_in_the_exception_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = 8.July(2012).At(22, 9);
var expected = 8.July(2012).At(22, 10);
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new RelaxingDateTimeAssertionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(string.Format("*{0}*", typeof(RelaxingDateTimeAssertionRule).Name));
}
[TestMethod]
public void When_an_assertion_rule_matches_the_root_object_the_assertion_rule_should_not_apply_to_the_root_object()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = 8.July(2012).At(22, 9);
var expected = 8.July(2012).At(22, 10);
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act = () => subject.ShouldBeEquivalentTo(
expected,
options => options.Using(new RelaxingDateTimeAssertionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_multiple_asertion_rules_are_added__they_should_be_executed_from_right_to_left()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new
{
Created = 8.July(2012).At(22, 9)
};
var expected = new
{
Created = 8.July(2012).At(22, 10)
};
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(expected,
opts => opts.Using(new AlwaysFailAssertionRule()).Using(new RelaxingDateTimeAssertionRule()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow(
"a different assertion rule should handle the comparision before the exception throwing assertion rule is hit");
}
[TestMethod]
public void When_an_assertion_rule_added_with_the_fluent_api_matches_the_root_object_the_assertion_rule_should_not_apply_to_the_root_object()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = 8.July(2012).At(22, 9);
var expected = 8.July(2012).At(22, 10);
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(
expected,
options =>
options.Using<DateTime>(
context => context.Subject.Should().BeCloseTo(context.Expectation, 1000 * 60))
.WhenTypeIs<DateTime>());
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
internal class AlwaysFailAssertionRule : IAssertionRule
{
public bool AssertEquality(IEquivalencyValidationContext context)
{
throw new Exception("Failed");
}
}
internal class RelaxingDateTimeAssertionRule : IAssertionRule
{
public bool AssertEquality(IEquivalencyValidationContext context)
{
if (context.Subject is DateTime)
{
((DateTime)context.Subject).Should().BeCloseTo((DateTime)context.Expectation, 1000 * 60);
return true;
}
return false;
}
}
[TestMethod]
public void When_multiple_asertion_rules_are_added_with_the_fluent_api_they_should_be_executed_from_right_to_left()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new ClassWithOnlyAProperty();
var expected = new ClassWithOnlyAProperty();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(expected,
opts =>
opts.Using<object>(context => { throw new Exception(); })
.When(s => true)
.Using<object>(context => { })
.When(s => true));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow(
"a different assertion rule should handle the comparision before the exception throwing assertion rule is hit");
}
#endregion
#region Equivalency Steps
[TestMethod]
public void When_an_equivalency_step_handles_the_comparison_later_equivalency_steps_should_not_be_ran()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new ClassWithOnlyAProperty();
var expected = new ClassWithOnlyAProperty();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(expected,
opts =>
opts.Using(new AlwayHandleEquivalencyStep())
.Using(new ThrowExceptionEquivalencyStep<InvalidOperationException>()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_an_equivalency_does_not_handle_the_comparison_later_equivalency_steps_should_stil_be_ran()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new ClassWithOnlyAProperty();
var expected = new ClassWithOnlyAProperty();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(expected,
opts =>
opts.Using(new NeverHandleEquivalencyStep())
.Using(new ThrowExceptionEquivalencyStep<InvalidOperationException>()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<InvalidOperationException>();
}
[TestMethod]
public void When_multiple_equivalency_steps_are_added_they_should_be_executed_from_right_to_left()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
var subject = new ClassWithOnlyAProperty();
var expected = new ClassWithOnlyAProperty();
//-----------------------------------------------------------------------------------------------------------
// Act
//-----------------------------------------------------------------------------------------------------------
Action act =
() =>
subject.ShouldBeEquivalentTo(expected,
opts =>
opts.Using(new ThrowExceptionEquivalencyStep<NotSupportedException>())
.Using(new ThrowExceptionEquivalencyStep<InvalidOperationException>()));
//-----------------------------------------------------------------------------------------------------------
// Assert
//-----------------------------------------------------------------------------------------------------------
act.ShouldThrow<NotSupportedException>();
}
internal class ThrowExceptionEquivalencyStep<TException> : CanHandleAnythingEquivalencyStep where TException : Exception, new()
{
public override bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config)
{
throw new TException();
}
}
internal class AlwayHandleEquivalencyStep : CanHandleAnythingEquivalencyStep
{
public override bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config)
{
return true;
}
}
internal class NeverHandleEquivalencyStep : CanHandleAnythingEquivalencyStep
{
public override bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config)
{
return false;
}
}
internal abstract class CanHandleAnythingEquivalencyStep : IEquivalencyStep
{
public bool CanHandle(IEquivalencyValidationContext context, IEquivalencyAssertionOptions config)
{
return true;
}
public abstract bool Handle(IEquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config);
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Voyage.Terraingine.DataCore;
namespace Voyage.Terraingine.SmoothVertices
{
/// <summary>
/// Summary description for Smooth.
/// </summary>
public class Driver : Voyage.Terraingine.PlugIn
{
#region Data Members
private System.Windows.Forms.Button btnRun;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown numVertices;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
#endregion
#region Properties
/// <summary>
/// Gets the TerrainPage used.
/// </summary>
public TerrainPage TerrainPage
{
get { return _page; }
}
#endregion
#region Methods
/// <summary>
/// Creates a smoothing modifier form.
/// </summary>
public Driver()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.CenterToParent();
base.InitializeBase();
_name = "Smooth Vertices";
}
/// <summary>
/// Runs the plug-in.
/// </summary>
public override void Run()
{
if ( _page != null )
ShowDialog( _owner );
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Smooths the vertices in the TerrainPatch based upon a box-filtering
/// method of averaging nearby vertices.
/// </summary>
/// <param name="numAdjVerts">Number of adjacent vertices that affect the smoothing.</param>
private void SmoothVertices( int numAdjVerts )
{
CustomVertex.PositionNormal[] origVerts = _page.TerrainPatch.Vertices;
Vector3[] newVerts = new Vector3[_page.TerrainPatch.NumVertices];
Vector3 position;
int numAffecting;
int rows = _page.TerrainPatch.Rows;
int columns = _page.TerrainPatch.Columns;
for ( int i = 0; i < rows; i++ )
{
for ( int j = 0; j < columns; j++ )
{
position = Vector3.Empty;
numAffecting = 0;
for ( int k = -numAdjVerts; k <= numAdjVerts; k++ )
{
for ( int l = -numAdjVerts; l <= numAdjVerts; l++ )
{
if ( i + k > -1 && i + k < rows && j + l > -1 && j + l < columns )
{
position += _page.TerrainPatch.Vertices[( i + k ) * rows + j + l].Position;
numAffecting++;
}
}
}
newVerts[i * rows + j] = origVerts[i * rows + j].Position;
newVerts[i * rows + j].Y = position.Y /= numAffecting;
}
}
for ( int i = 0; i < newVerts.Length; i++ )
origVerts[i].Position = newVerts[i];
}
/// <summary>
/// Runs the plug-in effect.
/// </summary>
private void btnRun_Click(object sender, System.EventArgs e)
{
SmoothVertices( Convert.ToInt32( numVertices.Value ) );
_success = true;
this.Close();
}
/// <summary>
/// Checks that the number of adjacent vertices is not more than the current
/// size of the TerrainPatch.
/// </summary>
private void numVertices_ValueChanged(object sender, System.EventArgs e)
{
int vertices;
if ( _page.TerrainPatch.Rows < _page.TerrainPatch.Columns )
{
vertices = _page.TerrainPatch.Rows;
if ( vertices % 2 == 0 )
vertices--;
if ( Convert.ToInt32( numVertices.Value ) > vertices )
numVertices.Value = Convert.ToDecimal( vertices );
}
else
{
vertices = _page.TerrainPatch.Columns;
if ( vertices % 2 == 0 )
vertices--;
if ( Convert.ToInt32( numVertices.Value ) > vertices )
numVertices.Value = Convert.ToDecimal( vertices );
}
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnRun = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.numVertices = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.numVertices)).BeginInit();
this.SuspendLayout();
//
// btnRun
//
this.btnRun.Location = new System.Drawing.Point(32, 56);
this.btnRun.Name = "btnRun";
this.btnRun.TabIndex = 0;
this.btnRun.Text = "Run";
this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(152, 56);
this.btnCancel.Name = "btnCancel";
this.btnCancel.TabIndex = 1;
this.btnCancel.Text = "Cancel";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(152, 32);
this.label1.TabIndex = 2;
this.label1.Text = "Number of Adjacent Vertices That Affect Smoothing:";
//
// numVertices
//
this.numVertices.Location = new System.Drawing.Point(168, 16);
this.numVertices.Maximum = new System.Decimal(new int[] {
200,
0,
0,
0});
this.numVertices.Minimum = new System.Decimal(new int[] {
1,
0,
0,
0});
this.numVertices.Name = "numVertices";
this.numVertices.Size = new System.Drawing.Size(64, 20);
this.numVertices.TabIndex = 3;
this.numVertices.Value = new System.Decimal(new int[] {
1,
0,
0,
0});
this.numVertices.ValueChanged += new System.EventHandler(this.numVertices_ValueChanged);
//
// Smooth
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(242, 88);
this.Controls.Add(this.numVertices);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnRun);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "Smooth";
this.Text = "Smooth Terrain Vertices";
((System.ComponentModel.ISupportInitialize)(this.numVertices)).EndInit();
this.ResumeLayout(false);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.ObjectModel.Tests
{
public partial class KeyedCollectionTests
{
[Fact]
public void Ctor_Default()
{
var collection = new StringKeyedCollection<int>();
Assert.Empty(collection);
Assert.Equal(EqualityComparer<string>.Default, collection.Comparer);
Assert.Null(collection.Dictionary);
Assert.Empty(collection.Items);
Assert.IsType<List<int>>(collection.Items);
}
public static IEnumerable<object[]> Ctor_IEqualityComparer_TestData()
{
yield return new object[] { null };
yield return new object[] { StringComparer.OrdinalIgnoreCase };
}
[Theory]
[MemberData(nameof(Ctor_IEqualityComparer_TestData))]
public void Ctor_IEqualityComparer(IEqualityComparer<string> comparer)
{
var collection = new StringKeyedCollection<int>(comparer);
Assert.Empty(collection);
Assert.Same(comparer ?? EqualityComparer<string>.Default, collection.Comparer);
Assert.Null(collection.Dictionary);
Assert.Empty(collection.Items);
Assert.IsType<List<int>>(collection.Items);
}
public static IEnumerable<object[]> Ctor_IEqualityComparer_Int_TestData()
{
yield return new object[] { null, 10 };
yield return new object[] { null, 0 };
yield return new object[] { null, -1 };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 10 };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 0 };
yield return new object[] { StringComparer.OrdinalIgnoreCase, -1 };
}
[Theory]
[MemberData(nameof(Ctor_IEqualityComparer_Int_TestData))]
public void Ctor_IEqualityComparer_Int(IEqualityComparer<string> comparer, int dictionaryCreationThreshold)
{
var collection = new StringKeyedCollection<int>(comparer, dictionaryCreationThreshold);
Assert.Empty(collection);
Assert.Same(comparer ?? EqualityComparer<string>.Default, collection.Comparer);
Assert.Null(collection.Dictionary);
Assert.Empty(collection.Items);
Assert.IsType<List<int>>(collection.Items);
}
[Fact]
public void Ctor_InvalidDictionaryCreationThreshold_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("dictionaryCreationThreshold", () => new StringKeyedCollection<int>(null, -2));
}
[Fact]
public void InsertItem_InvokeSeveralTimesWithoutCustomThreshold_Success()
{
var collection = new StringKeyedCollection<int>();
collection.GetKeyForItemHandler = item => (item * 2).ToString();
// Add first.
collection.InsertItem(0, 1);
Assert.Equal(new int[] { 1 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{"2", 1}
}, collection.Dictionary
);
Assert.Equal(1, collection["2"]);
// Add another - end.
collection.InsertItem(1, 3);
Assert.Equal(new int[] { 1, 3 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{"2", 1},
{"6", 3}
}, collection.Dictionary
);
Assert.Equal(1, collection["2"]);
Assert.Equal(3, collection["6"]);
// Add another - middle.
collection.InsertItem(1, 2);
Assert.Equal(new int[] { 1, 2, 3 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{"2", 1},
{"4", 2},
{"6", 3}
}, collection.Dictionary
);
Assert.Equal(1, collection["2"]);
Assert.Equal(2, collection["4"]);
Assert.Equal(3, collection["6"]);
}
[Fact]
public void InsertItem_InvokeSeveralTimesWithCustomThreshold_Success()
{
var collection = new StringKeyedCollection<int>(null, 3);
collection.GetKeyForItemHandler = item => (item * 2).ToString();
// Add first.
collection.InsertItem(0, 1);
Assert.Equal(new int[] { 1 }, collection.Items.Cast<int>());
Assert.Null(collection.Dictionary);
Assert.Equal(1, collection["2"]);
// Add another.
collection.InsertItem(1, 3);
Assert.Equal(new int[] { 1, 3 }, collection.Items.Cast<int>());
Assert.Null(collection.Dictionary);
Assert.Equal(1, collection["2"]);
Assert.Equal(3, collection["6"]);
// Meet threshold.
collection.InsertItem(1, 2);
Assert.Equal(new int[] { 1, 2, 3 }, collection.Items.Cast<int>());
Assert.Null(collection.Dictionary);
Assert.Equal(1, collection["2"]);
Assert.Equal(2, collection["4"]);
Assert.Equal(3, collection["6"]);
// Exceed threshold.
collection.InsertItem(3, 4);
Assert.Equal(new int[] { 1, 2, 3, 4 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "2", 1 },
{ "4", 2 },
{ "6", 3 },
{ "8", 4 }
}, collection.Dictionary
);
Assert.Equal(1, collection["2"]);
Assert.Equal(2, collection["4"]);
Assert.Equal(3, collection["6"]);
Assert.Equal(4, collection["8"]);
// Add another.
collection.InsertItem(4, 5);
Assert.Equal(new int[] { 1, 2, 3, 4, 5 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "2", 1 },
{ "4", 2 },
{ "6", 3 },
{ "8", 4 },
{ "10", 5 }
}, collection.Dictionary
);
Assert.Equal(1, collection["2"]);
Assert.Equal(2, collection["4"]);
Assert.Equal(3, collection["6"]);
Assert.Equal(4, collection["8"]);
Assert.Equal(5, collection["10"]);
}
[Fact]
public void InsertItem_NullKeyForItemResult_Success()
{
var collection = new StringKeyedCollection<int>(null, 0);
// Don't add even numbers.
collection.GetKeyForItemHandler = item => item % 2 == 0 ? null : item.ToString();
// Add null without dictionary - not added.
collection.InsertItem(0, 2);
Assert.Equal(new int[] { 2 }, collection.Items.Cast<int>());
Assert.Null(collection.Dictionary);
// Add non null without dictionary - added.
collection.InsertItem(0, 1);
Assert.Equal(new int[] { 1, 2 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{"1", 1}
}, collection.Dictionary
);
// Add null with dictionary - not added.
collection.InsertItem(0, 4);
Assert.Equal(new int[] { 4, 1, 2 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{"1", 1}
}, collection.Dictionary
);
// Add non null with dictionary - added.
collection.InsertItem(0, 3);
Assert.Equal(new int[] { 3, 4, 1, 2 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{"1", 1},
{"3", 3}
}, collection.Dictionary
);
}
public static IEnumerable<object[]> InsertItem_AddSameKey_TestData()
{
// Exceeding threshold.
yield return new object[] { null, 0, "first" };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 0, "first" };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 0, "FIRST" };
// Meeting threshold.
yield return new object[] { null, 1, "first" };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 1, "first" };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 1, "FIRST" };
// Not meeting threshold.
yield return new object[] { null, 2, "first" };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 2, "first" };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 2, "FIRST" };
}
[Theory]
[MemberData(nameof(InsertItem_AddSameKey_TestData))]
public void InsertItem_AddSameKey_ThrowsArgumentException(IEqualityComparer<string> comparer, int dictionaryCreationThreshold, string key)
{
var collection = new StringKeyedCollection<string>(comparer, dictionaryCreationThreshold);
collection.GetKeyForItemHandler = item => item + "_key";
collection.InsertItem(0, "first");
AssertExtensions.Throws<ArgumentException>(dictionaryCreationThreshold > 1 ? "key" : null, null, () => collection.InsertItem(0, key));
}
public static IEnumerable<object[]> Contains_TestData()
{
yield return new object[] { null, "first_key", true };
yield return new object[] { null, "FIRST_KEY", false };
yield return new object[] { null, "NoSuchKey", false };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "first_key", true };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "FIRST_KEY", true };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "NoSuchKey", false };
}
[Theory]
[MemberData(nameof(Contains_TestData))]
public void Contains_Invoke_ReturnsExpected(IEqualityComparer<string> comparer, string key, bool expected)
{
var collection = new StringKeyedCollection<string>(comparer, 3);
collection.GetKeyForItemHandler = item => item + "_key";
// Without dictionary.
collection.InsertItem(0, "first");
Assert.Equal(expected, collection.Contains(key));
// With dictionary.
collection.InsertItem(0, "second");
collection.InsertItem(0, "third");
collection.InsertItem(0, "fourth");
Assert.Equal(expected, collection.Contains(key));
}
[Theory]
[InlineData(3, true)]
[InlineData(4, false)]
public void Contains_NullKeyForItemResult_Success(int dictionaryCreationThreshold, bool expected)
{
var collection = new StringKeyedCollection<int>(null, dictionaryCreationThreshold);
collection.GetKeyForItemHandler = i => i.ToString();
collection.Add(1);
collection.Add(2);
collection.Add(3);
collection.Add(4);
// Don't get even numbers.
collection.GetKeyForItemHandler = i => i % 2 == 0 ? null : i.ToString();
// Get null key.
Assert.Equal(expected, collection.Contains("2"));
// Get non null key.
Assert.True(collection.Contains("1"));
}
[Theory]
[InlineData(3, false)]
[InlineData(4, true)]
public void Contains_DifferentKeyForItemResult_Success(int dictionaryCreationThreshold, bool expected)
{
var collection = new StringKeyedCollection<int>(null, dictionaryCreationThreshold);
collection.GetKeyForItemHandler = i => i.ToString();
collection.Add(1);
collection.Add(2);
collection.Add(3);
collection.Add(4);
collection.GetKeyForItemHandler = i => (i * 2).ToString();
Assert.Equal(expected, collection.Contains("6"));
}
[Fact]
public void Contains_NullKey_ThrowsArgumentNullException()
{
var collection = new StringKeyedCollection<string>();
AssertExtensions.Throws<ArgumentNullException>("key", () => collection.Contains(null));
}
[Fact]
public void Item_GetWithComparer_Success()
{
var collection = new StringKeyedCollection<string>(StringComparer.OrdinalIgnoreCase, 3);
collection.GetKeyForItemHandler = item => item + "_key";
// Without dictionary.
collection.Add("first");
Assert.Equal("first", collection["first_key"]);
Assert.Equal("first", collection["FIRST_KEY"]);
// With dictionary.
collection.Add("second");
collection.Add("third");
collection.Add("fourth");
Assert.Equal("first", collection["first_key"]);
Assert.Equal("first", collection["FIRST_KEY"]);
}
[Fact]
public void Item_GetNoSuchItem_ThrowsKeyNotFoundException()
{
var collection = new StringKeyedCollection<string>(null, 3);
collection.GetKeyForItemHandler = item => item + "_key";
// Without dictionary.
collection.Add("first");
Assert.Throws<KeyNotFoundException>(() => collection["NoSuchKey"]);
// With dictionary.
collection.Add("second");
collection.Add("third");
collection.Add("fourth");
Assert.Throws<KeyNotFoundException>(() => collection["NoSuchKey"]);
}
public static IEnumerable<object[]> Remove_WithoutDictionary_TestData()
{
yield return new object[] { null, "first_key", true, new object[0] };
yield return new object[] { null, "FIRST_KEY", false, new object[] { "first" } };
yield return new object[] { null, "NoSuchKey", false, new object[] { "first" } };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "first_key", true, new object[0] };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "FIRST_KEY", true, new object[0] };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "NoSuchKey", false, new object[] { "first" } };
}
[Theory]
[MemberData(nameof(Remove_WithoutDictionary_TestData))]
public void Remove_ValidKeyWithoutDictionary_Success(IEqualityComparer<string> comparer, string key, bool expected, string[] expectedItems)
{
var collection = new StringKeyedCollection<string>(comparer, 3);
collection.GetKeyForItemHandler = i => i + "_key";
collection.Add("first");
Assert.Null(collection.Dictionary);
Assert.Equal(expected, collection.Remove(key));
Assert.Equal(expectedItems, collection.Items.Cast<string>());
Assert.Null(collection.Dictionary);
}
public static IEnumerable<object[]> Remove_WithDictionary_TestData()
{
var fullDictionary = new Dictionary<string, string>
{
{ "first_key", "first" },
{ "second_key", "second" },
{ "third_key", "third" },
{ "fourth_key", "fourth" }
};
var removedDictionary = new Dictionary<string, string>
{
{ "second_key", "second" },
{ "third_key", "third" },
{ "fourth_key", "fourth" }
};
yield return new object[] { null, "first_key", true, new object[] { "second", "third", "fourth" }, removedDictionary };
yield return new object[] { null, "FIRST_KEY", false, new object[] { "first", "second", "third", "fourth" }, fullDictionary };
yield return new object[] { null, "NoSuchKey", false, new object[] { "first", "second", "third", "fourth" }, fullDictionary };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "first_key", true, new object[] { "second", "third", "fourth" }, removedDictionary };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "FIRST_KEY", true, new object[] { "second", "third", "fourth" }, removedDictionary };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "NoSuchKey", false, new object[] { "first", "second", "third", "fourth" }, fullDictionary };
}
[Theory]
[MemberData(nameof(Remove_WithDictionary_TestData))]
public void Remove_ValidKeyWithDictionary_Success(IEqualityComparer<string> comparer, string key, bool expected, string[] expectedItems, Dictionary<string, string> expectedDictionary)
{
var collection = new StringKeyedCollection<string>(comparer, 3);
collection.GetKeyForItemHandler = i => i + "_key";
collection.Add("first");
collection.Add("second");
collection.Add("third");
collection.Add("fourth");
Assert.NotNull(collection.Dictionary);
Assert.Equal(expected, collection.Remove(key));
Assert.Equal(expectedItems, collection.Items.Cast<string>());
Assert.Equal(expectedDictionary, collection.Dictionary);
}
[Fact]
public void Remove_NullKeyForItemResult_Success()
{
var collection = new StringKeyedCollection<int>(null, 3);
collection.GetKeyForItemHandler = item => item.ToString();
collection.Add(1);
collection.Add(2);
collection.Add(3);
collection.Add(4);
// Don't add/remove even numbers.
collection.GetKeyForItemHandler = item => item % 2 == 0 ? null : item.ToString();
// Remove null key.
Assert.True(collection.Remove("2"));
Assert.Equal(new int[] { 1, 3, 4 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "1", 1 },
{ "2", 2 },
{ "3", 3 },
{ "4", 4 }
}, collection.Dictionary
);
// Remove non-null key.
Assert.True(collection.Remove("1"));
Assert.Equal(new int[] { 3, 4 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "2", 2 },
{ "3", 3 },
{ "4", 4 }
}, collection.Dictionary
);
}
[Fact]
public void Remove_DifferentKeyForItemResult_Success()
{
var collection = new StringKeyedCollection<int>();
collection.GetKeyForItemHandler = item => item.ToString();
collection.Add(1);
collection.Add(2);
collection.GetKeyForItemHandler = item => (item * 2).ToString();
collection.RemoveItem(1);
Assert.Equal(new int[] { 1 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "1", 1 },
{ "2", 2 },
}, collection.Dictionary
);
}
[Fact]
public void Remove_Invoke_ResetsCurrentThresholdCount()
{
var collection = new StringKeyedCollection<string>(null, 3);
collection.GetKeyForItemHandler = item => item + "_key";
collection.Add("first");
collection.Remove("first_key");
// Add more items - make sure the current count has been reset.
collection.Add("first");
Assert.Null(collection.Dictionary);
collection.Add("second");
Assert.Null(collection.Dictionary);
collection.Add("third");
Assert.Null(collection.Dictionary);
collection.Add("fourth");
Assert.NotEmpty(collection.Dictionary);
}
[Fact]
public void Remove_NullKey_ThrowsArgumentNullException()
{
var collection = new StringKeyedCollection<string>();
AssertExtensions.Throws<ArgumentNullException>("key", () => collection.Remove(null));
}
[Fact]
public void RemoveItem_InvokeWithoutDictionary_Success()
{
var collection = new StringKeyedCollection<string>(null, 3);
collection.GetKeyForItemHandler = item => item + "_key";
collection.Add("first");
Assert.Null(collection.Dictionary);
collection.RemoveItem(0);
Assert.Empty(collection);
Assert.Null(collection.Dictionary);
}
[Fact]
public void RemoveItem_InvokeWithDictionary_Success()
{
var collection = new StringKeyedCollection<string>(null, 3);
collection.GetKeyForItemHandler = item => item + "_key";
collection.Add("first");
collection.Add("second");
collection.Add("third");
collection.Add("fourth");
Assert.NotNull(collection.Dictionary);
// Remove from start.
collection.RemoveItem(0);
Assert.Equal(new string[] { "second", "third", "fourth" }, collection.Items.Cast<string>());
Assert.Equal(new Dictionary<string, string>
{
{ "second_key", "second" },
{ "third_key", "third" },
{ "fourth_key", "fourth" }
}, collection.Dictionary
);
// Remove from middle.
collection.RemoveItem(1);
Assert.Equal(new string[] { "second", "fourth" }, collection.Items.Cast<string>());
Assert.Equal(new Dictionary<string, string>
{
{ "second_key", "second" },
{ "fourth_key", "fourth" }
}, collection.Dictionary
);
// Remove from end.
collection.RemoveItem(1);
Assert.Equal(new string[] { "second" }, collection.Items.Cast<string>());
Assert.Equal(new Dictionary<string, string>
{
{ "second_key", "second" }
}, collection.Dictionary
);
// Remove last.
collection.RemoveItem(0);
Assert.Empty(collection);
Assert.Empty(collection.Dictionary);
}
[Fact]
public void RemoveItem_NullKeyForItemResult_Success()
{
var collection = new StringKeyedCollection<int>(null, 3);
collection.GetKeyForItemHandler = item => item.ToString();
collection.Add(1);
collection.Add(2);
collection.Add(3);
collection.Add(4);
// Don't add/remove even numbers.
collection.GetKeyForItemHandler = item => item % 2 == 0 ? null : item.ToString();
// Remove null key.
collection.RemoveItem(1);
Assert.Equal(new int[] { 1, 3, 4 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "1", 1 },
{ "2", 2 },
{ "3", 3 },
{ "4", 4 }
}, collection.Dictionary
);
// Remove non-null key.
collection.RemoveItem(0);
Assert.Equal(new int[] { 3, 4 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "2", 2 },
{ "3", 3 },
{ "4", 4 }
}, collection.Dictionary
);
}
[Fact]
public void RemoveItem_DifferentKeyForItemResult_Success()
{
var collection = new StringKeyedCollection<int>();
collection.GetKeyForItemHandler = item => item.ToString();
collection.Add(1);
collection.Add(2);
collection.GetKeyForItemHandler = item => (item * 2).ToString();
collection.RemoveItem(1);
Assert.Equal(new int[] { 1 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "1", 1 },
{ "2", 2 },
}, collection.Dictionary
);
}
[Fact]
public void RemoveItem_Invoke_ResetsCurrentThresholdCount()
{
var collection = new StringKeyedCollection<string>(null, 3);
collection.GetKeyForItemHandler = item => item + "_key";
collection.Add("first");
collection.RemoveItem(0);
// Add more items - make sure the current count has been reset.
collection.Add("first");
Assert.Null(collection.Dictionary);
collection.Add("second");
Assert.Null(collection.Dictionary);
collection.Add("third");
Assert.Null(collection.Dictionary);
collection.Add("fourth");
Assert.NotEmpty(collection.Dictionary);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void RemoveItem_InvalidIndex_ThrowsArgumentOutOfRangeException(int index)
{
var collection = new StringKeyedCollection<string>(null, 3);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.RemoveItem(index));
}
[Fact]
public void ClearItems_WithDictionary_Success()
{
var collection = new StringKeyedCollection<string>(null, 3);
collection.GetKeyForItemHandler = item => item + "_key";
collection.Add("first");
collection.Add("second");
collection.Add("third");
collection.Add("fourth");
Assert.NotNull(collection.Dictionary);
collection.ClearItems();
Assert.Empty(collection);
Assert.Empty(collection.Dictionary);
}
[Fact]
public void ClearItems_WithoutDictionary_Success()
{
var collection = new StringKeyedCollection<string>(null, 3);
collection.GetKeyForItemHandler = item => item + "_key";
collection.Add("first");
collection.ClearItems();
Assert.Empty(collection);
Assert.Null(collection.Dictionary);
}
[Fact]
public void ClearItems_Invoke_ResetsCurrentThresholdCount()
{
var collection = new StringKeyedCollection<string>(null, 3);
collection.GetKeyForItemHandler = item => item + "_key";
collection.Add("first");
collection.ClearItems();
// Add more items - make sure the current count has been reset.
collection.Add("first");
Assert.Null(collection.Dictionary);
collection.Add("second");
Assert.Null(collection.Dictionary);
collection.Add("third");
Assert.Null(collection.Dictionary);
collection.Add("fourth");
Assert.NotEmpty(collection.Dictionary);
}
public static IEnumerable<object[]> ChangeItemKey_TestData()
{
yield return new object[] { null, 0, "first", "first_key", new Dictionary<string, string> { { "first_key", "first" }, { "second_key", "second" } } };
yield return new object[] { null, 0, "first", "FIRST_KEY", new Dictionary<string, string> { { "FIRST_KEY", "first" }, { "second_key", "second" } } };
yield return new object[] { null, 0, "first", "SECOND_KEY", new Dictionary<string, string> { { "SECOND_KEY", "first" }, { "second_key", "second" } } };
yield return new object[] { null, 0, "first", "other_key", new Dictionary<string, string> { { "other_key", "first" }, { "second_key", "second" } } };
yield return new object[] { null, 0, "first", null, new Dictionary<string, string> { { "second_key", "second" } } };
yield return new object[] { null, 3, "first", "first_key", null };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 0, "first", "first_key", new Dictionary<string, string> { { "first_key", "first" }, { "second_key", "second" } } };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 0, "first", "FIRST_KEY", new Dictionary<string, string> { { "first_key", "first" }, { "second_key", "second" } } };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 0, "first", null, new Dictionary<string, string> { { "second_key", "second" } } };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 0, "first", "other_key", new Dictionary<string, string> { { "other_key", "first" }, { "second_key", "second" } } };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 3, "first", "first_key", null };
}
[Theory]
[MemberData(nameof(ChangeItemKey_TestData))]
public void ChangeItemKey_Invoke_Success(IEqualityComparer<string> comparer, int dictionaryCreationThreshold, string item, string newKey, Dictionary<string, string> expectedDictionary)
{
var collection = new StringKeyedCollection<string>(comparer, dictionaryCreationThreshold);
collection.GetKeyForItemHandler = i => i + "_key";
collection.Add("first");
collection.Add("second");
collection.ChangeItemKey(item, newKey);
Assert.Equal(new string[] { "first", "second" }, collection.Items.Cast<string>());
Assert.Equal(expectedDictionary, collection.Dictionary);
}
[Fact]
public void ChangeItemKey_NullNewKey_Success()
{
var collection = new StringKeyedCollection<int>(null, 0);
collection.GetKeyForItemHandler = item => item.ToString();
collection.Add(1);
collection.Add(2);
// Don't add even numbers.
collection.GetKeyForItemHandler = item => item % 2 == 0 ? null : item.ToString();
// Change null key.
collection.ChangeItemKey(2, "6");
Assert.Equal(new int[] { 1, 2 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "1", 1 },
{ "2", 2 },
{ "6", 2 }
}, collection.Dictionary
);
// Change non-null key.
collection.ChangeItemKey(1, "5");
Assert.Equal(new int[] { 1, 2 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "5", 1 },
{ "2", 2 },
{ "6", 2 }
}, collection.Dictionary
);
}
[Fact]
public void ChangeItemKey_OnThresholdOfCreation_Success()
{
var collection = new StringKeyedCollection<int>(null, 3);
collection.GetKeyForItemHandler = item => item.ToString();
collection.Add(1);
collection.Add(2);
collection.Add(3);
Assert.Null(collection.Dictionary);
collection.GetKeyForItemHandler = item => (item * 2).ToString();
collection.ChangeItemKey(2, "10");
Assert.Equal(new Dictionary<string, int>
{
{"2", 1},
{"10", 2},
{"6", 3}
}, collection.Dictionary
);
}
public static IEnumerable<object[]> ChangeItemKey_DuplicateKey_TestData()
{
yield return new object[] { null, "second_key" };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "second_key" };
yield return new object[] { StringComparer.OrdinalIgnoreCase, "SECOND_KEY" };
}
[Theory]
[MemberData(nameof(ChangeItemKey_DuplicateKey_TestData))]
public void ChangeItemKey_DuplicateKey_ThrowsArgumentException(IEqualityComparer<string> comparer, string newKey)
{
var collection = new StringKeyedCollection<string>(comparer, 3);
collection.GetKeyForItemHandler = item => item + "_key";
collection.Add("first");
collection.Add("second");
AssertExtensions.Throws<ArgumentException>("key", null, () => collection.ChangeItemKey("first", newKey));
}
[Fact]
public void ChangeItemKey_NoSuchItem_ThrowsArgumentException()
{
var collection = new StringKeyedCollection<string>(StringComparer.OrdinalIgnoreCase, 3);
collection.GetKeyForItemHandler = item => item + "_key";
// Empty.
AssertExtensions.Throws<ArgumentException>("item", null, () => collection.ChangeItemKey("NoSuchItem", "other_key"));
AssertExtensions.Throws<ArgumentException>("item", null, () => collection.ChangeItemKey("FIRST", "other_key"));
// Without dictionary.
collection.Add("first");
AssertExtensions.Throws<ArgumentException>("item", null, () => collection.ChangeItemKey("NoSuchItem", "other_key"));
AssertExtensions.Throws<ArgumentException>("item", null, () => collection.ChangeItemKey("FIRST", "other_key"));
// With dictionary.
collection.Add("second");
collection.Add("third");
collection.Add("fourth");
AssertExtensions.Throws<ArgumentException>("item", null, () => collection.ChangeItemKey("NoSuchItem", "other_key"));
AssertExtensions.Throws<ArgumentException>("item", null, () => collection.ChangeItemKey("FIRST", "other_key"));
}
[Theory]
[InlineData("newKey")]
[InlineData("10")]
[InlineData("12")]
public void ChangeItemKey_DifferentKeyAfterCreation_ThrowsArgumentException(string newKey)
{
var collection = new StringKeyedCollection<int>(null, 3);
collection.GetKeyForItemHandler = item => item.ToString();
collection.Add(1);
collection.Add(2);
collection.Add(3);
Assert.Null(collection.Dictionary);
collection.GetKeyForItemHandler = item => (item * 2).ToString();
// Without dictionary.
collection.ChangeItemKey(2, "10");
Assert.Equal(new Dictionary<string, int>
{
{"2", 1},
{"10", 2},
{"6", 3}
}, collection.Dictionary
);
// With dictionary.
collection.Add(4);
AssertExtensions.Throws<ArgumentException>("item", null, () => collection.ChangeItemKey(2, newKey));
Assert.Equal(new Dictionary<string, int>
{
{"2", 1},
{"10", 2},
{"6", 3},
{"8", 4}
}, collection.Dictionary
);
}
public static IEnumerable<object[]> SetItem_TestData()
{
// Exceeding threshold.
yield return new object[] { null, 1, "first", new Dictionary<string, string> { { "first_key", "first" }, { "second_key", "second" }, { "third_key", "third" } } };
yield return new object[] { null, 1, "FIRST", new Dictionary<string, string> { { "FIRST_key", "FIRST" }, { "second_key", "second" }, { "third_key", "third" } } };
yield return new object[] { null, 1, "other", new Dictionary<string, string> { { "other_key", "other" }, { "second_key", "second" }, { "third_key", "third" } } };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 1, "first", new Dictionary<string, string> { { "first_key", "first" }, { "second_key", "second" }, { "third_key", "third" } } };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 1, "FIRST", new Dictionary<string, string> { { "first_key", "FIRST" }, { "second_key", "second" }, { "third_key", "third" } } };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 1, "other", new Dictionary<string, string> { { "other_key", "other" }, { "second_key", "second" }, { "third_key", "third" } } };
// Meeting threshold.
yield return new object[] { null, 3, "first", null };
yield return new object[] { null, 3, "FIRST", new Dictionary<String, String> { { "FIRST_key", "FIRST" }, { "second_key", "second" }, { "third_key", "third" } } };
yield return new object[] { null, 3, "other", new Dictionary<String, String> { { "other_key", "other" }, { "second_key", "second" }, { "third_key", "third" } } };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 3, "first", null };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 3, "FIRST", null };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 3, "other", new Dictionary<String, String> { { "other_key", "other" }, { "second_key", "second" }, { "third_key", "third" } } };
// Not meeting threshold.
yield return new object[] { null, 4, "first", null };
yield return new object[] { null, 4, "FIRST", null };
yield return new object[] { null, 4, "other", null };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 4, "first", null };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 4, "FIRST", null };
yield return new object[] { StringComparer.OrdinalIgnoreCase, 4, "other", null };
}
[Theory]
[MemberData(nameof(SetItem_TestData))]
public void SetItem_SameValue_Success(IEqualityComparer<string> comparer, int dictionaryCreationThreshold, string value, Dictionary<string, string> expectedDictionary)
{
var collection = new StringKeyedCollection<string>(comparer, dictionaryCreationThreshold);
collection.GetKeyForItemHandler = item => item + "_key";
collection.Add("first");
collection.Add("second");
collection.Add("third");
collection[0] = value;
Assert.Equal(new string[] { value, "second", "third" }, collection.Items.Cast<string>());
Assert.Equal(expectedDictionary, collection.Dictionary);
}
[Fact]
public void SetItem_NullNewKey_RemovesKey()
{
var collection = new StringKeyedCollection<int>();
collection.GetKeyForItemHandler = item => item.ToString();
collection.Add(1);
Assert.NotEmpty(collection.Dictionary);
// Don't add even numbers.
collection.GetKeyForItemHandler = item => item % 2 == 0 ? null : item.ToString();
collection[0] = 2;
Assert.Equal(new int[] { 2 }, collection.Items.Cast<int>());
Assert.Empty(collection.Dictionary);
}
[Fact]
public void SetItem_NullOldKey_DoesNotRemoveOldKey()
{
var collection = new StringKeyedCollection<int>();
collection.GetKeyForItemHandler = item => item.ToString();
collection.Add(2);
Assert.NotEmpty(collection.Dictionary);
// Don't add even numbers.
collection.GetKeyForItemHandler = item => item % 2 == 0 ? null : item.ToString();
collection[0] = 1;
Assert.Equal(new int[] { 1 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "1", 1 },
{ "2", 2 }
}, collection.Dictionary
);
}
[Fact]
public void SetItem_NullNewAndOldKey_DoesNotAffectDictionary()
{
var collection = new StringKeyedCollection<int>();
collection.GetKeyForItemHandler = item => item.ToString();
collection.Add(2);
Assert.NotEmpty(collection.Dictionary);
// Don't add even numbers.
collection.GetKeyForItemHandler = item => item % 2 == 0 ? null : item.ToString();
collection[0] = 4;
Assert.Equal(new int[] { 4 }, collection.Items.Cast<int>());
Assert.Equal(new Dictionary<string, int>
{
{ "2", 2 }
}, collection.Dictionary
);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void SetItem_InvalidIndex_ThrowsArgumentOutOfRangeException(int index)
{
var collection = new StringKeyedCollection<string>(null, 3);
collection.GetKeyForItemHandler = item => item + "_key";
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => collection.SetItem(index, "first"));
}
private class StringKeyedCollection<TItem> : KeyedCollection<string, TItem>
{
public StringKeyedCollection() : base()
{
}
public StringKeyedCollection(IEqualityComparer<string> comparer) : base(comparer)
{
}
public StringKeyedCollection(IEqualityComparer<string> comparer, int dictionaryCreationThreshold) : base(comparer, dictionaryCreationThreshold)
{
}
public Func<TItem, string> GetKeyForItemHandler { get; set; }
protected override string GetKeyForItem(TItem item)
{
return GetKeyForItemHandler(item);
}
public new IDictionary<string, TItem> Dictionary => base.Dictionary;
public new IList<TItem> Items => base.Items;
public new void InsertItem(int index, TItem item)
{
base.InsertItem(index, item);
}
public new void RemoveItem(int index)
{
base.RemoveItem(index);
}
public new void ClearItems()
{
base.ClearItems();
}
public new void ChangeItemKey(TItem item, string newKey)
{
base.ChangeItemKey(item, newKey);
}
public new void SetItem(int index, TItem item)
{
base.SetItem(index, item);
}
}
}
}
| |
using System;
using System.IO;
using System.Net;
using Google.GData.Client;
using Google.GData.Contacts;
using Google.GData.Extensions;
namespace Google.Contacts
{
/// <summary>
/// the base class for contacts elements
/// </summary>
public abstract class ContactBase : Entry
{
/// <summary>
/// returns if the Contact or Group is deleted
/// </summary>
/// <returns>the deleted status of the underlying object or false if no object set yet</returns>
public bool Deleted
{
get
{
BaseContactEntry b = AtomEntry as BaseContactEntry;
if (b != null)
{
return b.Deleted;
}
return false;
}
}
/// <summary>
/// returns the extended properties on this object
/// </summary>
/// <returns>the properties on the underlying object, or null if no
/// object set yet</returns>
public ExtensionCollection<ExtendedProperty> ExtendedProperties
{
get
{
BaseContactEntry b = AtomEntry as BaseContactEntry;
if (b != null)
{
return b.ExtendedProperties;
}
return null;
}
}
}
/// <summary>
/// the Contact entry for a Contacts Feed
/// </summary>
public class Contact : ContactBase
{
/// <summary>
/// readonly accessor for the ContactEntry that is underneath this object.
/// </summary>
/// <returns></returns>
public ContactEntry ContactEntry
{
get { return AtomEntry as ContactEntry; }
}
/// <summary>
/// convenience accessor to find the primary Email
/// there is no setter, to change this use the Primary Flag on
/// an individual object
/// </summary>
public EMail PrimaryEmail
{
get
{
EnsureInnerObject();
return ContactEntry.PrimaryEmail;
}
}
/// <summary>
/// convenience accessor to find the primary Phonenumber
/// there is no setter, to change this use the Primary Flag on
/// an individual object
/// </summary>
public PhoneNumber PrimaryPhonenumber
{
get
{
if (ContactEntry != null)
{
return ContactEntry.PrimaryPhonenumber;
}
return null;
}
}
/// <summary>
/// convenience accessor to find the primary PostalAddress
/// there is no setter, to change this use the Primary Flag on
/// an individual object
/// </summary>
public StructuredPostalAddress PrimaryPostalAddress
{
get
{
EnsureInnerObject();
return ContactEntry.PrimaryPostalAddress;
}
}
/// <summary>
/// convenience accessor to find the primary IMAddress
/// there is no setter, to change this use the Primary Flag on
/// an individual object
/// </summary>
public IMAddress PrimaryIMAddress
{
get
{
EnsureInnerObject();
return ContactEntry.PrimaryIMAddress;
}
}
/// <summary>
/// returns the groupmembership info on this object
/// </summary>
/// <returns></returns>
public ExtensionCollection<GroupMembership> GroupMembership
{
get
{
EnsureInnerObject();
return ContactEntry.GroupMembership;
}
}
/// <summary>
/// getter/setter for the email extension element
/// </summary>
public ExtensionCollection<EMail> Emails
{
get
{
EnsureInnerObject();
return ContactEntry.Emails;
}
}
/// <summary>
/// getter/setter for the IM extension element
/// </summary>
public ExtensionCollection<IMAddress> IMs
{
get
{
EnsureInnerObject();
return ContactEntry.IMs;
}
}
/// <summary>
/// returns the phone number collection
/// </summary>
public ExtensionCollection<PhoneNumber> Phonenumbers
{
get
{
EnsureInnerObject();
return ContactEntry.Phonenumbers;
}
}
/// <summary>
/// returns the postal address collection
/// </summary>
public ExtensionCollection<StructuredPostalAddress> PostalAddresses
{
get
{
EnsureInnerObject();
return ContactEntry.PostalAddresses;
}
}
/// <summary>
/// returns the organization collection
/// </summary>
public ExtensionCollection<Organization> Organizations
{
get
{
EnsureInnerObject();
return ContactEntry.Organizations;
}
}
/// <summary>
/// returns the language collection
/// </summary>
public ExtensionCollection<Language> Languages
{
get
{
EnsureInnerObject();
return ContactEntry.Languages;
}
}
/// <summary>
/// retrieves the Uri of the Photo Link. To set this, you need to create an AtomLink object
/// and add/replace it in the atomlinks colleciton.
/// </summary>
/// <returns></returns>
public Uri PhotoUri
{
get
{
EnsureInnerObject();
return ContactEntry.PhotoUri;
}
}
/// <summary>
/// if a photo is present on this contact, it will have an etag associated with it,
/// that needs to be used when you want to delete or update that picture.
/// </summary>
/// <returns>the etag value as a string</returns>
public string PhotoEtag
{
get
{
EnsureInnerObject();
return ContactEntry.PhotoEtag;
}
set
{
EnsureInnerObject();
ContactEntry.PhotoEtag = value;
}
}
/// <summary>
/// returns the location associated with a contact
/// </summary>
/// <returns></returns>
public string Location
{
get
{
EnsureInnerObject();
return ContactEntry.Location;
}
set
{
EnsureInnerObject();
ContactEntry.Location = value;
}
}
/// <summary>
/// the contacts name object
/// </summary>
public Name Name
{
get
{
EnsureInnerObject();
if (ContactEntry.Name == null)
ContactEntry.Name = new Name();
return ContactEntry.Name;
}
set
{
EnsureInnerObject();
ContactEntry.Name = value;
}
}
/// <summary>
/// creates the inner contact object when needed
/// </summary>
/// <returns></returns>
protected override void EnsureInnerObject()
{
if (AtomEntry == null)
{
AtomEntry = new ContactEntry();
}
}
}
/// <summary>
/// the group entry for a contacts groups Feed
/// </summary>
public class Group : ContactBase
{
/// <summary>
/// readonly accessor for the YouTubeEntry that is underneath this object.
/// </summary>
/// <returns></returns>
public GroupEntry GroupEntry
{
get { return AtomEntry as GroupEntry; }
}
/// <summary>
/// returns the systemgroup id, if this groupentry represents
/// a system group.
/// The values of the system group ids corresponding to these
/// groups can be found in the Reference Guide for the Contacts Data API.
/// Currently the values can be Contacts, Friends, Family and Coworkers
/// </summary>
/// <returns>the system group or null</returns>
public string SystemGroup
{
get
{
EnsureInnerObject();
return GroupEntry.SystemGroup;
}
}
/// <summary>
/// creates the inner contact object when needed
/// </summary>
/// <returns></returns>
protected override void EnsureInnerObject()
{
if (AtomEntry == null)
{
AtomEntry = new GroupEntry();
}
}
}
/// <summary>
/// The Contacts Data API provides two types of feed: contacts feed and
/// contact groups feed.
/// The feeds are private read/write feeds that can be used to view and
/// manage a user's contacts/groups. Since they are private, a programmer
/// can access them only by using an authenticated request. That is, the
/// request must contain an authentication token for the user whose
/// contacts you want to retrieve.
/// </summary>
/// <example>
/// The following code illustrates a possible use of
/// the <c>ContactsRequest</c> object:
/// <code>
/// RequestSettings settings = new RequestSettings("yourApp");
/// settings.PageSize = 50;
/// settings.AutoPaging = true;
/// ContactsRequest c = new ContactsRequest(settings);
/// Feed<Contacts> feed = c.GetContacts();
///
/// foreach (Contact contact in feed.Entries)
/// {
/// Console.WriteLine(contact.Title);
/// }
/// </code>
/// </example>
public class ContactsRequest : FeedRequest<ContactsService>
{
/// <summary>
/// default constructor for a YouTubeRequest
/// </summary>
/// <param name="settings"></param>
public ContactsRequest(RequestSettings settings)
: base(settings)
{
Service = new ContactsService(settings.Application);
PrepareService();
}
/// <summary>
/// returns a Feed of contacts for the default user
/// </summary>
/// <returns>a feed of Contacts</returns>
public Feed<Contact> GetContacts()
{
return GetContacts(null);
}
/// <summary>
/// returns a Feed of contacts for the given user
/// </summary>
/// <param name="user">the username</param>
/// <returns>a feed of Contacts</returns>
public Feed<Contact> GetContacts(string user)
{
ContactsQuery q = PrepareQuery<ContactsQuery>(ContactsQuery.CreateContactsUri(user));
return PrepareFeed<Contact>(q);
}
/// <summary>
/// returns a feed of Groups for the default user
/// </summary>
/// <returns>a feed of Groups</returns>
public Feed<Group> GetGroups()
{
return GetGroups(null);
}
/// <summary>
/// returns a feed of Groups for the given user
/// </summary>
/// <param name="user">the user for whom to retrieve the feed</param>
/// <returns>a feed of Groups</returns>
public Feed<Group> GetGroups(string user)
{
GroupsQuery q = PrepareQuery<GroupsQuery>(GroupsQuery.CreateGroupsUri(user));
return PrepareFeed<Group>(q);
}
/// <summary>
/// returns the photo stream for a given contact. If there is no photo,
/// the 404 is catched and null is returned.
/// </summary>
/// <param name="c">the contact that you want to get the photo of</param>
/// <returns></returns>
public Stream GetPhoto(Contact c)
{
Stream retStream = null;
try
{
if (c.PhotoUri != null)
{
retStream = Service.Query(c.PhotoUri, c.PhotoEtag);
}
}
catch (GDataRequestException e)
{
HttpWebResponse r = e.Response as HttpWebResponse;
if (r != null && r.StatusCode != HttpStatusCode.NotFound)
{
throw;
}
}
return retStream;
}
/// <summary>
/// sets the photo of a given contact entry
/// </summary>
/// <param name="c">the contact that should be modified</param>
/// <param name="photoStream">a stream to an JPG image</param>
/// <returns></returns>
public void SetPhoto(Contact c, Stream photoStream)
{
Stream res = Service.StreamSend(c.PhotoUri, photoStream, GDataRequestType.Update, "image/jpg", null,
c.PhotoEtag);
GDataReturnStream r = res as GDataReturnStream;
if (r != null)
{
c.PhotoEtag = r.Etag;
}
res.Close();
}
/// <summary>
/// sets the photo of a given contact entry
/// </summary>
/// <param name="c">the contact that should be modified</param>
/// <param name="photoStream">a stream to an JPG image</param>
/// <param name="mimeType">specifies the MIME type of the image, e.g. image/jpg</param>
/// <returns></returns>
public void SetPhoto(Contact c, Stream photoStream, string mimeType)
{
Stream res = Service.StreamSend(c.PhotoUri, photoStream, GDataRequestType.Update, mimeType, null,
c.PhotoEtag);
res.Close();
}
}
}
| |
// Copyright 2017 (c) [Denis Da Silva]. All rights reserved.
// See License.txt in the project root for license information.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Prolix.Collections;
using Prolix.Client.Extensions;
namespace Prolix.Client.Api
{
/// <summary>
/// Generic REST Client Service
/// </summary>
public class RestService : IRestService
{
#region Constructors
public RestService()
{
}
public RestService(string baseUrl, IDictionary<string, string> defaultHeaders)
{
BaseUrl = baseUrl;
DefaultHeaders = defaultHeaders;
}
#endregion
#region Properties
public string BaseUrl { get; set; }
public IDictionary<string, string> DefaultHeaders { get; set; } = new WeakDictionary<string, string>();
IHttpService HttpService => new HttpService(BaseUrl, DefaultHeaders);
#endregion
#region Static Constructor
static RestService()
{
// Initialize common json configuration
JsonExtensions.IgnoreErrors();
}
#endregion
#region Public Methods
/// <summary>
/// Performs GET calls to get an individual resource.
/// </summary>
/// <typeparam name="T">The result model type</typeparam>
/// <param name="resource">The relative endpoint Url</param>
/// <param name="param">The endpoint parameters</param>
/// <returns>The requested model</returns>
async public virtual Task<HttpBody<T>> Get<T>(string resource, object param = null)
where T : class, new()
{
return await GetApi<T>(resource, param);
}
/// <summary>
/// Performs GET calls to get a list of resources.
/// </summary>
/// <typeparam name="T">The result model type</typeparam>
/// <param name="resource">The relative endpoint Url</param>
/// <param name="param">The endpoint parameters</param>
/// <returns>The requested model list</returns>
async public Task<HttpBody<T[]>> List<T>(string resource, object param = null)
where T : class
{
return await GetApi<T[]>(resource, param);
}
/// <summary>
/// Performs POST calls to add a new resource.
/// </summary>
/// <typeparam name="TR">The result model type</typeparam>
/// <typeparam name="TB">The body type</typeparam>
/// <param name="resource">The relative endpoint Url</param>
/// <param name="body">The body data</param>
/// <returns>The requested response</returns>
async public virtual Task<HttpBody<TR>> Post<TR, TB>(string resource, HttpBody<TB> body)
where TR : class
where TB : class
{
return await PostApi<TR, TB>(resource, body);
}
/// <summary>
/// Performs POST calls to add a new resource.
/// </summary>
/// <typeparam name="T">The body type</typeparam>
/// <param name="resource">The relative endpoint Url</param>
/// <param name="body">The body data</param>
/// <returns>The requested response</returns>
async public virtual Task<HttpBody<T>> Post<T>(string resource, HttpBody<T> body)
where T : class
{
return await Post<T, T>(resource, body);
}
/// <summary>
/// Performs PUT calls to add an existing resource.
/// </summary>
/// <typeparam name="TR">The result model type</typeparam>
/// <typeparam name="TB">The body type</typeparam>
/// <param name="resource">The relative endpoint Url</param>
/// <param name="body">The body data</param>
/// <returns>The requested response</returns>
async public virtual Task<HttpBody<TR>> Put<TR, TB>(string resource, HttpBody<TB> body)
where TR : class
where TB : class
{
return await PutApi<TR>(resource, body?.Content);
}
/// <summary>
/// Performs PUT calls to add an existing resource.
/// </summary>
/// <typeparam name="T">The body type</typeparam>
/// <param name="resource">The relative endpoint Url</param>
/// <param name="body">The body data</param>
/// <returns>The requested response</returns>
async public virtual Task<HttpBody<T>> Put<T>(string resource, HttpBody<T> body)
where T : class
{
return await Put<T, T>(resource, body);
}
/// <summary>
/// Performs DELETE calls to remove an existing resource.
/// </summary>
/// <typeparam name="T">The body type</typeparam>
/// <param name="resource">The relative endpoint Url</param>
/// <returns>The requested response</returns>
async public virtual Task<HttpBody<T>> Delete<T>(string resource)
where T : class
{
return await DeleteApi<T>(resource);
}
#endregion
#region Private Methods
async Task<HttpBody<T>> GetApi<T>(string resourceOrUrl, object param)
where T : class
{
HttpBody<T> result;
try
{
// Builds the url
string url = param.ToQueryString(resourceOrUrl);
// Gets JSON and parse the result
StringBody response = await HttpService.Get(url);
T data = JsonConvert.DeserializeObject<T>(response.Content);
result = new HttpBody<T>(data, response);
}
catch (HttpException)
{
throw;
}
catch (Exception ex)
{
throw new HttpException(ex);
}
return result;
}
async Task<HttpBody<TR>> PostApi<TR, TB>(string url, HttpBody<TB> body)
where TR : class
where TB: class
{
HttpBody<TR> result;
try
{
HttpBody<string> response;
if (body.IsForm)
{
// Post FORM and parse the result
var dic = body.ToFormDictionaty();
response = await HttpService.Post(url, dic);
}
else
{
string json = string.Empty;
// Post JSON and parse the result
if (body.Content != null)
{
if (body.GetType() == typeof(string))
json = body as string;
else
json = JsonConvert.SerializeObject(body.Content);
}
response = await HttpService.Post(url, json);
}
var data = JsonConvert.DeserializeObject<TR>(response.Content);
result = new HttpBody<TR>(data, response);
}
catch (HttpException)
{
throw;
}
catch (Exception ex)
{
throw new HttpException(ex);
}
return result;
}
async Task<HttpBody<TR>> PutApi<TR>(string url, object input)
where TR : class
{
HttpBody<TR> result;
try
{
var json = JsonConvert.SerializeObject(input);
var response = await HttpService.Put(url, json);
var data = JsonConvert.DeserializeObject<TR>(response.Content);
result = new HttpBody<TR>(data, response);
}
catch (HttpException)
{
throw;
}
catch (Exception ex)
{
throw new HttpException(ex);
}
return result;
}
async Task<HttpBody<T>> DeleteApi<T>(string url)
where T : class
{
HttpBody<T> result;
try
{
var response = await HttpService.Delete(url);
var data = JsonConvert.DeserializeObject<T>(response.Content);
result = new HttpBody<T>(data, response);
}
catch (HttpException)
{
throw;
}
catch (Exception ex)
{
throw new HttpException(ex);
}
return result;
}
#endregion
}
}
| |
//This file has been modifed with suggestions from forum users.
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* 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 Reporting.Rdl;
using System.IO;
using System.Collections;
using System.Drawing.Imaging;
using System.Text;
using System.Xml;
using System.Globalization;
using System.Drawing;
namespace Reporting.Rdl
{
///<summary>
/// Renders a report to HTML. This handles some page formating but does not do true page formatting.
///</summary>
internal class RenderHtml: IPresent
{
Report r; // report
StringWriter tw; // temporary location where the output is going
IStreamGen _sg; // stream generater
Hashtable _styles; // hash table of styles we've generated
int cssId=1; // ID for css when names are usable or available
bool bScriptToggle=false; // need to generate toggle javascript in header
bool bScriptTableSort=false; // need to generate table sort javascript in header
Bitmap _bm=null; // bm and
Graphics _g=null; // g are needed when calculating string heights
bool _Asp=false; // denotes ASP.NET compatible HTML; e.g. no <html>, <body>
// separate JavaScript and CSS
string _Prefix=""; // prefix to generating all HTML names (e.g. css, ...
string _CSS; // when ASP we put the CSS into a string
string _JavaScript; // as well as any required javascript
int _SkipMatrixCols=0; // # of matrix columns to skip
public RenderHtml(Report rep, IStreamGen sg)
{
r = rep;
_sg = sg; // We need this in future
tw = new StringWriter(); // will hold the bulk of the HTML until we generate
// final file
_styles = new Hashtable();
}
//Replaced from forum, User: Aulofee http://www.fyireporting.com/forum/viewtopic.php?t=793
//~RenderHtml()
public void Dispose()
{
// These should already be cleaned up; but in case of an unexpected error
// these still need to be disposed of
if (_bm != null)
_bm.Dispose();
if (_g != null)
_g.Dispose();
}
public Report Report()
{
return r;
}
public bool Asp
{
get {return _Asp;}
set {_Asp = value;}
}
public string JavaScript
{
get {return _JavaScript;}
}
public string CSS
{
get {return _CSS;}
}
public string Prefix
{
get {return _Prefix;}
set
{
_Prefix = value==null? "": value;
if (_Prefix.Length > 0 &&
_Prefix[0] == '_')
_Prefix = "a" + _Prefix; // not perfect but underscores as first letter don't work
}
}
public bool IsPagingNeeded()
{
return false;
}
public void Start()
{
return;
}
string FixupRelativeName(string relativeName)
{
if (_sg is OneFileStreamGen)
{
if (relativeName[0] == Path.DirectorySeparatorChar || relativeName[0] == Path.AltDirectorySeparatorChar)
relativeName = relativeName.Substring(1);
}
else if (!(relativeName[0] == Path.DirectorySeparatorChar || relativeName[0] == Path.AltDirectorySeparatorChar))
{
if (_Asp)
relativeName = "/" + relativeName; // Hack for Firefox
else
relativeName = Path.DirectorySeparatorChar + relativeName;
}
return relativeName;
}
// puts the JavaScript into the header
private void ScriptGenerate(TextWriter ftw)
{
if (bScriptToggle || bScriptTableSort)
{
ftw.WriteLine("<script language=\"javascript\">");
}
if (bScriptToggle)
{
ftw.WriteLine("var dname='';");
ftw.WriteLine(@"function hideShow(node, hideCount, showID) {
if (navigator.appName.toLowerCase().indexOf('netscape') > -1)
dname = 'table-row';
else
dname = 'block';
var tNode;
for (var ci=0;ci<node.childNodes.length;ci++) {
if (node.childNodes[ci].tagName && node.childNodes[ci].tagName.toLowerCase() == 'img') tNode = node.childNodes[ci];
}
var rows = findObject(showID);
if (rows[0].style.display == dname) {hideRows(rows, hideCount); tNode.src='plus.gif';}
else {
tNode.src='minus.gif';
for (var i = 0; i < rows.length; i++) {
rows[i].style.display = dname;
}
}
}
function hideRows(rows, count) {
var row;
if (navigator.appName.toLowerCase().indexOf('netscape') > -1)
{
for (var r=0; r < rows.length; r++) {
row = rows[r];
row.style.display = 'none';
var imgs = row.getElementsByTagName('img');
for (var ci=0;ci<imgs.length;ci++) {
if (imgs[ci].className == 'toggle') {
imgs[ci].src='plus.gif';
}
}
}
return;
}
if (rows.tagName == 'TR')
row = rows;
else
row = rows[0];
while (count > 0) {
row.style.display = 'none';
var imgs = row.getElementsByTagName('img');
for (var ci=0;ci<imgs.length;ci++) {
if (imgs[ci].className == 'toggle') {
imgs[ci].src='plus.gif';
}
}
row = row.nextSibling;
count--;
}
}
function findObject(id) {
if (navigator.appName.toLowerCase().indexOf('netscape') > -1)
{
var a = new Array();
var count=0;
for (var i=0; i < document.all.length; i++)
{
if (document.all[i].id == id)
a[count++] = document.all[i];
}
return a;
}
else
{
var o = document.all[id];
if (o.tagName == 'TR')
{
var a = new Array();
a[0] = o;
return a;
}
return o;
}
}
");
}
if (bScriptTableSort)
{
ftw.WriteLine("var SORT_INDEX;");
ftw.WriteLine("var SORT_DIR;");
ftw.WriteLine("function sort_getInnerText(element) {");
ftw.WriteLine(" if (typeof element == 'string') return element;");
ftw.WriteLine(" if (typeof element == 'undefined') return element;");
ftw.WriteLine(" if (element.innerText) return element.innerText;");
ftw.WriteLine(" var s = '';");
ftw.WriteLine(" var cn = element.childNodes;");
ftw.WriteLine(" for (var i = 0; i < cn.length; i++) {");
ftw.WriteLine(" switch (cn[i].nodeType) {");
ftw.WriteLine(" case 1:"); // element node
ftw.WriteLine(" s += sort_getInnerText(cn[i]);");
ftw.WriteLine(" break;");
ftw.WriteLine(" case 3:"); // text node
ftw.WriteLine(" s += cn[i].nodeValue;");
ftw.WriteLine(" break;");
ftw.WriteLine(" }");
ftw.WriteLine(" }");
ftw.WriteLine(" return s;");
ftw.WriteLine("}");
ftw.WriteLine("function sort_table(node, sortfn, header_rows, footer_rows) {");
ftw.WriteLine(" var arrowNode;"); // arrow node
ftw.WriteLine(" for (var ci=0;ci<node.childNodes.length;ci++) {");
ftw.WriteLine(" if (node.childNodes[ci].tagName && node.childNodes[ci].tagName.toLowerCase() == 'span') arrowNode = node.childNodes[ci];");
ftw.WriteLine(" }");
ftw.WriteLine(" var td = node.parentNode;");
ftw.WriteLine(" SORT_INDEX = td.cellIndex;"); // need to remember SORT_INDEX in compare function
ftw.WriteLine(" var table = sort_getTable(td);");
ftw.WriteLine(" var sortnext;");
ftw.WriteLine(" if (arrowNode.getAttribute('sortdir') == 'down') {");
ftw.WriteLine(" arrow = ' ↑';");
ftw.WriteLine(" SORT_DIR = -1;"); // descending SORT_DIR in compare function
ftw.WriteLine(" sortnext = 'up';");
ftw.WriteLine(" } else {");
ftw.WriteLine(" arrow = ' ↓';");
ftw.WriteLine(" SORT_DIR = 1;"); // ascending SORT_DIR in compare function
ftw.WriteLine(" sortnext = 'down';");
ftw.WriteLine(" }");
ftw.WriteLine(" var newRows = new Array();");
ftw.WriteLine(" for (j=header_rows;j<table.rows.length-footer_rows;j++) { newRows[j-header_rows] = table.rows[j]; }");
ftw.WriteLine(" newRows.sort(sortfn);");
// We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
ftw.WriteLine(" for (i=0;i<newRows.length;i++) {table.tBodies[0].appendChild(newRows[i]);}");
// Reset all arrows and directions for next time
ftw.WriteLine(" var spans = document.getElementsByTagName('span');");
ftw.WriteLine(" for (var ci=0;ci<spans.length;ci++) {");
ftw.WriteLine(" if (spans[ci].className == 'sortarrow') {");
// in the same table as us?
ftw.WriteLine(" if (sort_getTable(spans[ci]) == sort_getTable(node)) {");
ftw.WriteLine(" spans[ci].innerHTML = ' ';");
ftw.WriteLine(" spans[ci].setAttribute('sortdir','up');");
ftw.WriteLine(" }");
ftw.WriteLine(" }");
ftw.WriteLine(" }");
ftw.WriteLine(" arrowNode.innerHTML = arrow;");
ftw.WriteLine(" arrowNode.setAttribute('sortdir',sortnext);");
ftw.WriteLine("}");
ftw.WriteLine("function sort_getTable(el) {");
ftw.WriteLine(" if (el == null) return null;");
ftw.WriteLine(" else if (el.nodeType == 1 && el.tagName.toLowerCase() == 'table')");
ftw.WriteLine(" return el;");
ftw.WriteLine(" else");
ftw.WriteLine(" return sort_getTable(el.parentNode);");
ftw.WriteLine("}");
ftw.WriteLine("function sort_cmp_date(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]);");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]);");
ftw.WriteLine(" dt1 = new Date(t1);");
ftw.WriteLine(" dt2 = new Date(t2);");
ftw.WriteLine(" if (dt1==dt2) return 0;");
ftw.WriteLine(" if (dt1<dt2) return -SORT_DIR;");
ftw.WriteLine(" return SORT_DIR;");
ftw.WriteLine("}");
// numeric - removes any extraneous formating characters before parsing
ftw.WriteLine("function sort_cmp_number(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]).replace(/[^0-9.]/g,'');");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]).replace(/[^0-9.]/g,'');");
ftw.WriteLine(" n1 = parseFloat(t1);");
ftw.WriteLine(" n2 = parseFloat(t2);");
ftw.WriteLine(" if (isNaN(n1)) n1 = Number.MAX_VALUE");
ftw.WriteLine(" if (isNaN(n2)) n2 = Number.MAX_VALUE");
ftw.WriteLine(" return (n1 - n2)*SORT_DIR;");
ftw.WriteLine("}");
// For string we first do a case insensitive comparison;
// when equal we then do a case sensitive comparison
ftw.WriteLine("function sort_cmp_string(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]).toLowerCase();");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]).toLowerCase();");
ftw.WriteLine(" if (t1==t2) return sort_cmp_casesensitive(c1,c2);");
ftw.WriteLine(" if (t1<t2) return -SORT_DIR;");
ftw.WriteLine(" return SORT_DIR;");
ftw.WriteLine("}");
ftw.WriteLine("function sort_cmp_casesensitive(c1,c2) {");
ftw.WriteLine(" t1 = sort_getInnerText(c1.cells[SORT_INDEX]);");
ftw.WriteLine(" t2 = sort_getInnerText(c2.cells[SORT_INDEX]);");
ftw.WriteLine(" if (t1==t2) return 0;");
ftw.WriteLine(" if (t2<t2) return -SORT_DIR;");
ftw.WriteLine(" return SORT_DIR;");
ftw.WriteLine("}");
}
if (bScriptToggle || bScriptTableSort)
{
ftw.WriteLine("</script>");
}
return;
}
// handle the Action tag
private string Action(Action a, Row r, string t, string tooltip)
{
if (a == null)
return t;
string result = t;
if (a.Hyperlink != null)
{ // Handle a hyperlink
string url = a.HyperLinkValue(this.r, r);
if (tooltip == null)
result = String.Format("<a target=\"_top\" href=\"{0}\">{1}</a>", url, t);
else
result = String.Format("<a target=\"_top\" href=\"{0}\" title=\"{1}\">{2}</a>", url, tooltip, t);
}
else if (a.Drill != null)
{ // Handle a drill through
StringBuilder args= new StringBuilder("<a target=\"_top\" href=\"");
if (_Asp) // for ASP we go thru the default page and pass it as an argument
args.Append("Default.aspx?rs:url=");
args.Append(a.Drill.ReportName);
args.Append(".rdl");
if (a.Drill.DrillthroughParameters != null)
{
bool bFirst = !_Asp; // ASP already have an argument
foreach (DrillthroughParameter dtp in a.Drill.DrillthroughParameters.Items)
{
if (!dtp.OmitValue(this.r, r))
{
if (bFirst)
{ // First parameter - prefixed by '?'
args.Append('?');
bFirst = false;
}
else
{ // Subsequant parameters - prefixed by '&'
args.Append('&');
}
args.Append(dtp.Name.Nm);
args.Append('=');
args.Append(dtp.ValueValue(this.r, r));
}
}
}
args.Append('"');
if (tooltip != null)
args.Append(String.Format(" title=\"{0}\"", tooltip));
args.Append(">");
args.Append(t);
args.Append("</a>");
result = args.ToString();
}
else if (a.BookmarkLink != null)
{ // Handle a bookmark
string bm = a.BookmarkLinkValue(this.r, r);
if (tooltip == null)
result = String.Format("<a href=\"#{0}\">{1}</a>", bm, t);
else
result = String.Format("<a href=\"#{0}\" title=\"{1}\">{2}</a>", bm, tooltip, t);
}
return result;
}
private string Bookmark(string bm, string t)
{
if (bm == null)
return t;
return String.Format("<div id=\"{0}\">{1}</div>", bm, t);
}
// Generate the CSS styles and put them in the header
private void CssGenerate(TextWriter ftw)
{
if (_styles.Count <= 0)
return;
if (!_Asp)
ftw.WriteLine("<style type='text/css'>");
foreach (CssCacheEntry cce in _styles.Values)
{
int i = cce.Css.IndexOf('{');
if (cce.Name.IndexOf('#') >= 0)
ftw.WriteLine("{0} {1}", cce.Name, cce.Css.Substring(i));
else
ftw.WriteLine(".{0} {1}", cce.Name, cce.Css.Substring(i));
}
if (!_Asp)
ftw.WriteLine("</style>");
}
private string CssAdd(Style s, ReportLink rl, Row row)
{
return CssAdd(s, rl, row, false, float.MinValue, float.MinValue);
}
private string CssAdd(Style s, ReportLink rl, Row row, bool bForceRelative)
{
return CssAdd(s, rl, row, bForceRelative, float.MinValue, float.MinValue);
}
private string CssAdd(Style s, ReportLink rl, Row row, bool bForceRelative, float h, float w)
{
string css;
string prefix = CssPrefix(s, rl);
if (_Asp && prefix == "table#")
bForceRelative = true;
if (s != null)
css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + s.GetCSS(this.r, row, true) + "}";
else if (rl is Table || rl is Matrix)
css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + "border-collapse:collapse;}";
else
css = prefix + "{" + CssPosition(rl, row, bForceRelative, h, w) + "}";
CssCacheEntry cce = (CssCacheEntry) _styles[css];
if (cce == null)
{
string name = prefix + this.Prefix + "css" + cssId++.ToString();
cce = new CssCacheEntry(css, name);
_styles.Add(cce.Css, cce);
}
int i = cce.Name.IndexOf('#');
if (i > 0)
return cce.Name.Substring(i+1);
else
return cce.Name;
}
private string CssPosition(ReportLink rl,Row row, bool bForceRelative, float h, float w)
{
if (!(rl is ReportItem)) // if not a report item then no position
return "";
// no positioning within a table
for (ReportLink p=rl.Parent; p != null; p=p.Parent)
{
if (p is TableCell)
return "";
if (p is RowGrouping ||
p is MatrixCell ||
p is ColumnGrouping ||
p is Corner)
{
StringBuilder sb2 = new StringBuilder();
if (h != float.MinValue)
sb2.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}pt; ", h);
if (w != float.MinValue)
sb2.AppendFormat(NumberFormatInfo.InvariantInfo, "width: {0}pt; ", w);
return sb2.ToString();
}
}
// TODO: optimize by putting this into ReportItem and caching result???
ReportItem ri = (ReportItem) rl;
StringBuilder sb = new StringBuilder();
if (ri.Left != null && ri.Left.Size > 0)
{
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "left: {0}; ", ri.Left.CSS);
}
if (ri is Matrix || ri is Image || ri is Chart)
{ }
else
{
if (ri.Width != null)
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "width: {0}; ", ri.Width.CSS);
}
if (ri.Top != null && ri.Top.Size > 0)
{
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "top: {0}pt; ", ri.Gap(this.r));
}
if (ri is List)
{
List l = ri as List;
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}pt; ", l.HeightOfList(this.r, GetGraphics,row));
}
else if (ri is Matrix || ri is Table || ri is Image || ri is Chart)
{}
else if (ri.Height != null)
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "height: {0}; ", ri.Height.CSS);
if (sb.Length > 0)
{
if (bForceRelative || ri.YParents != null)
sb.Insert(0, "position: relative; ");
else
sb.Insert(0, "position: absolute; ");
}
return sb.ToString();
}
private Graphics GetGraphics
{
get
{
if (_g == null)
{
_bm = new Bitmap(10, 10);
_g = Graphics.FromImage(_bm);
}
return _g;
}
}
private string CssPrefix(Style s, ReportLink rl)
{
string cssPrefix=null;
ReportLink p;
if (rl is Table || rl is Matrix || rl is Rectangle)
{
cssPrefix = "table#";
}
else if (rl is Body)
{
cssPrefix = "body#";
}
else if (rl is Line)
{
cssPrefix = "table#";
}
else if (rl is List)
{
cssPrefix = "";
}
else if (rl is Subreport)
{
cssPrefix = "";
}
else if (rl is Chart)
{
cssPrefix = "";
}
if (cssPrefix != null)
return cssPrefix;
// now find what the style applies to
for (p=rl.Parent; p != null; p=p.Parent)
{
if (p is TableCell)
{
bool bHead = false;
ReportLink p2;
for (p2=p.Parent; p2 != null; p2=p2.Parent)
{
Type t2 = p2.GetType();
if (t2 == typeof(Header))
{
if (p2.Parent is Table)
bHead=true;
break;
}
}
if (bHead)
cssPrefix = "th#";
else
cssPrefix = "td#";
break;
}
else if (p is RowGrouping ||
p is MatrixCell ||
p is ColumnGrouping ||
p is Corner)
{
cssPrefix = "td#";
break;
}
}
return cssPrefix == null? "": cssPrefix;
}
public void End()
{
string bodyCssId;
if (r.ReportDefinition.Body != null)
bodyCssId = CssAdd(r.ReportDefinition.Body.Style, r.ReportDefinition.Body, null); // add the style for the body
else
bodyCssId = null;
TextWriter ftw = _sg.GetTextWriter(); // the final text writer location
if (_Asp)
{
// do any required JavaScript
StringWriter sw = new StringWriter();
ScriptGenerate(sw);
_JavaScript = sw.ToString();
sw.Close();
// do any required CSS
sw = new StringWriter();
CssGenerate(sw);
_CSS = sw.ToString();
sw.Close();
}
else
{
ftw.WriteLine("<html>");
// handle the <head>: description, javascript and CSS goes here
ftw.WriteLine("<head>");
ScriptGenerate(ftw);
CssGenerate(ftw);
if (r.Description != null) // Use description as title if provided
ftw.WriteLine(string.Format(@"<title>{0}</title>", Xml.ToXmlAnsi(r.Description)));
ftw.WriteLine(@"</head>");
}
// Always want an HTML body - even if report doesn't have a body stmt
if (this._Asp)
{
ftw.WriteLine("<table style=\"position: relative;\">");
}
else if (bodyCssId != null)
ftw.WriteLine(@"<body id='{0}'><table>", bodyCssId);
else
ftw.WriteLine("<body><table>");
ftw.Write(tw.ToString());
if (this._Asp)
ftw.WriteLine(@"</table>");
else
ftw.WriteLine(@"</table></body></html>");
if (_g != null)
{
_g.Dispose();
_g = null;
}
if (_bm != null)
{
_bm.Dispose();
_bm = null;
}
return;
}
// Body: main container for the report
public void BodyStart(Body b)
{
if (b.ReportItems != null && b.ReportItems.Items.Count > 0)
tw.WriteLine("<tr><td><div style=\"POSITION: relative; \">");
}
public void BodyEnd(Body b)
{
if (b.ReportItems != null && b.ReportItems.Items.Count > 0)
tw.WriteLine("</div></td></tr>");
}
public void PageHeaderStart(PageHeader ph)
{
if (ph.ReportItems != null && ph.ReportItems.Items.Count > 0)
tw.WriteLine("<tr><td><div style=\"overflow: clip; POSITION: relative; HEIGHT: {0};\">", ph.Height.CSS);
}
public void PageHeaderEnd(PageHeader ph)
{
if (ph.ReportItems != null && ph.ReportItems.Items.Count > 0)
tw.WriteLine("</div></td></tr>");
}
public void PageFooterStart(PageFooter pf)
{
if (pf.ReportItems != null && pf.ReportItems.Items.Count > 0)
tw.WriteLine("<tr><td><div style=\"overflow: clip; POSITION: relative; HEIGHT: {0};\">", pf.Height.CSS);
}
public void PageFooterEnd(PageFooter pf)
{
if (pf.ReportItems != null && pf.ReportItems.Items.Count > 0)
tw.WriteLine("</div></td></tr>");
}
public void Textbox(Textbox tb, string t, Row row)
{
if (tb.IsHtml(this.r, row)) // we leave the text as is (except to handle unicode) when request is to treat as html
{ // this can screw up the generated HTML if not properly formed HTML
t = Xml.ToHtmlAnsi(t);
}
else
{
// make all the characters browser readable
t = Xml.ToXmlAnsi(t);
// handle any specified bookmark
t = Bookmark(tb.BookmarkValue(this.r, row), t);
// handle any specified actions
t = Action(tb.Action, row, t, tb.ToolTipValue(this.r, row));
}
// determine if we're in a tablecell
Type tp = tb.Parent.Parent.GetType();
bool bCell;
if (tp == typeof(TableCell) ||
tp == typeof(Corner) ||
tp == typeof(DynamicColumns) ||
tp == typeof(DynamicRows) ||
tp == typeof(StaticRow) ||
tp == typeof(StaticColumn) ||
tp == typeof(Subtotal) ||
tp == typeof(MatrixCell))
bCell = true;
else
bCell = false;
if (tp == typeof(Rectangle))
tw.Write("<td>");
if (bCell)
{ // The cell has the formatting for this text
if (t == "")
tw.Write("<br />"); // must have something in cell for formating
else
tw.Write(t);
}
else
{ // Formatting must be specified
string cssName = CssAdd(tb.Style, tb, row); // get the style name for this item
tw.Write("<div class='{0}'>{1}</div>", cssName, t);
}
if (tp == typeof(Rectangle))
tw.Write("</td>");
}
public void DataRegionNoRows(DataRegion d, string noRowsMsg) // no rows in table
{
if (noRowsMsg == null)
noRowsMsg = "";
bool bTableCell = d.Parent.Parent.GetType() == typeof(TableCell);
if (bTableCell)
{
if (noRowsMsg == "")
tw.Write("<br />");
else
tw.Write(noRowsMsg);
}
else
{
string cssName = CssAdd(d.Style, d, null); // get the style name for this item
tw.Write("<div class='{0}'>{1}</div>", cssName, noRowsMsg);
}
}
// Lists
public bool ListStart(List l, Row r)
{
// identifiy reportitem it if necessary
string bookmark = l.BookmarkValue(this.r, r);
if (bookmark != null) //
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
return true;
}
public void ListEnd(List l, Row r)
{
string bookmark = l.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("</div>");
}
public void ListEntryBegin(List l, Row r)
{
string cssName = CssAdd(l.Style, l, r, true); // get the style name for this item; force to be relative
tw.WriteLine();
tw.WriteLine("<div class={0}>", cssName);
}
public void ListEntryEnd(List l, Row r)
{
tw.WriteLine();
tw.WriteLine("</div>");
}
// Tables // Report item table
public bool TableStart(Table t, Row row)
{
string cssName = CssAdd(t.Style, t, row); // get the style name for this item
// Determine if report custom defn want this table to be sortable
if (IsTableSortable(t))
{
this.bScriptTableSort = true;
}
string bookmark = t.BookmarkValue(this.r, row);
if (bookmark != null)
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
// Calculate the width of all the columns
int width = t.WidthInPixels(this.r, row);
if (width <= 0)
tw.WriteLine("<table id='{0}'>", cssName);
else
tw.WriteLine("<table id='{0}' width={1}>", cssName, width);
return true;
}
public bool IsTableSortable(Table t)
{
if (t.TableGroups != null || t.Details == null ||
t.Details.TableRows == null || t.Details.TableRows.Items.Count != 1)
return false; // can't have tableGroups; must have 1 detail row
// Determine if report custom defn want this table to be sortable
bool bReturn = false;
if (t.Custom != null)
{
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in t.Custom.CustomXmlNode.ChildNodes)
{
if (xNodeLoop.Name == "HTML")
{
if (xNodeLoop.LastChild.InnerText.ToLower() == "true")
{
bReturn = true;
}
break;
}
}
}
return bReturn;
}
public void TableEnd(Table t, Row row)
{
string bookmark = t.BookmarkValue(this.r, row);
if (bookmark != null)
tw.WriteLine("</div>");
tw.WriteLine("</table>");
return;
}
public void TableBodyStart(Table t, Row row)
{
tw.WriteLine("<tbody>");
}
public void TableBodyEnd(Table t, Row row)
{
tw.WriteLine("</tbody>");
}
public void TableFooterStart(Footer f, Row row)
{
tw.WriteLine("<tfoot>");
}
public void TableFooterEnd(Footer f, Row row)
{
tw.WriteLine("</tfoot>");
}
public void TableHeaderStart(Header h, Row row)
{
tw.WriteLine("<thead>");
}
public void TableHeaderEnd(Header h, Row row)
{
tw.WriteLine("</thead>");
}
public void TableRowStart(TableRow tr, Row row)
{
tw.Write("\t<tr");
ReportLink rl = tr.Parent.Parent;
Visibility v=null;
Textbox togText=null; // holds the toggle text box if any
if (rl is Details)
{
Details d = (Details) rl;
v = d.Visibility;
togText = d.ToggleTextbox;
}
else if (rl.Parent is TableGroup)
{
TableGroup tg = (TableGroup) rl.Parent;
v = tg.Visibility;
togText = tg.ToggleTextbox;
}
if (v != null &&
v.Hidden != null)
{
bool bHide = v.Hidden.EvaluateBoolean(this.r, row);
if (bHide)
tw.Write(" style=\"display:none;\"");
}
if (togText != null && togText.Name != null)
{
string name = togText.Name.Nm + "_" + togText.RunCount(this.r).ToString();
tw.Write(" id='{0}'", name);
}
tw.Write(">");
}
public void TableRowEnd(TableRow tr, Row row)
{
tw.WriteLine("</tr>");
}
public void TableCellStart(TableCell t, Row row)
{
string cellType = t.InTableHeader? "th": "td";
ReportItem r = t.ReportItems.Items[0];
string cssName = CssAdd(r.Style, r, row); // get the style name for this item
tw.Write("<{0} id='{1}'", cellType, cssName);
// calculate width of column
if (t.InTableHeader && t.OwnerTable.TableColumns != null)
{
// Calculate the width across all the spanned columns
int width = 0;
for (int ci=t.ColIndex; ci < t.ColIndex + t.ColSpan; ci++)
{
TableColumn tc = t.OwnerTable.TableColumns.Items[ci] as TableColumn;
if (tc != null && tc.Width != null)
width += tc.Width.ToPixels();
}
if (width > 0)
tw.Write(" width={0}", width);
}
if (t.ColSpan > 1)
tw.Write(" colspan={0}", t.ColSpan);
Textbox tb = r as Textbox;
if (tb != null && // have textbox
tb.IsToggle && // and its a toggle
tb.Name != null) // and need name as well
{
int groupNestCount = t.OwnerTable.GetGroupNestCount(this.r);
if (groupNestCount > 0) // anything to toggle?
{
string name = tb.Name.Nm + "_" + (tb.RunCount(this.r)+1).ToString();
bScriptToggle = true;
// need both hand and pointer because IE and Firefox use different names
tw.Write(" onClick=\"hideShow(this, {0}, '{1}')\" onMouseOver=\"style.cursor ='hand';style.cursor ='pointer'\">", groupNestCount, name);
tw.Write("<img class='toggle' src=\"plus.gif\" align=\"top\"/>");
}
else
tw.Write("<img src=\"empty.gif\" align=\"top\"/>");
}
else
tw.Write(">");
if (t.InTableHeader)
{
// put the second half of the sort tags for the column; if needed
// first half ---- <a href="#" onclick="sort_table(this,sort_cmp_string,1,0);return false;">
// next half follows text ---- <span class="sortarrow"> </span></a></th>
string sortcmp = SortType(t, tb); // obtain the sort type
if (sortcmp != null) // null if sort not needed
{
int headerRows, footerRows;
headerRows = t.OwnerTable.Header.TableRows.Items.Count; // since we're in header we know we have some rows
if (t.OwnerTable.Footer != null &&
t.OwnerTable.Footer.TableRows != null)
footerRows = t.OwnerTable.Footer.TableRows.Items.Count;
else
footerRows = 0;
tw.Write("<a href=\"#\" title='Sort' onclick=\"sort_table(this,{0},{1},{2});return false;\">",sortcmp, headerRows, footerRows);
}
}
return;
}
private string SortType(TableCell tc, Textbox tb)
{
// return of null means don't sort
if (tb == null || !IsTableSortable(tc.OwnerTable))
return null;
// default is true if table is sortable;
// but user may place override on Textbox custom tag
if (tb.Custom != null)
{
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in tb.Custom.CustomXmlNode.ChildNodes)
{
if (xNodeLoop.Name == "HTML")
{
if (xNodeLoop.LastChild.InnerText.ToLower() == "false")
{
return null;
}
break;
}
}
}
// Must find out the type of the detail column
Details d = tc.OwnerTable.Details;
if (d == null)
return null;
TableRow tr = d.TableRows.Items[0] as TableRow;
if (tr == null)
return null;
TableCell dtc = tr.TableCells.Items[tc.ColIndex] as TableCell;
if (dtc == null)
return null;
Textbox dtb = dtc.ReportItems.Items[0] as Textbox;
if (dtb == null)
return null;
string sortcmp;
switch (dtb.Value.Type)
{
case TypeCode.DateTime:
sortcmp = "sort_cmp_date";
break;
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Decimal:
case TypeCode.Single:
case TypeCode.Double:
sortcmp = "sort_cmp_number";
break;
case TypeCode.String:
sortcmp = "sort_cmp_string";
break;
case TypeCode.Empty: // Not a type we know how to sort
default:
sortcmp = null;
break;
}
return sortcmp;
}
public void TableCellEnd(TableCell t, Row row)
{
string cellType = t.InTableHeader? "th": "td";
Textbox tb = t.ReportItems.Items[0] as Textbox;
if (cellType == "th" && SortType(t, tb) != null)
{ // put the second half of the sort tags for the column
// first half ---- <a href="#" onclick="sort_table(this,sort_cmp_string,1,0);return false;">
// next half follows text ---- <span class="sortarrow"> </span></a></th>
tw.Write("<span class=\"sortarrow\"> </span></a>");
}
tw.Write("</{0}>", cellType);
return;
}
public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first
{
string bookmark = m.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
// output some of the table styles
string cssName = CssAdd(m.Style, m, r); // get the style name for this item
tw.WriteLine("<table id='{0}'>", cssName);
return true;
}
public void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart
{
}
public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan)
{
if (ri == null) // Empty cell?
{
if (_SkipMatrixCols == 0)
tw.Write("<td>");
return;
}
string cssName = CssAdd(ri.Style, ri, r, false, h, w); // get the style name for this item
tw.Write("<td id='{0}'", cssName);
if (colSpan != 1)
{
tw.Write(" colspan={0}", colSpan);
_SkipMatrixCols=-(colSpan-1); // start it as negative as indicator that we need this </td>
}
else
_SkipMatrixCols=0;
if (ri is Textbox)
{
Textbox tb = (Textbox) ri;
if (tb.IsToggle && tb.Name != null) // name is required for this
{
string name = tb.Name.Nm + "_" + (tb.RunCount(this.r)+1).ToString();
bScriptToggle = true; // we need to generate JavaScript in header
// TODO -- need to calculate the hide count correctly
tw.Write(" onClick=\"hideShow(this, {0}, '{1}')\" onMouseOver=\"style.cursor ='hand'\"", 0, name);
}
}
tw.Write(">");
}
public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r)
{
if (_SkipMatrixCols == 0)
tw.Write("</td>");
else if (_SkipMatrixCols < 0)
{
tw.Write("</td>");
_SkipMatrixCols = -_SkipMatrixCols;
}
else
_SkipMatrixCols--;
return;
}
public void MatrixRowStart(Matrix m, int row, Row r)
{
tw.Write("\t<tr");
tw.Write(">");
}
public void MatrixRowEnd(Matrix m, int row, Row r)
{
tw.WriteLine("</tr>");
}
public void MatrixEnd(Matrix m, Row r) // called last
{
tw.Write("</table>");
string bookmark = m.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("</div>");
return;
}
public void Chart(Chart c, Row r, ChartBase cb)
{
string relativeName;
Stream io = _sg.GetIOStream(out relativeName, "png");
try
{
cb.Save(this.r, io, ImageFormat.Png);
}
finally
{
io.Flush();
io.Close();
}
relativeName = FixupRelativeName(relativeName);
// Create syntax in a string buffer
StringWriter sw = new StringWriter();
string bookmark = c.BookmarkValue(this.r, r);
if (bookmark != null)
sw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
string cssName = CssAdd(c.Style, c, null); // get the style name for this item
sw.Write("<img src=\"{0}\" class='{1}'", relativeName, cssName);
string tooltip = c.ToolTipValue(this.r, r);
if (tooltip != null)
sw.Write(" alt=\"{0}\"", tooltip);
if (c.Height != null)
sw.Write(" height=\"{0}\"", c.Height.ToPixels().ToString());
if (c.Width != null)
sw.Write(" width=\"{0}\"", c.Width.ToPixels().ToString());
sw.Write(">");
if (bookmark != null)
sw.Write("</div>");
tw.Write(Action(c.Action, r, sw.ToString(), tooltip));
return;
}
public void Image(Image i, Row r, string mimeType, Stream ioin)
{
string relativeName;
string suffix;
switch (mimeType)
{
case "image/bmp":
suffix = "bmp";
break;
case "image/jpeg":
suffix = "jpeg";
break;
case "image/gif":
suffix = "gif";
break;
case "image/png":
case "image/x-png":
suffix = "png";
break;
default:
suffix = "unk";
break;
}
Stream io = _sg.GetIOStream(out relativeName, suffix);
try
{
if (ioin.CanSeek) // ioin.Length requires Seek support
{
byte[] ba = new byte[ioin.Length];
ioin.Read(ba, 0, ba.Length);
io.Write(ba, 0, ba.Length);
}
else
{
byte[] ba = new byte[1000]; // read a 1000 bytes at a time
while (true)
{
int length = ioin.Read(ba, 0, ba.Length);
if (length <= 0)
break;
io.Write(ba, 0, length);
}
}
}
finally
{
io.Flush();
io.Close();
}
relativeName = FixupRelativeName(relativeName);
// Create syntax in a string buffer
StringWriter sw = new StringWriter();
string bookmark = i.BookmarkValue(this.r, r);
if (bookmark != null)
sw.WriteLine("<div id=\"{0}\">", bookmark); // we're using for css style
string cssName = CssAdd(i.Style, i, null); // get the style name for this item
sw.Write("<img src=\"{0}\" class='{1}'", relativeName, cssName);
string tooltip = i.ToolTipValue(this.r, r);
if (tooltip != null)
sw.Write(" alt=\"{0}\"", tooltip);
int h = i.Height == null? -1: i.Height.ToPixels();
int w = i.Width == null ? -1 : i.Width.ToPixels();
switch (i.Sizing)
{
case ImageSizingEnum.AutoSize:
break; // this is right
case ImageSizingEnum.Clip:
break; // not sure how to clip it
case ImageSizingEnum.Fit:
if (h > 0)
sw.Write(" height=\"{0}\"", h.ToString());
if (w > 0)
sw.Write(" width=\"{0}\"", w.ToString());
break;
case ImageSizingEnum.FitProportional:
break; // would have to create an image to handle this
}
sw.Write("/>");
if (bookmark != null)
sw.Write("</div>");
tw.Write(Action(i.Action, r, sw.ToString(), tooltip));
return;
}
public void Line(Line l, Row r)
{
bool bVertical;
string t;
if (l.Height == null || l.Height.ToPixels() > 0) // only handle horizontal rule
{
if (l.Width == null || l.Width.ToPixels() > 0) // and vertical rules
return;
bVertical = true;
t = "<TABLE style=\"border-collapse:collapse;BORDER-STYLE: none;WIDTH: {0}; POSITION: absolute; LEFT: {1}; TOP: {2}; HEIGHT: {3}; BACKGROUND-COLOR:{4};\"><TBODY><TR style=\"WIDTH:{0}\"><TD style=\"WIDTH:{0}\"></TD></TR></TBODY></TABLE>";
}
else
{
bVertical = false;
t = "<TABLE style=\"border-collapse:collapse;BORDER-STYLE: none;WIDTH: {0}; POSITION: absolute; LEFT: {1}; TOP: {2}; HEIGHT: {3}; BACKGROUND-COLOR:{4};\"><TBODY><TR style=\"HEIGHT:{3}\"><TD style=\"HEIGHT:{3}\"></TD></TR></TBODY></TABLE>";
}
string width, left, top, height, color;
Style s = l.Style;
left = l.Left == null? "0px": l.Left.CSS;
top = l.Top == null? "0px": l.Top.CSS;
if (bVertical)
{
height = l.Height == null? "0px": l.Height.CSS;
// width comes from the BorderWidth
if (s != null && s.BorderWidth != null && s.BorderWidth.Default != null)
width = s.BorderWidth.Default.EvaluateString(this.r, r);
else
width = "1px";
}
else
{
width = l.Width == null? "0px": l.Width.CSS;
// height comes from the BorderWidth
if (s != null && s.BorderWidth != null && s.BorderWidth.Default != null)
height = s.BorderWidth.Default.EvaluateString(this.r, r);
else
height = "1px";
}
if (s != null && s.BorderColor != null && s.BorderColor.Default != null)
color = s.BorderColor.Default.EvaluateString(this.r, r);
else
color = "black";
tw.WriteLine(t, width, left, top, height, color);
return;
}
public bool RectangleStart(Rdl.Rectangle rect, Row r)
{
string cssName = CssAdd(rect.Style, rect, r); // get the style name for this item
string bookmark = rect.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("<div id=\"{0}\">", bookmark); // can't use the table id since we're using for css style
// Calculate the width of all the columns
int width = rect.Width == null ? -1 : rect.Width.ToPixels();
if (width < 0)
tw.WriteLine("<table id='{0}'><tr>", cssName);
else
tw.WriteLine("<table id='{0}' width={1}><tr>", cssName, width);
return true;
}
public void RectangleEnd(Rdl.Rectangle rect, Row r)
{
tw.WriteLine("</tr></table>");
string bookmark = rect.BookmarkValue(this.r, r);
if (bookmark != null)
tw.WriteLine("</div>");
return;
}
// Subreport:
public void Subreport(Subreport s, Row r)
{
string cssName = CssAdd(s.Style, s, r); // get the style name for this item
tw.WriteLine("<div class='{0}'>", cssName);
s.ReportDefn.Run(this);
tw.WriteLine("</div>");
}
public void GroupingStart(Grouping g) // called at start of grouping
{
}
public void GroupingInstanceStart(Grouping g) // called at start for each grouping instance
{
}
public void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance
{
}
public void GroupingEnd(Grouping g) // called at end of grouping
{
}
public void RunPages(Pages pgs) // we don't have paging turned on for html
{
}
}
class CssCacheEntry
{
string _Css; // css
string _Name; // name of entry
public CssCacheEntry(string css, string name)
{
_Css = css;
_Name = name;
}
public string Css
{
get { return _Css; }
set { _Css = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
}
| |
using System;
using IO = System.IO;
// 2/7/03
namespace NBM.Plugin
{
/// <summary>
/// Summary description for CircularBuffer.
/// </summary>
public class CircularStream : IO.Stream
{
private const int defaultSize = 4092;
private byte[] internalData;
private int size;
private int readPosition = 0, writePosition = 0;
public int DataAvailable
{
get
{
if (this.readPosition == this.writePosition)
return 0;
else if (this.readPosition > this.writePosition)
return this.size - this.readPosition + this.writePosition;
else
return this.writePosition - this.readPosition;
}
}
public override bool CanRead
{
get { return true; }
}
public override bool CanWrite
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override long Length
{
get { return size - 1; }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public CircularStream()
: this(defaultSize)
{
}
public CircularStream(int size)
{
this.size = size + 1;
this.internalData = new byte[ this.size ];
}
public override void Flush()
{
}
public override long Seek(long offset, IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long length)
{
int bytesTillEnd = this.size - this.writePosition;
// copy data from the write pointer to the end into a new array
byte[] rawData = new byte[ this.size ];
Array.Copy(this.internalData, this.writePosition, rawData, 0, bytesTillEnd);
// then append the rest of the data to the new array
Array.Copy(this.internalData, 0, rawData, bytesTillEnd, this.writePosition);
// now we have the data all in order, recreate the internal array and then
// copy the new array back into it
int copyLength = Math.Min((int)length, rawData.Length);
this.internalData = new byte[ length+1 ];
Array.Copy(rawData, 0, this.internalData, 0, copyLength);
// set read pointer to the position relative to where it was
if (this.readPosition > this.writePosition)
this.readPosition -= this.writePosition + 1;
else
this.readPosition += bytesTillEnd;
// if the new read position points at invalid data (if the stream was shrunk)
// simply reset it
if (this.readPosition >= length)
this.readPosition = 0;
// set write pointer to the end of the freshly written data
this.writePosition = copyLength;
this.size = (int)length + 1;
}
public override int Read(byte[] data, int offset, int length)
{
lock (this)
{
if (this.writePosition == this.readPosition)
return 0; // empty buffer
int amountRead = 0;
if (this.writePosition < this.readPosition)
{
// write pointer is behind the read pointer, then read up until the end of
// the buffer and read from the start till the write p
int bytesTillEnd = this.size - this.readPosition;
if (bytesTillEnd < length)
{
int bytesFromStart = Math.Min(this.writePosition, length - bytesTillEnd);
Array.Copy(this.internalData, this.readPosition, data, offset, bytesTillEnd);
Array.Copy(this.internalData, 0, data, offset + bytesTillEnd, bytesFromStart);
amountRead = bytesTillEnd + bytesFromStart;
this.readPosition = bytesFromStart;
}
else
{
Array.Copy(this.internalData, this.readPosition, data, offset, length);
amountRead = length;
this.readPosition += amountRead;
}
}
else
{
// write pointer is ahead of the read pointer, just read up until then
int amountToCopy = Math.Min(this.writePosition - this.readPosition, length);
Array.Copy(this.internalData, this.readPosition, data, offset, amountToCopy);
amountRead = amountToCopy;
this.readPosition += amountToCopy;
}
return amountRead;
}
}
public override void Write(byte[] data, int offset, int length)
{
lock (this)
{
// test if the buffer needs to be resized to accomodate the written data
int spaceAvailable = 0;
if (this.readPosition == this.writePosition)
spaceAvailable = this.size - 1;
else if (this.readPosition == this.writePosition + 1)
spaceAvailable = 0;
else if (this.readPosition < this.writePosition)
spaceAvailable = this.size - this.writePosition + this.readPosition;
else
spaceAvailable = this.readPosition - this.writePosition;
if (spaceAvailable < length)
this.SetLength(this.size - spaceAvailable + length - 1);
if (this.readPosition <= this.writePosition)
{
// read pointer is behind the write pointer, write till the end
// of the buffer then go back to the start
int bytesTillEnd = this.size - this.writePosition;
if (bytesTillEnd - 1 < length)
{
// length to copy is greater than the size of the data until the end of the buffer,
// so copy the remaining data until the end
Array.Copy(data, offset, this.internalData, this.writePosition, bytesTillEnd);
int bytesFromStart = Math.Min(this.readPosition-1, length - bytesTillEnd);
if (bytesFromStart > 0)
{
Array.Copy(data, offset + bytesTillEnd, this.internalData, 0, bytesFromStart);
this.writePosition = bytesFromStart;
}
else
this.writePosition = this.size;
}
else
{
// length is not greater than the size of the data until the end, so
// just copy it over
Array.Copy(data, offset, this.internalData, this.writePosition, length);
this.writePosition += length;
}
}
else
{
// write pointer is behind the read pointer, simply write up until then
int amountToCopy = Math.Min(this.readPosition - this.writePosition - 1, length);
Array.Copy(data, offset, this.internalData, this.writePosition, amountToCopy);
this.writePosition += amountToCopy;
}
}
}
}
}
| |
#pragma warning disable 1634, 1691
namespace System.Workflow.ComponentModel.Design
{
using System;
using System.IO;
using System.Drawing;
using System.CodeDom;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;
using System.Globalization;
using System.Drawing.Design;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Windows.Forms.Design;
using System.ComponentModel.Design;
using System.Collections.Specialized;
using System.ComponentModel.Design.Serialization;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Workflow.ComponentModel.Design;
using System.Runtime.Serialization.Formatters.Binary;
//
#region StructuredCompositeActivityDesigner Class
/// <summary>
/// Base class for CompositActivityDesigner which have a structured layouts where contained ContainedDesigners
/// are connected to each other using connectors. Class is used when the user needs to provide different types
/// of layouts for CompositeActivityDesigner
/// </summary>
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public abstract class StructuredCompositeActivityDesigner : CompositeActivityDesigner
{
#region Fields
private int currentDropTarget = -1;
private List<DesignerView> views = null;
private DesignerView activeView;
private ItemPalette itemPalette = null;
#endregion
#region Properties
#region Public Properties
public override ReadOnlyCollection<ActivityDesigner> ContainedDesigners
{
get
{
List<ActivityDesigner> containedDesigners = new List<ActivityDesigner>();
ActivityDesigner activeDesigner = ActiveDesigner;
if (activeDesigner != null)
{
if (activeDesigner == this)
{
//We need to remove the secondary activities
containedDesigners.AddRange(base.ContainedDesigners);
List<ActivityDesigner> designersToRemove = new List<ActivityDesigner>();
IList<ActivityDesigner> mappedDesigners = DesignersFromSupportedViews;
foreach (ActivityDesigner containedDesigner in containedDesigners)
{
bool isAlternateFlowActivityAttribute = Helpers.IsAlternateFlowActivity(containedDesigner.Activity);
if (mappedDesigners.Contains(containedDesigner) || isAlternateFlowActivityAttribute)
designersToRemove.Add(containedDesigner);
}
foreach (ActivityDesigner activityDesigner in designersToRemove)
containedDesigners.Remove(activityDesigner);
}
else
{
containedDesigners.Add(activeDesigner);
}
}
return containedDesigners.AsReadOnly();
}
}
public override object FirstSelectableObject
{
get
{
ActivityDesigner activeDesigner = ActiveDesigner;
if (activeDesigner != null && activeDesigner != this)
return activeDesigner.Activity;
else
return base.FirstSelectableObject;
}
}
public override object LastSelectableObject
{
get
{
ActivityDesigner activeDesigner = ActiveDesigner;
if (activeDesigner != null && activeDesigner != this && activeDesigner is CompositeActivityDesigner)
return ((CompositeActivityDesigner)activeDesigner).LastSelectableObject;
else
return base.LastSelectableObject;
}
}
/// <summary>
/// Gets the ActiveView supported by the designer
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DesignerView ActiveView
{
get
{
if (this.activeView == null)
this.activeView = ValidatedViews[0];
return this.activeView;
}
set
{
if (this.activeView == value || value == null)
return;
DesignerView previousView = this.activeView;
this.activeView = value;
value.OnActivate();
ActivityDesigner designer = value.AssociatedDesigner;
if (designer == null)
{
value.OnDeactivate();
this.activeView = previousView;
return;
}
if (previousView != null)
previousView.OnDeactivate();
OnViewChanged(this.activeView);
//When we change the view we want to make sure that if we hide any of the child
//activities with errors we want to reveal these activities
DesignerHelpers.RefreshDesignerActions(Activity.Site);
//Keep the dynamic action and designer verbs in [....]
RefreshDesignerVerbs();
}
}
public override Size MinimumSize
{
get
{
Size minimumSize = base.MinimumSize;
ActivityDesigner activeDesigner = ActiveDesigner;
if (activeDesigner != null && activeDesigner != this && Expanded)
{
minimumSize.Width = Math.Max(minimumSize.Width, 160);
minimumSize.Height = Math.Max(minimumSize.Height, 160);
}
return minimumSize;
}
}
/// <summary>
/// Gets the array of views supported by the current designer
/// </summary>
public virtual ReadOnlyCollection<DesignerView> Views
{
get
{
if (this.views == null)
{
this.views = new List<DesignerView>();
this.views.AddRange(SecondaryViewProvider.GetViews(this));
}
return this.views.AsReadOnly();
}
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the index of the cuurent drop target in the array of drop targets returned by method GetDropTargets
/// This property is only used when the drag drop operation is in progress
/// </summary>
protected virtual int CurrentDropTarget
{
get
{
return this.currentDropTarget;
}
set
{
this.currentDropTarget = value;
Invalidate();
}
}
protected override bool ShowSmartTag
{
get
{
return (!String.IsNullOrEmpty(Text) && !TextRectangle.Size.IsEmpty && Views.Count > 1);
}
}
protected override ReadOnlyCollection<ActivityDesignerVerb> SmartTagVerbs
{
get
{
List<ActivityDesignerVerb> smartTagVerbs = new List<ActivityDesignerVerb>(base.SmartTagVerbs);
//Return smarttag actions only if there is more than one view
if (Views.Count > 1)
{
for (int i = 0; i < Views.Count; i++)
{
DesignerView view = Views[i];
ActivityDesignerVerb smartVerb = new ActivityDesignerVerb(this, DesignerVerbGroup.Actions, view.Text, new EventHandler(OnSmartTagVerb), new EventHandler(OnSmartTagVerbStatus));
smartVerb.Properties[DesignerUserDataKeys.DesignerView] = view;
smartVerb.Properties[DesignerUserDataKeys.Image] = view.Image;
smartTagVerbs.Add(smartVerb);
}
}
return smartTagVerbs.AsReadOnly();
}
}
#endregion
#region Private Properties
internal ActivityDesigner ActiveDesigner
{
get
{
if (ActiveView != null)
return ActiveView.AssociatedDesigner;
else
return null;
}
}
internal override bool SmartTagVisible
{
get
{
if (this.itemPalette != null && this.itemPalette.IsVisible)
return true;
return base.SmartTagVisible;
}
set
{
base.SmartTagVisible = value;
}
}
private ReadOnlyCollection<DesignerView> ValidatedViews
{
get
{
ReadOnlyCollection<DesignerView> views = Views;
if (views.Count == 0)
#pragma warning suppress 56503
throw new InvalidOperationException(DR.GetString(DR.Error_MultiviewSequentialActivityDesigner));
return views;
}
}
private IList<ActivityDesigner> DesignersFromSupportedViews
{
get
{
List<ActivityDesigner> mappedDesigners = new List<ActivityDesigner>();
foreach (DesignerView view in ValidatedViews)
{
ActivityDesigner mappedDesigner = view.AssociatedDesigner;
if (mappedDesigner != null)
mappedDesigners.Add(mappedDesigner);
}
return mappedDesigners.AsReadOnly();
}
}
#endregion
#endregion
#region Methods
#region Public Methods
public override bool CanInsertActivities(HitTestInfo insertLocation, ReadOnlyCollection<Activity> activitiesToInsert)
{
if (insertLocation == null)
throw new ArgumentNullException("insertLocation");
if (activitiesToInsert == null)
throw new ArgumentNullException("activitiesToInsert");
ActivityDesigner hostedDesigner = (ActiveView != null) ? ActiveView.AssociatedDesigner : null;
if (hostedDesigner != this)
return false;
IList<Type> secondaryViewTypes = SecondaryViewProvider.GetActivityTypes(this);
foreach (Activity activity in activitiesToInsert)
{
if (activity == null)
throw new ArgumentException("activitiesToInsert", SR.GetString(SR.Error_CollectionHasNullEntry));
if (secondaryViewTypes.Contains(activity.GetType()))
return false;
}
return base.CanInsertActivities(GetUpdatedLocation(insertLocation), activitiesToInsert);
}
public override void InsertActivities(HitTestInfo insertLocation, ReadOnlyCollection<Activity> activitiesToInsert)
{
if (insertLocation == null)
throw new ArgumentNullException("insertLocation");
if (activitiesToInsert == null)
throw new ArgumentNullException("activitiesToInsert");
base.InsertActivities(GetUpdatedLocation(insertLocation), activitiesToInsert);
}
public override void MoveActivities(HitTestInfo moveLocation, ReadOnlyCollection<Activity> activitiesToMove)
{
if (moveLocation == null)
throw new ArgumentNullException("moveLocation");
if (activitiesToMove == null)
throw new ArgumentNullException("activitiesToMove");
base.MoveActivities(GetUpdatedLocation(moveLocation), activitiesToMove);
}
public override bool CanRemoveActivities(ReadOnlyCollection<Activity> activitiesToRemove)
{
if (activitiesToRemove == null)
throw new ArgumentNullException("activitiesToRemove");
return base.CanRemoveActivities(activitiesToRemove);
}
public override void EnsureVisibleContainedDesigner(ActivityDesigner containedDesigner)
{
if (containedDesigner == null)
throw new ArgumentNullException("containedDesigner");
//we could be collapsed, make sure the view itself is visible
this.Expanded = true;
ActivityDesigner activeDesigner = ActiveDesigner;
if (containedDesigner != activeDesigner && containedDesigner != this)
{
DesignerView viewToActivate = null;
ReadOnlyCollection<DesignerView> views = ValidatedViews;
//Go thru the views and check if the child designer is one of the views
foreach (DesignerView view in views)
{
if (containedDesigner == view.AssociatedDesigner)
{
viewToActivate = view;
break;
}
}
//This means that the child designer is in our main flow
if (viewToActivate == null)
viewToActivate = views[0];
ActiveView = viewToActivate;
//Invoking a verb might change the shown view so we map again
CompositeActivityDesigner activeCompositeDesigner = ActiveDesigner as CompositeActivityDesigner;
if (activeCompositeDesigner != null)
{
if (activeCompositeDesigner != this)
activeCompositeDesigner.EnsureVisibleContainedDesigner(containedDesigner);
else
base.EnsureVisibleContainedDesigner(containedDesigner);
}
}
}
public override object GetNextSelectableObject(object current, DesignerNavigationDirection direction)
{
object nextObject = null;
ActivityDesigner activeDesigner = ActiveDesigner;
if (activeDesigner != null)
{
if (activeDesigner != this)
{
if (current != activeDesigner.Activity && activeDesigner is CompositeActivityDesigner)
nextObject = ((CompositeActivityDesigner)activeDesigner).GetNextSelectableObject(current, direction);
}
else
{
nextObject = base.GetNextSelectableObject(current, direction);
}
}
return nextObject;
}
#endregion
#region Protected Methods
protected override void Initialize(Activity activity)
{
base.Initialize(activity);
ActiveView = ValidatedViews[0];
}
/// <summary>
/// Returns the collection of points which represents the inner connections of the designer. The designer can have connectors
/// within it, the points returned are the connection points used for connectable designer.
/// </summary>
/// <param name="edges">Designer Edge along which the connection point lies</param>
/// <returns>List of connection Points</returns>
protected virtual ReadOnlyCollection<Point> GetInnerConnections(DesignerEdges edges)
{
List<Point> connectionPoints = new List<Point>(GetConnections(edges));
if (connectionPoints.Count > 0 && (edges & DesignerEdges.Top) > 0)
connectionPoints[0] = new Point(connectionPoints[0].X, connectionPoints[0].Y + TitleHeight);
return connectionPoints.AsReadOnly();
}
/// <summary>
/// Returns array of rectangles representing the valid drop locations with the designer
/// </summary>
/// <param name="dropPoint"></param>
/// <returns></returns>
protected virtual Rectangle[] GetDropTargets(Point dropPoint)
{
return new Rectangle[] { Bounds };
}
protected override void OnContainedActivitiesChanging(ActivityCollectionChangeEventArgs listChangeArgs)
{
base.OnContainedActivitiesChanging(listChangeArgs);
if (listChangeArgs.Action == ActivityCollectionChangeAction.Remove && listChangeArgs.RemovedItems[0] != null)
{
ActivityDesigner activeDesigner = ActiveDesigner;
if (activeDesigner != null && listChangeArgs.RemovedItems[0] == activeDesigner.Activity)
ActiveView = ValidatedViews[0];
SecondaryViewProvider.OnViewRemoved(this, listChangeArgs.RemovedItems[0].GetType());
}
}
protected void DrawConnectors(Graphics graphics, Pen pen, Point[] points, LineAnchor startCap, LineAnchor endCap)
{
Size arrowCapSize = Size.Empty;
Size maxCapSize = Size.Empty;
CompositeDesignerTheme compositeDesignerTheme = DesignerTheme as CompositeDesignerTheme;
if (compositeDesignerTheme != null)
{
arrowCapSize = new Size(compositeDesignerTheme.ConnectorSize.Width / 3, compositeDesignerTheme.ConnectorSize.Height / 3);
maxCapSize = compositeDesignerTheme.ConnectorSize;
}
ActivityDesignerPaint.DrawConnectors(graphics, pen, points, arrowCapSize, maxCapSize, startCap, endCap);
}
protected override void OnDragEnter(ActivityDragEventArgs e)
{
base.OnDragEnter(e);
CurrentDropTarget = CanDrop(e);
e.Effect = CheckDragEffect(e);
e.DragImageSnapPoint = SnapInToDropTarget(e);
}
protected override void OnDragOver(ActivityDragEventArgs e)
{
base.OnDragOver(e);
CurrentDropTarget = CanDrop(e);
e.Effect = CheckDragEffect(e);
e.DragImageSnapPoint = SnapInToDropTarget(e);
}
protected override void OnDragLeave()
{
base.OnDragLeave();
//Clear earlier drop target information
CurrentDropTarget = -1;
}
protected override void OnDragDrop(ActivityDragEventArgs e)
{
base.OnDragDrop(e);
bool ctrlKeyPressed = ((e.KeyState & 8) == 8);
if (ctrlKeyPressed && (e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
e.Effect = DragDropEffects.Copy;
else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
e.Effect = DragDropEffects.Move;
//If the component is sited then that means that we are moving it
try
{
CompositeActivityDesigner.InsertActivities(this, new ConnectorHitTestInfo(this, HitTestLocations.Designer, CurrentDropTarget), e.Activities, SR.GetString(SR.DragDropActivities));
}
finally
{
CurrentDropTarget = -1;
}
}
protected override void OnLayoutPosition(ActivityDesignerLayoutEventArgs e)
{
if (e == null)
throw new ArgumentNullException("e");
base.OnLayoutPosition(e);
if (Expanded)
{
ActivityDesigner activeDesigner = ActiveDesigner;
if (activeDesigner != null && activeDesigner != this)
{
Point location = Location;
location.X += (Size.Width - activeDesigner.Size.Width) / 2;
location.Y += e.AmbientTheme.SelectionSize.Height;
activeDesigner.Location = location;
}
int titleHeight = TitleHeight;
foreach (ActivityDesigner activityDesigner in ContainedDesigners)
activityDesigner.Location = new Point(activityDesigner.Location.X, activityDesigner.Location.Y + titleHeight);
}
}
protected override Size OnLayoutSize(ActivityDesignerLayoutEventArgs e)
{
Size containerSize = base.OnLayoutSize(e);
if (Expanded)
{
ActivityDesigner activeDesigner = ActiveDesigner;
if (activeDesigner != null && activeDesigner != this)
{
containerSize.Width = Math.Max(containerSize.Width, activeDesigner.Size.Width);
containerSize.Height += activeDesigner.Size.Height;
containerSize.Width += 2 * e.AmbientTheme.SelectionSize.Width;
containerSize.Width += 3 * e.AmbientTheme.Margin.Width;
containerSize.Height += e.AmbientTheme.Margin.Height;
containerSize.Height += 2 * e.AmbientTheme.SelectionSize.Height;
}
}
return containerSize;
}
protected override void SaveViewState(BinaryWriter writer)
{
if (writer == null)
throw new ArgumentNullException("writer");
List<DesignerView> views = new List<DesignerView>(ValidatedViews);
writer.Write("ActiveView");
writer.Write(views.IndexOf(this.activeView));
base.SaveViewState(writer);
}
protected override void LoadViewState(BinaryReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
string str = reader.ReadString();
if (str != null && str.Equals("ActiveView", StringComparison.Ordinal))
{
int activeDesignerIndex = reader.ReadInt32();
ReadOnlyCollection<DesignerView> views = ValidatedViews;
if (activeDesignerIndex != -1 && activeDesignerIndex < views.Count)
ActiveView = views[activeDesignerIndex];
}
base.LoadViewState(reader);
}
/// <summary>
/// Called when the current view of the designer changes
/// </summary>
/// <param name="view">View which is being set.</param>
protected virtual void OnViewChanged(DesignerView view)
{
PerformLayout();
}
protected override void OnShowSmartTagVerbs(Point smartTagPoint)
{
if (this.itemPalette == null)
{
this.itemPalette = new ItemPalette();
this.itemPalette.Closed += new EventHandler(OnPaletteClosed);
this.itemPalette.SelectionChanged += new SelectionChangeEventHandler<SelectionChangeEventArgs>(OnSmartAction);
}
//we need to update the font every time the menu is shown
this.itemPalette.SetFont(WorkflowTheme.CurrentTheme.AmbientTheme.Font);
this.itemPalette.Items.Clear();
foreach (ActivityDesignerVerb smartVerb in SmartTagVerbs)
{
Image image = smartVerb.Properties[DesignerUserDataKeys.Image] as Image;
ItemInfo smartVerbItem = new ItemInfo(smartVerb.Id, image, smartVerb.Text);
smartVerbItem.UserData[DesignerUserDataKeys.DesignerVerb] = smartVerb;
this.itemPalette.Items.Add(smartVerbItem);
}
Point location = PointToScreen(smartTagPoint);
this.itemPalette.Show(location);
}
protected override void OnActivityChanged(ActivityChangedEventArgs e)
{
ReadOnlyCollection<DesignerView> newViews = SecondaryViewProvider.GetViews(this);
ReadOnlyCollection<DesignerView> oldViews = Views;
if (newViews.Count != oldViews.Count)
{
this.views = null;
//
PerformLayout();
}
base.OnActivityChanged(e);
}
#endregion
#region Private Methods
internal override void OnPaintContainedDesigners(ActivityDesignerPaintEventArgs e)
{
//Draw all the activity designers contained by the activity designer
//We know that all the children which are in drawing range will be always
//consecutive both for parallel and for sequential containers hence
//once we go in the invisible range we bail out of drawing logic for rest of
//the children
bool bDrawingVisibleChildren = false;
foreach (ActivityDesigner activityDesigner in ContainedDesigners)
{
Rectangle designerBounds = activityDesigner.Bounds;
if (e.ViewPort.IntersectsWith(designerBounds))
{
bDrawingVisibleChildren = true;
using (PaintEventArgs paintEventArgs = new PaintEventArgs(e.Graphics, e.ViewPort))
{
((IWorkflowDesignerMessageSink)activityDesigner).OnPaint(paintEventArgs, e.ViewPort);
}
}
else
{
if (bDrawingVisibleChildren)
break;
}
}
}
private Point SnapInToDropTarget(ActivityDragEventArgs e)
{
if (CurrentDropTarget >= 0)
{
Rectangle[] dropTargets = GetDropTargets(new Point(e.X, e.Y));
if (CurrentDropTarget < dropTargets.Length)
{
Rectangle dropConnector = dropTargets[CurrentDropTarget];
return new Point(dropConnector.Left + dropConnector.Width / 2, dropConnector.Top + dropConnector.Height / 2);
}
}
return Point.Empty;
}
private int CanDrop(ActivityDragEventArgs e)
{
if (e.Activities.Count == 0)
return -1;
Point dropPoint = new Point(e.X, e.Y);
int dropIndex = -1;
Rectangle[] dropTargets = GetDropTargets(dropPoint);
for (int i = 0; i < dropTargets.Length; i++)
{
if (dropTargets[i].Contains(dropPoint))
{
dropIndex = i;
break;
}
}
if (dropIndex >= 0 && !CanInsertActivities(new ConnectorHitTestInfo(this, HitTestLocations.Designer, dropIndex), e.Activities))
dropIndex = -1;
bool ctrlKeyPressed = ((e.KeyState & 8) == 8);
if (dropIndex >= 0 && !ctrlKeyPressed && (e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
{
ConnectorHitTestInfo moveLocation = new ConnectorHitTestInfo(this, HitTestLocations.Designer, dropIndex);
foreach (Activity activity in e.Activities)
{
if (activity.Site != null)
{
ActivityDesigner activityDesigner = ActivityDesigner.GetDesigner(activity);
if (activityDesigner == null || activityDesigner.ParentDesigner == null || !activityDesigner.ParentDesigner.CanMoveActivities(moveLocation, new List<Activity>(new Activity[] { activity }).AsReadOnly()))
{
dropIndex = -1;
break;
}
}
}
}
return dropIndex;
}
private DragDropEffects CheckDragEffect(ActivityDragEventArgs e)
{
if (e.Activities.Count == 0)
{
return DragDropEffects.None;
}
else if (CurrentDropTarget >= 0)
{
bool ctrlKeyPressed = ((e.KeyState & 8) == 8);
if (ctrlKeyPressed && (e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
return DragDropEffects.Copy;
else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
return DragDropEffects.Move;
}
return e.Effect;
}
private void OnSmartTagVerbStatus(object sender, EventArgs e)
{
ActivityDesignerVerb verb = sender as ActivityDesignerVerb;
DesignerView view = verb.Properties[DesignerUserDataKeys.DesignerView] as DesignerView;
if (view != null)
verb.Checked = (view == ActiveView);
}
private void OnSmartTagVerb(object sender, EventArgs e)
{
ActivityDesignerVerb verb = sender as ActivityDesignerVerb;
DesignerView view = verb.Properties[DesignerUserDataKeys.DesignerView] as DesignerView;
if (view != null)
{
ActiveView = view;
if (Expanded && view.AssociatedDesigner != null)
{
ISelectionService selectionService = GetService(typeof(ISelectionService)) as ISelectionService;
if (selectionService != null)
selectionService.SetSelectedComponents(new object[] { view.AssociatedDesigner.Activity }, SelectionTypes.Replace);
}
}
}
private void OnSmartAction(object sender, SelectionChangeEventArgs e)
{
ItemInfo itemInfo = e.CurrentItem as ItemInfo;
if (itemInfo != null)
{
ActivityDesignerVerb smartVerb = itemInfo.UserData[DesignerUserDataKeys.DesignerVerb] as ActivityDesignerVerb;
if (smartVerb != null)
smartVerb.Invoke();
}
}
private void OnPaletteClosed(object sender, EventArgs e)
{
Invalidate(DesignerSmartTag.GetBounds(this, true));
}
private HitTestInfo GetUpdatedLocation(HitTestInfo location)
{
int lockedActivityOffset = 0;
foreach (DesignerView secondaryView in Views)
{
if (secondaryView.AssociatedDesigner != null &&
this != secondaryView.AssociatedDesigner &&
Helpers.IsActivityLocked(secondaryView.AssociatedDesigner.Activity))
{
lockedActivityOffset++;
}
}
return new ConnectorHitTestInfo(this, location.HitLocation, lockedActivityOffset + location.MapToIndex());
}
#endregion
#endregion
}
#endregion
}
| |
using LambdaExpression = System.Linq.Expressions.LambdaExpression;
using ExpressionRequest = MicroMapper.QueryableExtensions.ExpressionRequest;
namespace MicroMapper
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Impl;
using Internal;
using Mappers;
using QueryableExtensions;
using QueryableExtensions.Impl;
using ObjectDictionary = System.Collections.Generic.IDictionary<string, object>;
using ExpressionDictionary = Internal.IDictionary<ExpressionRequest, LambdaExpression>;
public class MappingEngine : IMappingEngine, IMappingEngineRunner
{
/// <summary>
/// Gets the runner.
/// </summary>
public IMappingEngineRunner Runner => this;
private static readonly IDictionaryFactory DictionaryFactory = PlatformAdapter.Resolve<IDictionaryFactory>();
private static readonly IProxyGeneratorFactory ProxyGeneratorFactory = PlatformAdapter.Resolve<IProxyGeneratorFactory>();
// Refactored from Extensions.
private static readonly IExpressionResultConverter[] ExpressionResultConverters =
{
new MemberGetterExpressionResultConverter(),
new MemberResolverExpressionResultConverter(),
new NullSubstitutionExpressionResultConverter()
};
private static readonly IExpressionBinder[] Binders =
{
new NullableExpressionBinder(),
new AssignableExpressionBinder(),
new EnumerableExpressionBinder(),
new MappedTypeExpressionBinder(),
new CustomProjectionExpressionBinder(),
new StringExpressionBinder()
};
private bool _disposed;
private Internal.IDictionary<TypePair, IObjectMapper> ObjectMapperCache { get; }
/// <summary>
/// Gets the cache.
/// </summary>
public ExpressionDictionary ExpressionCache { get; }
= DictionaryFactory.CreateDictionary<ExpressionRequest, LambdaExpression>();
private Func<Type, object> ServiceCtor { get; }
private readonly IMapperContext _mapperContext;
public IConfigurationProvider ConfigurationProvider => _mapperContext.ConfigurationProvider;
public MappingEngine(IMapperContext mapperContext)
: this(
mapperContext,
DictionaryFactory.CreateDictionary<TypePair, IObjectMapper>(),
mapperContext.ConfigurationProvider.ServiceCtor)
{
}
public MappingEngine(IMapperContext mapperContext,
Internal.IDictionary<TypePair, IObjectMapper> objectMapperCache,
Func<Type, object> serviceCtor)
{
/* Never, ever carry a previously configured engine forward:
that's the whole point of facilitating micro-mapping. */
_mapperContext = mapperContext;
ObjectMapperCache = objectMapperCache;
ServiceCtor = serviceCtor;
_mapperContext.ConfigurationProvider.TypeMapCreated += ClearTypeMap;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (ConfigurationProvider != null)
ConfigurationProvider.TypeMapCreated -= ClearTypeMap;
}
_disposed = true;
}
}
public TDestination Map<TDestination>(object source)
{
return Map<TDestination>(source, DefaultMappingOptions);
}
public TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
{
var mappedObject = default(TDestination);
if (source != null)
{
var sourceType = source.GetType();
var destinationType = typeof (TDestination);
mappedObject = (TDestination) Map(source, sourceType, destinationType, opts);
}
return mappedObject;
}
public TDestination Map<TSource, TDestination>(TSource source)
{
var modelType = typeof (TSource);
var destinationType = typeof (TDestination);
return (TDestination) Map(source, modelType, destinationType, DefaultMappingOptions);
}
public TDestination Map<TSource, TDestination>(TSource source,
Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
var modelType = typeof (TSource);
var destinationType = typeof (TDestination);
var options = new MappingOperationOptions<TSource, TDestination>();
opts(options);
return (TDestination) MapCore(source, modelType, destinationType, options);
}
public TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
{
return Map(source, destination, DefaultMappingOptions);
}
public TDestination Map<TSource, TDestination>(TSource source, TDestination destination,
Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
var modelType = typeof (TSource);
var destinationType = typeof (TDestination);
var options = new MappingOperationOptions<TSource, TDestination>();
opts(options);
return (TDestination) MapCore(source, destination, modelType, destinationType, options);
}
public object Map(object source, Type sourceType, Type destinationType)
{
return Map(source, sourceType, destinationType, DefaultMappingOptions);
}
public object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
{
var options = new MappingOperationOptions();
opts(options);
return MapCore(source, sourceType, destinationType, options);
}
private object MapCore(object source, Type sourceType, Type destinationType, MappingOperationOptions options)
{
var typeMap = ConfigurationProvider.ResolveTypeMap(source, null, sourceType, destinationType);
var context = new ResolutionContext(typeMap, source, sourceType, destinationType, options, _mapperContext);
return ((IMappingEngineRunner) this).Map(context);
}
public object Map(object source, object destination, Type sourceType, Type destinationType)
{
return Map(source, destination, sourceType, destinationType, DefaultMappingOptions);
}
public object Map(object source, object destination, Type sourceType, Type destinationType,
Action<IMappingOperationOptions> opts)
{
var options = new MappingOperationOptions();
opts(options);
return MapCore(source, destination, sourceType, destinationType, options);
}
private object MapCore(object source, object destination, Type sourceType, Type destinationType,
MappingOperationOptions options)
{
var typeMap = ConfigurationProvider.ResolveTypeMap(source, destination, sourceType, destinationType);
var context = new ResolutionContext(typeMap, source, destination, sourceType, destinationType, options, _mapperContext);
return ((IMappingEngineRunner) this).Map(context);
}
public TDestination DynamicMap<TSource, TDestination>(TSource source)
{
var modelType = typeof (TSource);
var destinationType = typeof (TDestination);
return (TDestination) DynamicMap(source, modelType, destinationType);
}
public void DynamicMap<TSource, TDestination>(TSource source, TDestination destination)
{
var modelType = typeof (TSource);
var destinationType = typeof (TDestination);
DynamicMap(source, destination, modelType, destinationType);
}
public TDestination DynamicMap<TDestination>(object source)
{
var modelType = source?.GetType() ?? typeof (object);
var destinationType = typeof (TDestination);
return (TDestination) DynamicMap(source, modelType, destinationType);
}
public object DynamicMap(object source, Type sourceType, Type destinationType)
{
var typeMap = ConfigurationProvider.ResolveTypeMap(source, null, sourceType, destinationType);
var context = new ResolutionContext(typeMap, source, sourceType, destinationType,
new MappingOperationOptions
{
CreateMissingTypeMaps = true
}, _mapperContext);
return ((IMappingEngineRunner) this).Map(context);
}
public void DynamicMap(object source, object destination, Type sourceType, Type destinationType)
{
var typeMap = ConfigurationProvider.ResolveTypeMap(source, destination, sourceType, destinationType);
var context = new ResolutionContext(typeMap, source, destination, sourceType, destinationType,
new MappingOperationOptions {CreateMissingTypeMaps = true}, _mapperContext);
((IMappingEngineRunner) this).Map(context);
}
public TDestination Map<TSource, TDestination>(ResolutionContext parentContext, TSource source)
{
var destinationType = typeof (TDestination);
var sourceType = typeof (TSource);
var typeMap = ConfigurationProvider.ResolveTypeMap(source, null, sourceType, destinationType);
var context = parentContext.CreateTypeContext(typeMap, source, null, sourceType, destinationType);
return (TDestination) ((IMappingEngineRunner) this).Map(context);
}
public Expression CreateMapExpression(Type sourceType, Type destinationType, ObjectDictionary parameters = null, params MemberInfo[] membersToExpand)
{
//TODO: this appears to be very definitely new
parameters = parameters ?? new Dictionary<string, object>();
var cachedExpression =
ExpressionCache.GetOrAdd(new ExpressionRequest(sourceType, destinationType, membersToExpand),
tp => CreateMapExpression(tp, DictionaryFactory.CreateDictionary<ExpressionRequest, int>()));
if (!parameters.Any())
return cachedExpression;
var visitor = new ConstantExpressionReplacementVisitor(parameters);
return visitor.Visit(cachedExpression);
}
public LambdaExpression CreateMapExpression(ExpressionRequest request, Internal.IDictionary<ExpressionRequest, int> typePairCount)
{
// this is the input parameter of this expression with name <variableName>
var instanceParameter = Expression.Parameter(request.SourceType, "dto");
var total = CreateMapExpression(request, instanceParameter, typePairCount);
var delegateType = typeof(Func<,>).MakeGenericType(request.SourceType, request.DestinationType);
return Expression.Lambda(delegateType, total, instanceParameter);
}
public Expression CreateMapExpression(ExpressionRequest request,
Expression instanceParameter, Internal.IDictionary<ExpressionRequest, int> typePairCount)
{
var typeMap = ConfigurationProvider.ResolveTypeMap(request.SourceType,
request.DestinationType);
if (typeMap == null)
{
const string MessageFormat = "Missing map from {0} to {1}. Create using Mapper.CreateMap<{0}, {1}>.";
var message = string.Format(MessageFormat, request.SourceType.Name, request.DestinationType.Name);
throw new InvalidOperationException(message);
}
var bindings = CreateMemberBindings(request, typeMap, instanceParameter, typePairCount);
var parameterReplacer = new ParameterReplacementVisitor(instanceParameter);
var visitor = new NewFinderVisitor();
var constructorExpression = typeMap.DestinationConstructorExpression(instanceParameter);
visitor.Visit(parameterReplacer.Visit(constructorExpression));
var expression = Expression.MemberInit(
visitor.NewExpression,
bindings.ToArray()
);
return expression;
}
private class NewFinderVisitor : ExpressionVisitor
{
public NewExpression NewExpression { get; private set; }
protected override Expression VisitNew(NewExpression node)
{
NewExpression = node;
return base.VisitNew(node);
}
}
private List<MemberBinding> CreateMemberBindings(ExpressionRequest request,
TypeMap typeMap,
Expression instanceParameter, Internal.IDictionary<ExpressionRequest, int> typePairCount)
{
var bindings = new List<MemberBinding>();
var visitCount = typePairCount.AddOrUpdate(request, 0, (tp, i) => i + 1);
if (visitCount >= typeMap.MaxDepth)
return bindings;
foreach (var propertyMap in typeMap.GetPropertyMaps().Where(pm => pm.CanResolveValue()))
{
var result = ResolveExpression(propertyMap, request.SourceType, instanceParameter);
if (propertyMap.ExplicitExpansion &&
!request.MembersToExpand.Contains(propertyMap.DestinationProperty.MemberInfo))
continue;
var propertyTypeMap = ConfigurationProvider.ResolveTypeMap(result.Type,
propertyMap.DestinationPropertyType);
var propertyRequest = new ExpressionRequest(result.Type, propertyMap.DestinationPropertyType, request.MembersToExpand);
var binder = Binders.FirstOrDefault(b => b.IsMatch(propertyMap, propertyTypeMap, result));
if (binder == null)
{
var message =
$"Unable to create a map expression from {propertyMap.SourceMember?.DeclaringType?.Name}.{propertyMap.SourceMember?.Name} ({result.Type}) to {propertyMap.DestinationProperty.MemberInfo.DeclaringType?.Name}.{propertyMap.DestinationProperty.Name} ({propertyMap.DestinationPropertyType})";
throw new MicroMapperMappingException(message);
}
var bindExpression = binder.Build(this, propertyMap, propertyTypeMap, propertyRequest, result, typePairCount);
bindings.Add(bindExpression);
}
return bindings;
}
private static ExpressionResolutionResult ResolveExpression(PropertyMap propertyMap, Type currentType,
Expression instanceParameter)
{
var result = new ExpressionResolutionResult(instanceParameter, currentType);
foreach (var resolver in propertyMap.GetSourceValueResolvers())
{
var matchingExpressionConverter =
ExpressionResultConverters.FirstOrDefault(c => c.CanGetExpressionResolutionResult(result, resolver));
if (matchingExpressionConverter == null)
throw new ArgumentException($"Unable to resolve {{{currentType}}} this to Queryable Expression", nameof(currentType));
result = matchingExpressionConverter.GetExpressionResolutionResult(result, propertyMap, resolver);
}
return result;
}
private class ConstantExpressionReplacementVisitor : ExpressionVisitor
{
private readonly System.Collections.Generic.IDictionary<string, object> _paramValues;
public ConstantExpressionReplacementVisitor(
System.Collections.Generic.IDictionary<string, object> paramValues)
{
_paramValues = paramValues;
}
protected override Expression VisitMember(MemberExpression node)
{
if (!node.Member.DeclaringType.Name.Contains("<>"))
return base.VisitMember(node);
if (!_paramValues.ContainsKey(node.Member.Name))
return base.VisitMember(node);
return Expression.Convert(
Expression.Constant(_paramValues[node.Member.Name]),
node.Member.GetMemberType());
}
}
object IMappingEngineRunner.Map(ResolutionContext context)
{
try
{
var contextTypePair = new TypePair(context.SourceType, context.DestinationType);
Func<TypePair, IObjectMapper> missFunc =
tp => _mapperContext.ObjectMappers.FirstOrDefault(mapper => mapper.IsMatch(context));
var mapperToUse = ObjectMapperCache.GetOrAdd(contextTypePair, missFunc);
if (mapperToUse == null || (context.Options.CreateMissingTypeMaps && !mapperToUse.IsMatch(context)))
{
if (context.Options.CreateMissingTypeMaps)
{
var typeMap = ConfigurationProvider.CreateTypeMap(context.SourceType, context.DestinationType);
context = context.CreateTypeContext(typeMap, context.SourceValue, context.DestinationValue, context.SourceType, context.DestinationType);
mapperToUse = missFunc(contextTypePair);
if(mapperToUse == null)
{
throw new MicroMapperMappingException(context, "Unsupported mapping.");
}
ObjectMapperCache.AddOrUpdate(contextTypePair, mapperToUse, (tp, mapper) => mapperToUse);
}
else
{
if(context.SourceValue != null)
{
throw new MicroMapperMappingException(context, "Missing type map configuration or unsupported mapping.");
}
return ObjectCreator.CreateDefaultValue(context.DestinationType);
}
}
return mapperToUse.Map(context);
}
catch (MicroMapperMappingException)
{
throw;
}
catch (Exception ex)
{
throw new MicroMapperMappingException(context, ex);
}
}
object IMappingEngineRunner.CreateObject(ResolutionContext context)
{
var typeMap = context.TypeMap;
var destinationType = context.DestinationType;
if (typeMap != null)
if (typeMap.DestinationCtor != null)
return typeMap.DestinationCtor(context);
else if (typeMap.ConstructDestinationUsingServiceLocator)
return context.Options.ServiceCtor(destinationType);
else if (typeMap.ConstructorMap != null && typeMap.ConstructorMap.CtorParams.All(p => p.CanResolve))
return typeMap.ConstructorMap.ResolveValue(context, this);
if (context.DestinationValue != null)
return context.DestinationValue;
if (destinationType.IsInterface())
destinationType = ProxyGeneratorFactory.Create().GetProxyType(destinationType);
return !ConfigurationProvider.MapNullSourceValuesAsNull
? ObjectCreator.CreateNonNullValue(destinationType)
: ObjectCreator.CreateObject(destinationType);
}
bool IMappingEngineRunner.ShouldMapSourceValueAsNull(ResolutionContext context)
{
if (context.DestinationType.IsValueType() && !context.DestinationType.IsNullableType())
return false;
var typeMap = context.GetContextTypeMap();
if (typeMap != null)
return ConfigurationProvider.GetProfileConfiguration(typeMap.Profile).MapNullSourceValuesAsNull;
return ConfigurationProvider.MapNullSourceValuesAsNull;
}
bool IMappingEngineRunner.ShouldMapSourceCollectionAsNull(ResolutionContext context)
{
var typeMap = context.GetContextTypeMap();
if (typeMap != null)
return ConfigurationProvider.GetProfileConfiguration(typeMap.Profile).MapNullSourceCollectionsAsNull;
return ConfigurationProvider.MapNullSourceCollectionsAsNull;
}
private void ClearTypeMap(object sender, TypeMapCreatedEventArgs e)
{
IObjectMapper existing;
ObjectMapperCache.TryRemove(new TypePair(e.TypeMap.SourceType, e.TypeMap.DestinationType), out existing);
}
private void DefaultMappingOptions(IMappingOperationOptions opts)
{
opts.ConstructServicesUsing(ServiceCtor);
}
public IQueryable<TDestination> MapQuery<TSource, TDestination>(IQueryable<TSource> sourceQuery,
IQueryable<TDestination> destinationQuery)
{
return QueryMapperVisitor.Map(sourceQuery, destinationQuery, this);
}
public IQueryDataSourceInjection<TSource> UseAsDataSource<TSource>(IQueryable<TSource> dataSource)
{
return new QueryDataSourceInjection<TSource>(dataSource, this);
}
[Obsolete("Use ProjectTo instead")]
public IProjectionExpression ProjectQuery<TSource>(IQueryable<TSource> source)
{
return new ProjectionExpression(source, this);
}
public IQueryable<TDestination> ProjectTo<TDestination>(IQueryable source, object parameters,
params Expression<Func<TDestination, object>>[] membersToExpand)
{
return new ProjectionExpression(source, this).To(parameters, membersToExpand);
}
public IQueryable<TDestination> ProjectTo<TDestination>(IQueryable source,
ObjectDictionary parameters, params string[] membersToExpand)
{
return new ProjectionExpression(source, this)
.To<TDestination>(parameters, membersToExpand);
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="StateMachine.cs" company="Appccelerate">
// Copyright (c) 2008-2019 Appccelerate
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.AsyncMachine
{
using System;
using System.Threading.Tasks;
using Events;
using Infrastructure;
using States;
/// <summary>
/// Base implementation of a state machine.
/// </summary>
/// <typeparam name="TState">The type of the state.</typeparam>
/// <typeparam name="TEvent">The type of the event.</typeparam>
public class StateMachine<TState, TEvent> :
INotifier<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
private readonly IFactory<TState, TEvent> factory;
private readonly IStateLogic<TState, TEvent> stateLogic;
/// <summary>
/// Initializes a new instance of the <see cref="StateMachine{TState,TEvent}"/> class.
/// </summary>
/// <param name="factory">The factory used to create internal instances.</param>
/// <param name="stateLogic">The state logic used to handle state changes.</param>
public StateMachine(IFactory<TState, TEvent> factory, IStateLogic<TState, TEvent> stateLogic)
{
this.factory = factory;
this.stateLogic = stateLogic;
}
/// <summary>
/// Occurs when no transition could be executed.
/// </summary>
public event EventHandler<TransitionEventArgs<TState, TEvent>> TransitionDeclined;
/// <summary>
/// Occurs when an exception was thrown inside a transition of the state machine.
/// </summary>
public event EventHandler<TransitionExceptionEventArgs<TState, TEvent>> TransitionExceptionThrown;
/// <summary>
/// Occurs when a transition begins.
/// </summary>
public event EventHandler<TransitionEventArgs<TState, TEvent>> TransitionBegin;
/// <summary>
/// Occurs when a transition completed.
/// </summary>
public event EventHandler<TransitionCompletedEventArgs<TState, TEvent>> TransitionCompleted;
private static async Task SwitchStateTo(
IStateDefinition<TState, TEvent> newState,
StateContainer<TState, TEvent> stateContainer,
IStateDefinitionDictionary<TState, TEvent> stateDefinitions)
{
var oldState = stateContainer
.CurrentStateId
.Map(x => stateDefinitions[x])
.ExtractOr(null);
stateContainer.CurrentStateId = Initializable<TState>.Initialized(newState.Id);
await stateContainer
.ForEach(extension =>
extension.SwitchedState(oldState, newState))
.ConfigureAwait(false);
}
/// <summary>
/// Enters the initial state as specified with <paramref name="initialState"/>.
/// </summary>
/// <param name="stateContainer">Contains all mutable state of of the state machine.</param>
/// <param name="stateDefinitions">The definitions for all states of this state Machine.</param>
/// <param name="initialState">The initial state the state machine should enter.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task EnterInitialState(
StateContainer<TState, TEvent> stateContainer,
IStateDefinitionDictionary<TState, TEvent> stateDefinitions,
TState initialState)
{
await stateContainer.ForEach(extension => extension.EnteringInitialState(initialState))
.ConfigureAwait(false);
var context = this.factory.CreateTransitionContext(null, new Missable<TEvent>(), Missing.Value, this);
await this.EnterInitialState(context, stateContainer, stateDefinitions, initialState)
.ConfigureAwait(false);
await stateContainer.ForEach(extension => extension.EnteredInitialState(initialState, context))
.ConfigureAwait(false);
}
/// <summary>
/// Fires the specified event.
/// </summary>
/// <param name="eventId">The event.</param>
/// <param name="eventArgument">The event argument.</param>
/// <param name="stateContainer">Contains all mutable state of of the state machine.</param>
/// <param name="stateDefinitions">The definitions for all states of this state Machine.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task Fire(
TEvent eventId,
object eventArgument,
StateContainer<TState, TEvent> stateContainer,
IStateDefinitionDictionary<TState, TEvent> stateDefinitions)
{
CheckThatStateMachineHasEnteredInitialState(stateContainer);
await stateContainer.ForEach(extension => extension.FiringEvent(ref eventId, ref eventArgument))
.ConfigureAwait(false);
var currentState = stateContainer
.CurrentStateId
.Map(x => stateDefinitions[x])
.ExtractOrThrow();
var context = this.factory.CreateTransitionContext(currentState, new Missable<TEvent>(eventId), eventArgument, this);
var result = await this.stateLogic.Fire(currentState, context, stateContainer, stateDefinitions)
.ConfigureAwait(false);
if (!result.Fired)
{
this.OnTransitionDeclined(context);
return;
}
var newState = stateDefinitions[result.NewState];
await SwitchStateTo(newState, stateContainer, stateDefinitions)
.ConfigureAwait(false);
await stateContainer.ForEach(extension => extension.FiredEvent(context))
.ConfigureAwait(false);
this.OnTransitionCompleted(context, stateContainer.CurrentStateId.ExtractOrThrow());
}
public void OnExceptionThrown(ITransitionContext<TState, TEvent> context, Exception exception)
{
RethrowExceptionIfNoHandlerRegistered(exception, this.TransitionExceptionThrown);
this.RaiseEvent(this.TransitionExceptionThrown, new TransitionExceptionEventArgs<TState, TEvent>(context, exception), context, false);
}
/// <summary>
/// Fires the <see cref="TransitionBegin"/> event.
/// </summary>
/// <param name="transitionContext">The transition context.</param>
public void OnTransitionBegin(ITransitionContext<TState, TEvent> transitionContext)
{
this.RaiseEvent(this.TransitionBegin, new TransitionEventArgs<TState, TEvent>(transitionContext), transitionContext, true);
}
// ReSharper disable once UnusedParameter.Local
private static void RethrowExceptionIfNoHandlerRegistered<T>(Exception exception, EventHandler<T> exceptionHandler)
where T : EventArgs
{
if (exceptionHandler == null)
{
throw new StateMachineException("No exception listener is registered. Exception: ", exception);
}
}
/// <summary>
/// Fires the <see cref="TransitionDeclined"/> event.
/// </summary>
/// <param name="transitionContext">The transition event context.</param>
private void OnTransitionDeclined(ITransitionContext<TState, TEvent> transitionContext)
{
this.RaiseEvent(this.TransitionDeclined, new TransitionEventArgs<TState, TEvent>(transitionContext), transitionContext, true);
}
private void OnTransitionCompleted(ITransitionContext<TState, TEvent> transitionContext, TState currentStateId)
{
this.RaiseEvent(
this.TransitionCompleted,
new TransitionCompletedEventArgs<TState, TEvent>(
currentStateId,
transitionContext),
transitionContext,
true);
}
private async Task EnterInitialState(
ITransitionContext<TState, TEvent> context,
StateContainer<TState, TEvent> stateContainer,
IStateDefinitionDictionary<TState, TEvent> stateDefinitions,
TState initialStateId)
{
var initialState = stateDefinitions[initialStateId];
var initializer = this.factory.CreateStateMachineInitializer(initialState, context);
var newStateId = await initializer.EnterInitialState(this.stateLogic, stateContainer, stateDefinitions).
ConfigureAwait(false);
var newStateDefinition = stateDefinitions[newStateId];
await SwitchStateTo(newStateDefinition, stateContainer, stateDefinitions)
.ConfigureAwait(false);
}
private void RaiseEvent<T>(EventHandler<T> eventHandler, T arguments, ITransitionContext<TState, TEvent> context, bool raiseEventOnException)
where T : EventArgs
{
try
{
if (eventHandler == null)
{
return;
}
eventHandler(this, arguments);
}
catch (Exception e)
{
if (!raiseEventOnException)
{
throw;
}
((INotifier<TState, TEvent>)this).OnExceptionThrown(context, e);
}
}
private static void CheckThatStateMachineHasEnteredInitialState(StateContainer<TState, TEvent> stateContainer)
{
if (!stateContainer.CurrentStateId.IsInitialized)
{
throw new InvalidOperationException(ExceptionMessages.StateMachineHasNotYetEnteredInitialState);
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Workflow.ComponentModel;
namespace System.Workflow.Runtime
{
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class WorkflowQueue
{
IComparable queueName;
WorkflowQueuingService qService;
internal WorkflowQueue(WorkflowQueuingService qService, IComparable queueName)
{
this.qService = qService;
this.queueName = queueName;
}
public event EventHandler<QueueEventArgs> QueueItemAvailable
{
add
{
if (value == null)
throw new ArgumentNullException("value");
lock (qService.SyncRoot)
{
EventQueueState qState = qService.GetQueueState(this.queueName);
ActivityExecutorDelegateInfo<QueueEventArgs> subscriber = new ActivityExecutorDelegateInfo<QueueEventArgs>(value, qService.CallingActivity);
qState.AsynchronousListeners.Add(subscriber);
WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 0, "WorkflowQueue:QueueItemAvailable subscribe for activity '{0}' with context Id {1}", subscriber.ActivityQualifiedName, subscriber.ContextId);
if (qState.AsynchronousListeners.Count == 1)
qService.NotifyAsynchronousSubscribers(this.queueName, qState, qState.Messages.Count);
}
}
remove
{
lock (qService.SyncRoot)
{
ActivityExecutorDelegateInfo<QueueEventArgs> subscriber = new ActivityExecutorDelegateInfo<QueueEventArgs>(value, qService.CallingActivity);
bool removed = qService.GetQueueState(this.queueName).AsynchronousListeners.Remove(subscriber);
if (!removed)
{
WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 0, "WorkflowQueue:QueueItemAvailable unsubscribe failed for activity '{0}' with context Id {1} ", subscriber.ActivityQualifiedName, subscriber.ContextId);
}
}
}
}
public void RegisterForQueueItemAvailable(IActivityEventListener<QueueEventArgs> eventListener)
{
RegisterForQueueItemAvailable(eventListener, null);
}
public void RegisterForQueueItemAvailable(IActivityEventListener<QueueEventArgs> eventListener, string subscriberQualifiedName)
{
if (eventListener == null)
throw new ArgumentNullException("eventListener");
lock (qService.SyncRoot)
{
EventQueueState qState = qService.GetQueueState(this.queueName);
ActivityExecutorDelegateInfo<QueueEventArgs> subscriber = new ActivityExecutorDelegateInfo<QueueEventArgs>(eventListener, qService.CallingActivity);
if (subscriberQualifiedName != null)
{
subscriber.SubscribedActivityQualifiedName = subscriberQualifiedName;
}
qState.AsynchronousListeners.Add(subscriber);
WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 0, "WorkflowQueue:QueueItemAvailable subscribe for activity '{0}' with context Id {1}", subscriber.ActivityQualifiedName, subscriber.ContextId);
if (qState.AsynchronousListeners.Count == 1)
qService.NotifyAsynchronousSubscribers(this.queueName, qState, qState.Messages.Count);
}
}
public void UnregisterForQueueItemAvailable(IActivityEventListener<QueueEventArgs> eventListener)
{
if (eventListener == null)
throw new ArgumentNullException("eventListener");
lock (qService.SyncRoot)
{
ActivityExecutorDelegateInfo<QueueEventArgs> subscriber = new ActivityExecutorDelegateInfo<QueueEventArgs>(eventListener, qService.CallingActivity);
bool removed = qService.GetQueueState(this.queueName).AsynchronousListeners.Remove(subscriber);
if (!removed)
{
WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 0, "WorkflowQueue:QueueItemAvailable unsubscribe failed for activity '{0}' with context Id {1}", subscriber.ActivityQualifiedName, subscriber.ContextId);
}
}
}
public event EventHandler<QueueEventArgs> QueueItemArrived
{
add
{
if (value == null)
throw new ArgumentNullException("value");
lock (qService.SyncRoot)
{
qService.GetQueueState(this.queueName).SynchronousListeners.Add(new ActivityExecutorDelegateInfo<QueueEventArgs>(value, qService.CallingActivity));
}
}
remove
{
if (value == null)
throw new ArgumentNullException("value");
lock (qService.SyncRoot)
{
qService.GetQueueState(this.queueName).SynchronousListeners.Remove(new ActivityExecutorDelegateInfo<QueueEventArgs>(value, qService.CallingActivity));
}
}
}
public void RegisterForQueueItemArrived(IActivityEventListener<QueueEventArgs> eventListener)
{
if (eventListener == null)
throw new ArgumentNullException("eventListener");
lock (qService.SyncRoot)
{
qService.GetQueueState(this.queueName).SynchronousListeners.Add(new ActivityExecutorDelegateInfo<QueueEventArgs>(eventListener, qService.CallingActivity));
}
}
public void UnregisterForQueueItemArrived(IActivityEventListener<QueueEventArgs> eventListener)
{
if (eventListener == null)
throw new ArgumentNullException("eventListener");
lock (qService.SyncRoot)
{
qService.GetQueueState(this.queueName).SynchronousListeners.Remove(new ActivityExecutorDelegateInfo<QueueEventArgs>(eventListener, qService.CallingActivity));
}
}
public IComparable QueueName
{
get
{
return this.queueName;
}
}
public WorkflowQueuingService QueuingService
{
get
{
return this.qService;
}
}
public void Enqueue(object item)
{
lock (qService.SyncRoot)
{
qService.EnqueueEvent(this.queueName, item);
}
}
public object Dequeue()
{
lock (qService.SyncRoot)
{
object message = qService.Peek(this.queueName);
return qService.DequeueEvent(this.queueName);
}
}
public object Peek()
{
lock (qService.SyncRoot)
{
object message = qService.Peek(this.queueName);
return message;
}
}
public int Count
{
get
{
lock (qService.SyncRoot)
{
return this.qService.GetQueueState(this.queueName).Messages.Count;
}
}
}
public bool Enabled
{
get
{
lock (qService.SyncRoot)
{
return this.qService.GetQueueState(this.queueName).Enabled;
}
}
set
{
lock (qService.SyncRoot)
{
this.qService.GetQueueState(this.queueName).Enabled = value;
}
}
}
}
}
| |
using System;
using System.IO;
namespace Whitelog.Core.File
{
public class FileStreamProvider : IStreamProvider
{
private FileConfiguration m_configuration;
private DateTime? m_nextArchive;
public string FileName { get; private set; }
public FileStreamProvider(FileConfiguration configuration)
{
m_configuration = configuration;
FileName = GetFileName(configuration);
}
public Stream GetStream()
{
var filePath = GetFileName(m_configuration);
if (System.IO.File.Exists(filePath))
{
if (m_configuration.AppendToEnd)
{
if (m_configuration.ArchiveEvery.HasValue)
{
var originalCreationDate = System.IO.File.GetCreationTime(filePath);
if ((m_configuration.ArchiveEvery.Value == ArchiveOptions.Hour && originalCreationDate.AddHours(1) > DateTime.Now) ||
(m_configuration.ArchiveEvery.Value == ArchiveOptions.Day && originalCreationDate.AddDays(1) > DateTime.Now) ||
(m_configuration.ArchiveEvery.Value == ArchiveOptions.Week && originalCreationDate.AddDays(7) > DateTime.Now) ||
(m_configuration.ArchiveEvery.Value == ArchiveOptions.Month && originalCreationDate.AddMonths(1) > DateTime.Now))
{
return new OverrideStreamFlush(CreateFile(filePath));
}
}
else
{
return new OverrideStreamFlush(CreateFile(filePath));
}
}
if (!m_configuration.Archive)
{
throw new Exception(string.Format("The file '{0}' already exist and not configured to be archived", filePath));
}
ArchiveFile(m_configuration, filePath);
return new OverrideStreamFlush(CreateFile(filePath));
}
else
{
return new OverrideStreamFlush(CreateFile(filePath));
}
}
public bool ShouldArchive(long currSize, int bytesToAdd, DateTime now)
{
if (m_configuration.ArchiveAboveSize.HasValue)
{
if ((currSize + bytesToAdd) > m_configuration.ArchiveAboveSize.Value)
{
return true;
}
}
if (m_configuration.ArchiveEvery.HasValue)
{
if (!m_nextArchive.HasValue)
{
m_nextArchive = GetNextArchiveTime(m_configuration, now);
}
if (now > m_nextArchive.Value)
{
return true;
}
}
return false;
}
public void Archive()
{
var filePath = GetFileName(m_configuration);
if (System.IO.File.Exists(filePath))
{
ArchiveFile(m_configuration, filePath);
}
}
private static void ArchiveFile(FileConfiguration configuration, string filePath)
{
string archiveFilePath = GetArchiveFileName(configuration, filePath);
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(archiveFilePath))))
{
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(archiveFilePath)));
}
if (configuration.ArchiveNumbering == ArchiveNumberingOptions.Sequence)
{
var filesMatchDescription = System.IO.Directory.GetFiles(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(archiveFilePath)),
System.IO.Path.GetFileNameWithoutExtension(archiveFilePath) + ".*" + System.IO.Path.GetExtension(archiveFilePath));
int maxIndexFound = 0;
foreach (var currFile in filesMatchDescription)
{
var start = System.IO.Path.GetFileNameWithoutExtension(archiveFilePath).Length + 1;
var legnth = System.IO.Path.GetFileName(currFile).Length - start - System.IO.Path.GetExtension(archiveFilePath).Length;
var sequenceString = System.IO.Path.GetFileName(currFile).Substring(System.IO.Path.GetFileNameWithoutExtension(archiveFilePath).Length + 1, legnth);
int sequenceNumber;
if (int.TryParse(sequenceString, out sequenceNumber))
{
if (sequenceNumber > maxIndexFound)
{
maxIndexFound = sequenceNumber;
}
}
}
// The file now archived.
System.IO.File.Move(filePath, System.IO.Path.Combine(System.IO.Path.GetDirectoryName(archiveFilePath), System.IO.Path.GetFileNameWithoutExtension(archiveFilePath)) + "." + (maxIndexFound + 1) + System.IO.Path.GetExtension(archiveFilePath));
}
}
public static DateTime? GetNextArchiveTime(FileConfiguration configuration,DateTime now)
{
if (!configuration.ArchiveEvery.HasValue)
{
return null;
}
else
{
switch (configuration.ArchiveEvery.Value)
{
case ArchiveOptions.Hour:
return new DateTime(now.Year,now.Month,now.Day,now.Hour,0,0).AddHours(1);
case ArchiveOptions.Day:
return now.Date.AddDays(1);
case ArchiveOptions.Week:
return now.Date.AddDays(7);
case ArchiveOptions.Month:
return new DateTime(now.Year, now.Month, 1).AddMonths(1);
}
}
return null;
}
private static string GetArchiveFileName(FileConfiguration configuration, string originalPath)
{
string archiveFormat = configuration.ArchiveFilePath;
if (string.IsNullOrWhiteSpace(archiveFormat))
{
archiveFormat = configuration.FilePath;
if (string.IsNullOrWhiteSpace(archiveFormat))
{
archiveFormat = string.Format(@"{{SOURCEPATH}}{0}{{SOURCENAME}}",Path.DirectorySeparatorChar);
}
}
string archiveFilePath = string.Empty;
foreach (var part in StringParser.GetParts(archiveFormat))
{
if (part.IsConst)
{
archiveFilePath += part.Value;
}
else
{
switch (part.Value.ToUpper())
{
case "BASEDIR":
archiveFilePath += System.AppDomain.CurrentDomain.BaseDirectory;
break;
case "WORKDIR":
archiveFilePath += Environment.CurrentDirectory;
break;
case "USERDIR":
archiveFilePath += Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
break;
case "DATE":
archiveFilePath += DateTime.Now.ToString("yyyy.MM.dd");
break;
case "DATETIME":
archiveFilePath += DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss");
break;
case "SOURCENAME":
archiveFilePath += System.IO.Path.GetFileName(originalPath);
break;
case "SOURCEPATH":
archiveFilePath += System.IO.Path.GetDirectoryName(originalPath);
break;
}
}
}
return archiveFilePath;
}
private static string GetFileName(FileConfiguration configuration)
{
string baseFilePath = configuration.FilePath;
if (string.IsNullOrWhiteSpace(configuration.FilePath))
{
baseFilePath = string.Format(@"${{BaseDir}}{0}Log.txt",Path.DirectorySeparatorChar);
}
string filePath = string.Empty;
foreach (var part in StringParser.GetParts(baseFilePath))
{
if (part.IsConst)
{
filePath += part.Value;
}
else
{
switch (part.Value.ToUpper())
{
case "BASEDIR":
filePath += System.AppDomain.CurrentDomain.BaseDirectory;
break;
case "WORKDIR":
filePath += Environment.CurrentDirectory;
break;
case "USERDIR":
filePath += Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
break;
case "DATE":
filePath += DateTime.Now.Date.ToString("yyyy.MM.dd");
break;
case "DATETIME":
filePath += DateTime.Now.ToString("yyyy.MM.dd HH.mm.ss");
break;
}
}
}
return filePath;
}
private FileStream CreateFile(string filePath)
{
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(filePath))))
{
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(filePath)));
}
// http://support.microsoft.com/?kbid=172190
// http://stackoverflow.com/questions/2109152/unbelievable-strange-file-creation-time-problem
// there is a bug with the creation time, to overcome this problem we need to change the file creation time manualy
FileName = filePath;
using (var strem = System.IO.File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
{
}
new FileInfo(FileName).CreationTime = DateTime.Now;
return System.IO.File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
}
}
}
| |
using System;
using System.Collections;
using PX.Data;
using PX.TrelloIntegration.Trello;
using System.Web;
using System.Linq;
using PX.SM;
using System.Collections.Generic;
namespace PX.TrelloIntegration
{
public class TrelloSetupMaint : PXGraph<TrelloSetupMaint>
{
#region DataViews
public PXSave<TrelloSetup> Save;
public PXCancel<TrelloSetup> Cancel;
public PXSelect<TrelloSetup> Document;
public PXSelect<TrelloBoardMapping> Boards;
public PXSelect<TrelloBoardMapping,
Where<TrelloBoardMapping.boardID,
Equal<Current<TrelloBoardMapping.boardID>>>> CurrentBoard;
public PXSelect<TrelloBoardMapping,
Where<TrelloBoardMapping.parentBoardID,
Equal<Optional<TrelloBoardMapping.boardID>>>> ChildBoards;
public PXSelect<TrelloListMapping,
Where<TrelloListMapping.boardID,
Equal<Optional<TrelloBoardMapping.boardID>>>> List;
#endregion
#region Delegates
protected virtual IEnumerable boards(
[PXInt]
int? boardID
)
{
if (boardID == null)
{
yield return new TrelloBoardMapping()
{
ParentBoardID = 0,
BoardID = 0
};
}
else
{
foreach (TrelloBoardMapping trelloBoard in ChildBoards.Select(boardID))
{
yield return trelloBoard;
}
}
}
protected virtual IEnumerable currentBoard()
{
if (Boards.Current != null)
{
var isNotRoot = Boards.Current.BoardID != 0;
var isMainTypeMapping = Boards.Current.ParentBoardID == 0;
var hasChildBoard = ChildBoards.Select(Boards.Current.BoardID).Any();
var isCompleted = isMainTypeMapping
? Boards.Current.BoardType.HasValue
: !string.IsNullOrEmpty(Boards.Current.ClassID) &&
!string.IsNullOrEmpty(Boards.Current.TrelloBoardID);
var typeOrClassFilled = isMainTypeMapping
? Boards.Current.BoardType.HasValue
: !string.IsNullOrEmpty(Boards.Current.ClassID);
var trelloBoardIDFilled = !string.IsNullOrEmpty(Boards.Current.TrelloBoardID);
AddBoard.SetEnabled(!isNotRoot || (isMainTypeMapping && isCompleted));
DeleteBoard.SetEnabled(isNotRoot);
PopulateStates.SetEnabled(trelloBoardIDFilled);
PXUIFieldAttribute.SetVisible<TrelloBoardMapping.boardType>(Caches[typeof(TrelloBoardMapping)], null, isMainTypeMapping);
PXUIFieldAttribute.SetVisible<TrelloBoardMapping.classID>(Caches[typeof(TrelloBoardMapping)], null, !isMainTypeMapping);
PXUIFieldAttribute.SetEnabled<TrelloBoardMapping.boardType>(Caches[typeof(TrelloBoardMapping)], null, isNotRoot && !hasChildBoard && !trelloBoardIDFilled);
PXUIFieldAttribute.SetEnabled<TrelloBoardMapping.classID>(Caches[typeof(TrelloBoardMapping)], null, isNotRoot);
PXUIFieldAttribute.SetEnabled<TrelloBoardMapping.trelloBoardID>(Caches[typeof(TrelloBoardMapping)], null, isNotRoot && typeOrClassFilled);
Caches[typeof(TrelloBoardMapping)].AllowInsert = isNotRoot;
Caches[typeof(TrelloBoardMapping)].AllowDelete = isNotRoot;
Caches[typeof(TrelloBoardMapping)].AllowUpdate = isNotRoot;
foreach (TrelloBoardMapping item in PXSelect<TrelloBoardMapping,
Where<TrelloBoardMapping.boardID,
Equal<Required<TrelloBoardMapping.boardID>>>>.
Select(this, Boards.Current.BoardID))
{
yield return item;
}
}
}
#endregion
#region CTOR
public TrelloSetupMaint()
{
List.AllowInsert =
List.AllowDelete = false;
}
#endregion
#region Event Handlers
public virtual void TrelloSetup_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
{
var row = (TrelloSetup)e.Row;
if(row != null)
{
var isConnected = !string.IsNullOrEmpty(row.TrelloUsrToken);
login.SetVisible(!isConnected);
logout.SetVisible(isConnected);
PXUIFieldAttribute.SetEnabled<TrelloSetup.trelloOrganizationID>(sender, row, isConnected);
CurrentBoard.AllowUpdate = CurrentBoard.AllowUpdate && isConnected;
List.AllowUpdate = isConnected;
AddBoard.SetEnabled(AddBoard.GetEnabled() && isConnected);
DeleteBoard.SetEnabled(DeleteBoard.GetEnabled() && isConnected);
PopulateStates.SetEnabled(PopulateStates.GetEnabled() && isConnected);
}
}
public virtual void TrelloBoardMapping_TrelloBoardID_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
{
UpdateStates((TrelloBoardMapping)e.Row, true);
}
public virtual void TrelloBoardMapping_RowPersisting(PXCache sender, PXRowPersistingEventArgs e)
{
var row = (TrelloBoardMapping)e.Row;
PXDefaultAttribute.SetPersistingCheck<TrelloBoardMapping.classID>(
sender,
row,
row.ParentBoardID == 0 ?
PXPersistingCheck.Nothing :
PXPersistingCheck.NullOrBlank);
PXDefaultAttribute.SetPersistingCheck<TrelloBoardMapping.trelloBoardID>(
sender,
row,
row.ParentBoardID == 0 ?
PXPersistingCheck.Nothing :
PXPersistingCheck.NullOrBlank);
}
public override void Persist()
{
base.Persist();
foreach (TrelloBoardMapping item in Caches[typeof(TrelloBoardMapping)].Cached)
{
if (item.TempParentID < 0)
{
foreach (TrelloBoardMapping item2 in Caches[typeof(TrelloBoardMapping)].Cached)
{
if (item2.TempChildID == item.TempParentID)
{
item.ParentBoardID = item2.BoardID;
item.TempParentID = item2.BoardID;
Caches[typeof(TrelloBoardMapping)].SetStatus(item, PXEntryStatus.Updated);
}
}
}
}
base.Persist();
}
#endregion
#region Actions
public PXAction<TrelloSetup> login;
[PXUIField(DisplayName = "Login to Trello")]
[PXButton(ImageKey = "LinkWB")]
public virtual void Login()
{
Actions.PressSave();
throw new PXRedirectToUrlException(TrelloUrl, PXBaseRedirectException.WindowMode.Same, "Login To Trello");
}
public PXAction<TrelloSetup> logout;
[PXUIField(DisplayName = "Logout")]
[PXButton(ImageKey = "LinkWB")]
public virtual void Logout()
{
var setup = Document.Current;
setup.ConnectionDateTime = null;
setup.UserName = null;
setup.TrelloUsrToken = null;
Document.Update(setup);
Actions.PressSave();
}
public PXAction<TrelloSetup> completeAuthentication;
[PXButton()]
public virtual IEnumerable CompleteAuthentication(PXAdapter adapter)
{
var token = TrelloToken.GetToken(adapter.CommandArguments);
//If the user deny the authentication token will be blank
if(!string.IsNullOrEmpty(token.Token))
{
var setup = Document.Current;
setup.TrelloUsrToken = token.Token;
var memberRepo = new TrelloMemberRepository(setup);
var currentMember = memberRepo.GetCurrentMember();
setup.ConnectionDateTime = DateTime.Now;
setup.UserName = currentMember.Name;
Document.Update(setup);
this.Actions.PressSave();
}
return adapter.Get();
}
public PXAction<TrelloSetup> AddBoard;
[PXUIField(DisplayName = " ", MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select, Enabled = true)]
[PXButton()]
public virtual IEnumerable addBoard(PXAdapter adapter)
{
var selectedBoard = Boards.Current;
if (selectedBoard.ParentBoardID == 0)
{
var inserted = (TrelloBoardMapping)Caches[typeof(TrelloBoardMapping)].Insert(new TrelloBoardMapping
{
BoardType = Boards.Current.BoardType,
ParentBoardID = Boards.Current.BoardID
});
inserted.TempChildID = inserted.BoardID;
inserted.TempParentID = inserted.ParentBoardID;
Boards.Cache.ActiveRow = inserted;
}
return adapter.Get();
}
public PXAction<TrelloSetup> DeleteBoard;
[PXUIField(DisplayName = " ", MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select, Enabled = true)]
[PXButton()]
public virtual IEnumerable deleteBoard(PXAdapter adapter)
{
var selectedBoard = Boards.Current;
if(selectedBoard.BoardID != 0)
{
if(selectedBoard.ParentBoardID == 0)
{
var childrenBoards = ChildBoards
.Select(selectedBoard.BoardID)
.Select(br => (TrelloBoardMapping)br).ToList();
if (childrenBoards.Any())
{
if (Document.Ask(Messages.ValidationDeleteChildren, MessageButtons.YesNo) == WebDialogResult.Yes)
{
foreach(var childrenBoard in childrenBoards)
{
Caches[typeof(TrelloBoardMapping)].Delete(childrenBoard);
}
Caches[typeof(TrelloBoardMapping)].Delete(selectedBoard);
}
}
else
{
Caches[typeof(TrelloBoardMapping)].Delete(selectedBoard);
}
}
else
{
Caches[typeof(TrelloBoardMapping)].Delete(selectedBoard);
}
}
return adapter.Get();
}
public PXAction<TrelloSetup> PopulateStates;
[PXButton]
[PXUIField(DisplayName = "Reload")]
public virtual void populateStates()
{
var board = (TrelloBoardMapping)Caches[typeof(TrelloBoardMapping)].Current;
UpdateStates(board, false);
}
#endregion
#region Configuration Helpers
public virtual void UpdateStates(TrelloBoardMapping board, bool purgeList)
{
if(board != null)
{
if (purgeList || string.IsNullOrEmpty(board.TrelloBoardID))
{
foreach (TrelloListMapping list in List.Select(board.BoardID))
List.Delete(list);
}
if(!string.IsNullOrEmpty(board.TrelloBoardID))
{
var listMapping = List.Select(board.BoardID)
.Select(tl => (TrelloListMapping)tl)
.ToList();
var currentSteps = listMapping
.Select(tl => Tuple.Create(tl.ScreenID, tl.StepID))
.ToList();
var systemSteps = PXSelect<AUStep,
Where<AUStep.screenID,
Equal<Required<AUStep.screenID>>>>
.Select(this, BoardTypes.GetBoardTypeScreenID(board.BoardType.GetValueOrDefault()))
.Select(aus => Tuple.Create(((AUStep)aus).ScreenID, ((AUStep)aus).StepID))
.ToList();
//Remove deprecated mapping
foreach (var list in listMapping.Where(tl => !systemSteps.Contains(Tuple.Create(tl.ScreenID, tl.StepID))))
List.Delete(list);
//Add new Mapping
foreach (var step in systemSteps.Where(st => !currentSteps.Contains(st)))
List.Insert(new TrelloListMapping() { BoardID = board.BoardID, ScreenID = step.Item1, StepID = step.Item2 });
}
}
}
#endregion
#region Connection Helpers
public string TrelloUrl
{
get
{
return String.Format("https://trello.com/1/authorize?expiration=never&name=Acumatica&callback_method=fragment&key={0}&return_url={1}&scope=read,write,account&response_type=token",
Properties.Settings.Default.TrelloAPIKey,
System.Web.HttpContext.Current.Request.UrlReferrer.GetLeftPart(UriPartial.Path) + "Frames/TrelloAuthenticator.html");
}
}
public class TrelloToken
{
public string Token { get; }
private TrelloToken(string token)
{
Token = token;
}
public static TrelloToken GetToken(string arg)
{
return new TrelloToken(HttpUtility.ParseQueryString(arg).Get("token"));
}
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
/// <summary>
/// Binary builder implementation.
/// </summary>
internal class BinaryObjectBuilder : IBinaryObjectBuilder
{
/** Cached dictionary with no values. */
private static readonly IDictionary<int, BinaryBuilderField> EmptyVals =
new Dictionary<int, BinaryBuilderField>();
/** Binary. */
private readonly Binary _binary;
/** */
private readonly BinaryObjectBuilder _parent;
/** Initial binary object. */
private readonly BinaryObject _obj;
/** Type descriptor. */
private readonly IBinaryTypeDescriptor _desc;
/** Values. */
private IDictionary<string, BinaryBuilderField> _vals;
/** Contextual fields. */
private IDictionary<int, BinaryBuilderField> _cache;
/** Hash code. */
private int _hashCode;
/** Current context. */
private Context _ctx;
/** Write array action. */
private static readonly Action<BinaryWriter, object> WriteArrayAction =
(w, o) => w.WriteArrayInternal((Array) o);
/** Write collection action. */
private static readonly Action<BinaryWriter, object> WriteCollectionAction =
(w, o) => w.WriteCollection((ICollection) o);
/** Write timestamp action. */
private static readonly Action<BinaryWriter, object> WriteTimestampAction =
(w, o) => w.WriteTimestamp((DateTime?) o);
/** Write timestamp array action. */
private static readonly Action<BinaryWriter, object> WriteTimestampArrayAction =
(w, o) => w.WriteTimestampArray((DateTime?[])o);
/// <summary>
/// Constructor.
/// </summary>
/// <param name="binary">Binary.</param>
/// <param name="parent">Parent builder.</param>
/// <param name="obj">Initial binary object.</param>
/// <param name="desc">Type descriptor.</param>
public BinaryObjectBuilder(Binary binary, BinaryObjectBuilder parent,
BinaryObject obj, IBinaryTypeDescriptor desc)
{
Debug.Assert(binary != null);
Debug.Assert(obj != null);
Debug.Assert(desc != null);
_binary = binary;
_parent = parent ?? this;
_obj = obj;
_desc = desc;
_hashCode = obj.GetHashCode();
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetHashCode(int hashCode)
{
_hashCode = hashCode;
return this;
}
/** <inheritDoc /> */
public T GetField<T>(string name)
{
BinaryBuilderField field;
if (_vals != null && _vals.TryGetValue(name, out field))
return field != BinaryBuilderField.RmvMarker ? (T) field.Value : default(T);
int pos;
if (!_obj.TryGetFieldPosition(name, out pos))
return default(T);
T val;
if (TryGetCachedField(pos, out val))
return val;
val = _obj.GetField<T>(pos, this);
var fld = CacheField(pos, val);
SetField0(name, fld);
return val;
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetField<T>(string fieldName, T val)
{
return SetField0(fieldName,
new BinaryBuilderField(typeof (T), val, BinarySystemHandlers.GetTypeId(typeof (T))));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetArrayField<T>(string fieldName, T[] val)
{
return SetField0(fieldName,
new BinaryBuilderField(typeof (T[]), val, BinaryUtils.TypeArray, WriteArrayAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetBooleanField(string fieldName, bool val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (bool), val, BinaryUtils.TypeBool,
(w, o) => w.WriteBoolean((bool) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetBooleanArrayField(string fieldName, bool[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (bool[]), val, BinaryUtils.TypeArrayBool,
(w, o) => w.WriteBooleanArray((bool[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetByteField(string fieldName, byte val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (byte), val, BinaryUtils.TypeByte,
(w, o) => w.WriteByte((byte) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetByteArrayField(string fieldName, byte[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (byte[]), val, BinaryUtils.TypeArrayByte,
(w, o) => w.WriteByteArray((byte[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetCharField(string fieldName, char val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (char), val, BinaryUtils.TypeChar,
(w, o) => w.WriteChar((char) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetCharArrayField(string fieldName, char[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (char[]), val, BinaryUtils.TypeArrayChar,
(w, o) => w.WriteCharArray((char[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetCollectionField(string fieldName, ICollection val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (ICollection), val, BinaryUtils.TypeCollection,
WriteCollectionAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDecimalField(string fieldName, decimal? val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (decimal?), val, BinaryUtils.TypeDecimal,
(w, o) => w.WriteDecimal((decimal?) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDecimalArrayField(string fieldName, decimal?[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (decimal?[]), val, BinaryUtils.TypeArrayDecimal,
(w, o) => w.WriteDecimalArray((decimal?[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDictionaryField(string fieldName, IDictionary val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (IDictionary), val, BinaryUtils.TypeDictionary,
(w, o) => w.WriteDictionary((IDictionary) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDoubleField(string fieldName, double val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (double), val, BinaryUtils.TypeDouble,
(w, o) => w.WriteDouble((double) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetDoubleArrayField(string fieldName, double[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (double[]), val, BinaryUtils.TypeArrayDouble,
(w, o) => w.WriteDoubleArray((double[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetEnumField<T>(string fieldName, T val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (T), val, BinaryUtils.TypeEnum,
(w, o) => w.WriteEnum((T) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetEnumArrayField<T>(string fieldName, T[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (T[]), val, BinaryUtils.TypeArrayEnum,
(w, o) => w.WriteEnumArray((T[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetFloatField(string fieldName, float val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (float), val, BinaryUtils.TypeFloat,
(w, o) => w.WriteFloat((float) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetFloatArrayField(string fieldName, float[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (float[]), val, BinaryUtils.TypeArrayFloat,
(w, o) => w.WriteFloatArray((float[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetGuidField(string fieldName, Guid? val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (Guid?), val, BinaryUtils.TypeGuid,
(w, o) => w.WriteGuid((Guid?) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetGuidArrayField(string fieldName, Guid?[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (Guid?[]), val, BinaryUtils.TypeArrayGuid,
(w, o) => w.WriteGuidArray((Guid?[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetIntField(string fieldName, int val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (int), val, BinaryUtils.TypeInt,
(w, o) => w.WriteInt((int) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetIntArrayField(string fieldName, int[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (int[]), val, BinaryUtils.TypeArrayInt,
(w, o) => w.WriteIntArray((int[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetLongField(string fieldName, long val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (long), val, BinaryUtils.TypeLong,
(w, o) => w.WriteLong((long) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetLongArrayField(string fieldName, long[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (long[]), val, BinaryUtils.TypeArrayLong,
(w, o) => w.WriteLongArray((long[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetShortField(string fieldName, short val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (short), val, BinaryUtils.TypeShort,
(w, o) => w.WriteShort((short) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetShortArrayField(string fieldName, short[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (short[]), val, BinaryUtils.TypeArrayShort,
(w, o) => w.WriteShortArray((short[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetStringField(string fieldName, string val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (string), val, BinaryUtils.TypeString,
(w, o) => w.WriteString((string) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetStringArrayField(string fieldName, string[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (string[]), val, BinaryUtils.TypeArrayString,
(w, o) => w.WriteStringArray((string[]) o)));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetTimestampField(string fieldName, DateTime? val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (DateTime?), val, BinaryUtils.TypeTimestamp,
WriteTimestampAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder SetTimestampArrayField(string fieldName, DateTime?[] val)
{
return SetField0(fieldName, new BinaryBuilderField(typeof (DateTime?[]), val, BinaryUtils.TypeArrayTimestamp,
WriteTimestampArrayAction));
}
/** <inheritDoc /> */
public IBinaryObjectBuilder RemoveField(string name)
{
return SetField0(name, BinaryBuilderField.RmvMarker);
}
/** <inheritDoc /> */
public IBinaryObject Build()
{
BinaryHeapStream inStream = new BinaryHeapStream(_obj.Data);
inStream.Seek(_obj.Offset, SeekOrigin.Begin);
// Assume that resulting length will be no less than header + [fields_cnt] * 12;
int estimatedCapacity = BinaryObjectHeader.Size + (_vals == null ? 0 : _vals.Count*12);
BinaryHeapStream outStream = new BinaryHeapStream(estimatedCapacity);
BinaryWriter writer = _binary.Marshaller.StartMarshal(outStream);
writer.SetBuilder(this);
// All related builders will work in this context with this writer.
_parent._ctx = new Context(writer);
try
{
// Write.
writer.Write(this);
// Process metadata.
_binary.Marshaller.FinishMarshal(writer);
// Create binary object once metadata is processed.
return new BinaryObject(_binary.Marshaller, outStream.InternalArray, 0,
BinaryObjectHeader.Read(outStream, 0));
}
finally
{
// Cleanup.
_parent._ctx.Closed = true;
}
}
/// <summary>
/// Create child builder.
/// </summary>
/// <param name="obj">binary object.</param>
/// <returns>Child builder.</returns>
public BinaryObjectBuilder Child(BinaryObject obj)
{
var desc = _binary.Marshaller.GetDescriptor(true, obj.TypeId);
return new BinaryObjectBuilder(_binary, null, obj, desc);
}
/// <summary>
/// Get cache field.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="val">Value.</param>
/// <returns><c>true</c> if value is found in cache.</returns>
public bool TryGetCachedField<T>(int pos, out T val)
{
if (_parent._cache != null)
{
BinaryBuilderField res;
if (_parent._cache.TryGetValue(pos, out res))
{
val = res != null ? (T) res.Value : default(T);
return true;
}
}
val = default(T);
return false;
}
/// <summary>
/// Add field to cache test.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="val">Value.</param>
public BinaryBuilderField CacheField<T>(int pos, T val)
{
if (_parent._cache == null)
_parent._cache = new Dictionary<int, BinaryBuilderField>(2);
var hdr = _obj.Data[pos];
var field = new BinaryBuilderField(typeof(T), val, hdr, GetWriteAction(hdr, pos));
_parent._cache[pos] = field;
return field;
}
/// <summary>
/// Gets the write action by header.
/// </summary>
/// <param name="header">The header.</param>
/// <param name="pos">Position.</param>
/// <returns>Write action.</returns>
private Action<BinaryWriter, object> GetWriteAction(byte header, int pos)
{
// We need special actions for all cases where SetField(X) produces different result from SetSpecialField(X)
// Arrays, Collections, Dates
switch (header)
{
case BinaryUtils.TypeArray:
return WriteArrayAction;
case BinaryUtils.TypeCollection:
return WriteCollectionAction;
case BinaryUtils.TypeTimestamp:
return WriteTimestampAction;
case BinaryUtils.TypeArrayTimestamp:
return WriteTimestampArrayAction;
case BinaryUtils.TypeArrayEnum:
using (var stream = new BinaryHeapStream(_obj.Data))
{
stream.Seek(pos, SeekOrigin.Begin + 1);
var elementTypeId = stream.ReadInt();
return (w, o) => w.WriteEnumArrayInternal((Array) o, elementTypeId);
}
default:
return null;
}
}
/// <summary>
/// Internal set field routine.
/// </summary>
/// <param name="fieldName">Name.</param>
/// <param name="val">Value.</param>
/// <returns>This builder.</returns>
private IBinaryObjectBuilder SetField0(string fieldName, BinaryBuilderField val)
{
if (_vals == null)
_vals = new Dictionary<string, BinaryBuilderField>();
_vals[fieldName] = val;
return this;
}
/// <summary>
/// Mutate binary object.
/// </summary>
/// <param name="inStream">Input stream with initial object.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="desc">Type descriptor.</param>
/// <param name="hashCode">Hash code.</param>
/// <param name="vals">Values.</param>
private void Mutate(
BinaryHeapStream inStream,
BinaryHeapStream outStream,
IBinaryTypeDescriptor desc,
int hashCode,
IDictionary<string, BinaryBuilderField> vals)
{
// Set correct builder to writer frame.
BinaryObjectBuilder oldBuilder = _parent._ctx.Writer.SetBuilder(_parent);
int streamPos = inStream.Position;
try
{
// Prepare fields.
IBinaryTypeHandler metaHnd = _binary.Marshaller.GetBinaryTypeHandler(desc);
IDictionary<int, BinaryBuilderField> vals0;
if (vals == null || vals.Count == 0)
vals0 = EmptyVals;
else
{
vals0 = new Dictionary<int, BinaryBuilderField>(vals.Count);
foreach (KeyValuePair<string, BinaryBuilderField> valEntry in vals)
{
int fieldId = BinaryUtils.FieldId(desc.TypeId, valEntry.Key, desc.NameMapper, desc.IdMapper);
if (vals0.ContainsKey(fieldId))
throw new IgniteException("Collision in field ID detected (change field name or " +
"define custom ID mapper) [fieldName=" + valEntry.Key + ", fieldId=" + fieldId + ']');
vals0[fieldId] = valEntry.Value;
// Write metadata if: 1) it is enabled for type; 2) type is not null (i.e. it is neither
// remove marker, nor a field read through "GetField" method.
if (metaHnd != null && valEntry.Value.Type != null)
metaHnd.OnFieldWrite(fieldId, valEntry.Key, valEntry.Value.TypeId);
}
}
// Actual processing.
Mutate0(_parent._ctx, inStream, outStream, true, hashCode, vals0);
// 3. Handle metadata.
if (metaHnd != null)
{
IDictionary<string, int> meta = metaHnd.OnObjectWriteFinished();
if (meta != null)
_parent._ctx.Writer.SaveMetadata(desc, meta);
}
}
finally
{
// Restore builder frame.
_parent._ctx.Writer.SetBuilder(oldBuilder);
inStream.Seek(streamPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Internal mutation routine.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="ctx">Context.</param>
/// <param name="changeHash">WHether hash should be changed.</param>
/// <param name="hash">New hash.</param>
/// <param name="vals">Values to be replaced.</param>
/// <returns>Mutated object.</returns>
private void Mutate0(Context ctx, BinaryHeapStream inStream, IBinaryStream outStream,
bool changeHash, int hash, IDictionary<int, BinaryBuilderField> vals)
{
int inStartPos = inStream.Position;
int outStartPos = outStream.Position;
byte inHdr = inStream.ReadByte();
if (inHdr == BinaryUtils.HdrNull)
outStream.WriteByte(BinaryUtils.HdrNull);
else if (inHdr == BinaryUtils.HdrHnd)
{
int inHnd = inStream.ReadInt();
int oldPos = inStartPos - inHnd;
int newPos;
if (ctx.OldToNew(oldPos, out newPos))
{
// Handle is still valid.
outStream.WriteByte(BinaryUtils.HdrHnd);
outStream.WriteInt(outStartPos - newPos);
}
else
{
// Handle is invalid, write full object.
int inRetPos = inStream.Position;
inStream.Seek(oldPos, SeekOrigin.Begin);
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
inStream.Seek(inRetPos, SeekOrigin.Begin);
}
}
else if (inHdr == BinaryUtils.HdrFull)
{
var inHeader = BinaryObjectHeader.Read(inStream, inStartPos);
BinaryUtils.ValidateProtocolVersion(inHeader.Version);
int hndPos;
if (ctx.AddOldToNew(inStartPos, outStartPos, out hndPos))
{
// Object could be cached in parent builder.
BinaryBuilderField cachedVal;
if (_parent._cache != null && _parent._cache.TryGetValue(inStartPos, out cachedVal))
{
WriteField(ctx, cachedVal);
}
else
{
// New object, write in full form.
var inSchema = inHeader.ReadSchema(inStream, inStartPos);
var outSchema = BinaryObjectSchemaHolder.Current;
var schemaIdx = outSchema.PushSchema();
try
{
// Skip header as it is not known at this point.
outStream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current);
if (inSchema != null)
{
foreach (var inField in inSchema)
{
BinaryBuilderField fieldVal;
var fieldFound = vals.TryGetValue(inField.Id, out fieldVal);
if (fieldFound && fieldVal == BinaryBuilderField.RmvMarker)
continue;
outSchema.PushField(inField.Id, outStream.Position - outStartPos);
if (!fieldFound)
fieldFound = _parent._cache != null &&
_parent._cache.TryGetValue(inField.Offset + inStartPos,
out fieldVal);
if (fieldFound)
{
WriteField(ctx, fieldVal);
vals.Remove(inField.Id);
}
else
{
// Field is not tracked, re-write as is.
inStream.Seek(inField.Offset + inStartPos, SeekOrigin.Begin);
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
}
}
}
// Write remaining new fields.
foreach (var valEntry in vals)
{
if (valEntry.Value == BinaryBuilderField.RmvMarker)
continue;
outSchema.PushField(valEntry.Key, outStream.Position - outStartPos);
WriteField(ctx, valEntry.Value);
}
var flags = inHeader.IsUserType
? BinaryObjectHeader.Flag.UserType
: BinaryObjectHeader.Flag.None;
// Write raw data.
int outRawOff = outStream.Position - outStartPos;
if (inHeader.HasRaw)
{
var inRawOff = inHeader.GetRawOffset(inStream, inStartPos);
var inRawLen = inHeader.SchemaOffset - inRawOff;
flags |= BinaryObjectHeader.Flag.HasRaw;
outStream.Write(inStream.InternalArray, inStartPos + inRawOff, inRawLen);
}
// Write schema
int outSchemaOff = outRawOff;
var schemaPos = outStream.Position;
int outSchemaId;
var hasSchema = outSchema.WriteSchema(outStream, schemaIdx, out outSchemaId, ref flags);
if (hasSchema)
{
outSchemaOff = schemaPos - outStartPos;
flags |= BinaryObjectHeader.Flag.HasSchema;
if (inHeader.HasRaw)
outStream.WriteInt(outRawOff);
}
var outLen = outStream.Position - outStartPos;
var outHash = changeHash ? hash : inHeader.HashCode;
var outHeader = new BinaryObjectHeader(inHeader.TypeId, outHash, outLen,
outSchemaId, outSchemaOff, flags);
BinaryObjectHeader.Write(outHeader, outStream, outStartPos);
outStream.Seek(outStartPos + outLen, SeekOrigin.Begin); // seek to the end of the object
}
finally
{
outSchema.PopSchema(schemaIdx);
}
}
}
else
{
// Object has already been written, write as handle.
outStream.WriteByte(BinaryUtils.HdrHnd);
outStream.WriteInt(outStartPos - hndPos);
}
// Synchronize input stream position.
inStream.Seek(inStartPos + inHeader.Length, SeekOrigin.Begin);
}
else
{
// Try writing as well-known type with fixed size.
outStream.WriteByte(inHdr);
if (!WriteAsPredefined(inHdr, inStream, outStream, ctx))
throw new IgniteException("Unexpected header [position=" + (inStream.Position - 1) +
", header=" + inHdr + ']');
}
}
/// <summary>
/// Writes the specified field.
/// </summary>
private static void WriteField(Context ctx, BinaryBuilderField field)
{
var action = field.WriteAction;
if (action != null)
action(ctx.Writer, field.Value);
else
ctx.Writer.Write(field.Value);
}
/// <summary>
/// Process binary object inverting handles if needed.
/// </summary>
/// <param name="outStream">Output stream.</param>
/// <param name="port">Binary object.</param>
internal void ProcessBinary(IBinaryStream outStream, BinaryObject port)
{
// Special case: writing binary object with correct inversions.
BinaryHeapStream inStream = new BinaryHeapStream(port.Data);
inStream.Seek(port.Offset, SeekOrigin.Begin);
// Use fresh context to ensure correct binary inversion.
Mutate0(new Context(), inStream, outStream, false, 0, EmptyVals);
}
/// <summary>
/// Process child builder.
/// </summary>
/// <param name="outStream">Output stream.</param>
/// <param name="builder">Builder.</param>
internal void ProcessBuilder(IBinaryStream outStream, BinaryObjectBuilder builder)
{
BinaryHeapStream inStream = new BinaryHeapStream(builder._obj.Data);
inStream.Seek(builder._obj.Offset, SeekOrigin.Begin);
// Builder parent context might be null only in one case: if we never met this group of
// builders before. In this case we set context to their parent and track it. Context
// cleanup will be performed at the very end of build process.
if (builder._parent._ctx == null || builder._parent._ctx.Closed)
builder._parent._ctx = new Context(_parent._ctx);
builder.Mutate(inStream, outStream as BinaryHeapStream, builder._desc,
builder._hashCode, builder._vals);
}
/// <summary>
/// Write object as a predefined type if possible.
/// </summary>
/// <param name="hdr">Header.</param>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="ctx">Context.</param>
/// <returns><c>True</c> if was written.</returns>
private bool WriteAsPredefined(byte hdr, BinaryHeapStream inStream, IBinaryStream outStream,
Context ctx)
{
switch (hdr)
{
case BinaryUtils.TypeByte:
TransferBytes(inStream, outStream, 1);
break;
case BinaryUtils.TypeShort:
TransferBytes(inStream, outStream, 2);
break;
case BinaryUtils.TypeInt:
TransferBytes(inStream, outStream, 4);
break;
case BinaryUtils.TypeLong:
TransferBytes(inStream, outStream, 8);
break;
case BinaryUtils.TypeFloat:
TransferBytes(inStream, outStream, 4);
break;
case BinaryUtils.TypeDouble:
TransferBytes(inStream, outStream, 8);
break;
case BinaryUtils.TypeChar:
TransferBytes(inStream, outStream, 2);
break;
case BinaryUtils.TypeBool:
TransferBytes(inStream, outStream, 1);
break;
case BinaryUtils.TypeDecimal:
TransferBytes(inStream, outStream, 4); // Transfer scale
int magLen = inStream.ReadInt(); // Transfer magnitude length.
outStream.WriteInt(magLen);
TransferBytes(inStream, outStream, magLen); // Transfer magnitude.
break;
case BinaryUtils.TypeString:
BinaryUtils.WriteString(BinaryUtils.ReadString(inStream), outStream);
break;
case BinaryUtils.TypeGuid:
TransferBytes(inStream, outStream, 16);
break;
case BinaryUtils.TypeTimestamp:
TransferBytes(inStream, outStream, 12);
break;
case BinaryUtils.TypeArrayByte:
TransferArray(inStream, outStream, 1);
break;
case BinaryUtils.TypeArrayShort:
TransferArray(inStream, outStream, 2);
break;
case BinaryUtils.TypeArrayInt:
TransferArray(inStream, outStream, 4);
break;
case BinaryUtils.TypeArrayLong:
TransferArray(inStream, outStream, 8);
break;
case BinaryUtils.TypeArrayFloat:
TransferArray(inStream, outStream, 4);
break;
case BinaryUtils.TypeArrayDouble:
TransferArray(inStream, outStream, 8);
break;
case BinaryUtils.TypeArrayChar:
TransferArray(inStream, outStream, 2);
break;
case BinaryUtils.TypeArrayBool:
TransferArray(inStream, outStream, 1);
break;
case BinaryUtils.TypeArrayDecimal:
case BinaryUtils.TypeArrayString:
case BinaryUtils.TypeArrayGuid:
case BinaryUtils.TypeArrayTimestamp:
case BinaryUtils.TypeArrayEnum:
case BinaryUtils.TypeArray:
int arrLen = inStream.ReadInt();
outStream.WriteInt(arrLen);
for (int i = 0; i < arrLen; i++)
Mutate0(ctx, inStream, outStream, false, 0, null);
break;
case BinaryUtils.TypeCollection:
int colLen = inStream.ReadInt();
outStream.WriteInt(colLen);
outStream.WriteByte(inStream.ReadByte());
for (int i = 0; i < colLen; i++)
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
break;
case BinaryUtils.TypeDictionary:
int dictLen = inStream.ReadInt();
outStream.WriteInt(dictLen);
outStream.WriteByte(inStream.ReadByte());
for (int i = 0; i < dictLen; i++)
{
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
}
break;
case BinaryUtils.TypeMapEntry:
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
Mutate0(ctx, inStream, outStream, false, 0, EmptyVals);
break;
case BinaryUtils.TypeBinary:
TransferArray(inStream, outStream, 1); // Data array.
TransferBytes(inStream, outStream, 4); // Offset in array.
break;
case BinaryUtils.TypeEnum:
TransferBytes(inStream, outStream, 4); // Integer ordinal.
break;
default:
return false;
}
return true;
}
/// <summary>
/// Transfer bytes from one stream to another.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="cnt">Bytes count.</param>
private static void TransferBytes(BinaryHeapStream inStream, IBinaryStream outStream, int cnt)
{
outStream.Write(inStream.InternalArray, inStream.Position, cnt);
inStream.Seek(cnt, SeekOrigin.Current);
}
/// <summary>
/// Transfer array of fixed-size elements from one stream to another.
/// </summary>
/// <param name="inStream">Input stream.</param>
/// <param name="outStream">Output stream.</param>
/// <param name="elemSize">Element size.</param>
private static void TransferArray(BinaryHeapStream inStream, IBinaryStream outStream,
int elemSize)
{
int len = inStream.ReadInt();
outStream.WriteInt(len);
TransferBytes(inStream, outStream, elemSize * len);
}
/// <summary>
/// Mutation ocntext.
/// </summary>
private class Context
{
/** Map from object position in old binary to position in new binary. */
private IDictionary<int, int> _oldToNew;
/** Parent context. */
private readonly Context _parent;
/** Binary writer. */
private readonly BinaryWriter _writer;
/** Children contexts. */
private ICollection<Context> _children;
/** Closed flag; if context is closed, it can no longer be used. */
private bool _closed;
/// <summary>
/// Constructor for parent context where writer invocation is not expected.
/// </summary>
public Context()
{
// No-op.
}
/// <summary>
/// Constructor for parent context.
/// </summary>
/// <param name="writer">Writer</param>
public Context(BinaryWriter writer)
{
_writer = writer;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="parent">Parent context.</param>
public Context(Context parent)
{
_parent = parent;
_writer = parent._writer;
if (parent._children == null)
parent._children = new List<Context>();
parent._children.Add(this);
}
/// <summary>
/// Add another old-to-new position mapping.
/// </summary>
/// <param name="oldPos">Old position.</param>
/// <param name="newPos">New position.</param>
/// <param name="hndPos">Handle position.</param>
/// <returns><c>True</c> if ampping was added, <c>false</c> if mapping already existed and handle
/// position in the new object is returned.</returns>
public bool AddOldToNew(int oldPos, int newPos, out int hndPos)
{
if (_oldToNew == null)
_oldToNew = new Dictionary<int, int>();
if (_oldToNew.TryGetValue(oldPos, out hndPos))
return false;
_oldToNew[oldPos] = newPos;
return true;
}
/// <summary>
/// Get mapping of old position to the new one.
/// </summary>
/// <param name="oldPos">Old position.</param>
/// <param name="newPos">New position.</param>
/// <returns><c>True</c> if mapping exists.</returns>
public bool OldToNew(int oldPos, out int newPos)
{
return _oldToNew.TryGetValue(oldPos, out newPos);
}
/// <summary>
/// Writer.
/// </summary>
public BinaryWriter Writer
{
get { return _writer; }
}
/// <summary>
/// Closed flag.
/// </summary>
public bool Closed
{
get
{
return _closed;
}
set
{
Context ctx = this;
while (ctx != null)
{
ctx._closed = value;
if (_children != null) {
foreach (Context child in _children)
child.Closed = value;
}
ctx = ctx._parent;
}
}
}
}
}
}
| |
//
// System.Web.UI.WebControls.HotSpot.cs
//
// Authors:
// Lluis Sanchez Gual (lluis@novell.com)
//
// (C) 2005 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.
//
#if NET_2_0
using System.ComponentModel;
using System.Security.Permissions;
namespace System.Web.UI.WebControls
{
[TypeConverterAttribute (typeof(ExpandableObjectConverter))]
[AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public abstract class HotSpot: IStateManager
{
StateBag viewState = new StateBag ();
[LocalizableAttribute (true)]
[DefaultValueAttribute ("")]
public virtual string AccessKey {
get {
object o = viewState ["AccessKey"];
return o != null ? (string) o : "";
}
set {
viewState ["AccessKey"] = value;
}
}
[NotifyParentPropertyAttribute (true)]
[WebCategoryAttribute ("Behavior")]
[DefaultValueAttribute ("")]
[BindableAttribute (true)]
public virtual string AlternateText {
get {
object o = viewState ["AlternateText"];
return o != null ? (string) o : "";
}
set {
viewState ["AlternateText"] = value;
}
}
[WebCategoryAttribute ("Behavior")]
[DefaultValueAttribute (HotSpotMode.NotSet)]
[NotifyParentPropertyAttribute (true)]
public virtual HotSpotMode HotSpotMode {
get {
object o = viewState ["HotSpotMode"];
return o != null ? (HotSpotMode) o : HotSpotMode.NotSet;
}
set {
viewState ["HotSpotMode"] = value;
}
}
[DefaultValueAttribute ("")]
[BindableAttribute (true)]
[EditorAttribute ("System.Web.UI.Design.UrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
[NotifyParentPropertyAttribute (true)]
[UrlPropertyAttribute]
public virtual string NavigateUrl {
get {
object o = viewState ["NavigateUrl"];
return o != null ? (string) o : "";
}
set {
viewState ["NavigateUrl"] = value;
}
}
[BindableAttribute (true)]
[WebCategoryAttribute ("Behavior")]
[DefaultValueAttribute ("")]
[NotifyParentPropertyAttribute (true)]
public virtual string PostBackValue {
get {
object o = viewState ["PostBackValue"];
return o != null ? (string) o : "";
}
set {
viewState ["PostBackValue"] = value;
}
}
[DefaultValueAttribute (0)]
[WebCategoryAttribute ("Accessibility")]
public virtual short TabIndex {
get {
object o = viewState ["TabIndex"];
return o != null ? (short) o : (short) 0;
}
set {
viewState ["TabIndex"] = value;
}
}
[WebCategoryAttribute ("Behavior")]
[NotifyParentPropertyAttribute (true)]
[DefaultValueAttribute ("")]
[TypeConverterAttribute (typeof(TargetConverter))]
public virtual string Target {
get {
object o = viewState ["Target"];
return o != null ? (string) o : "";
}
set {
viewState ["Target"] = value;
}
}
[Browsable (false)]
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
protected StateBag ViewState {
get { return viewState; }
}
protected virtual void LoadViewState (object savedState)
{
viewState.LoadViewState (savedState);
}
protected virtual object SaveViewState ()
{
return viewState.SaveViewState ();
}
protected virtual void TrackViewState ()
{
viewState.TrackViewState ();
}
protected virtual bool IsTrackingViewState
{
get { return viewState.IsTrackingViewState; }
}
void IStateManager.LoadViewState (object savedState)
{
LoadViewState (savedState);
}
object IStateManager.SaveViewState ()
{
return SaveViewState ();
}
void IStateManager.TrackViewState ()
{
TrackViewState ();
}
bool IStateManager.IsTrackingViewState
{
get { return IsTrackingViewState; }
}
public override string ToString ()
{
return GetType().Name;
}
internal void SetDirty ()
{
viewState.SetDirty ();
}
public abstract string GetCoordinates ();
protected internal abstract string MarkupName { get; }
}
}
#endif
| |
// 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;
namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdprfx
{
/// <summary>
/// The RLGR decoder
/// </summary>
public class RLGRDecoder
{
// Constants used within the RLGR1/RLGR3 algorithm
const int KPMAX = 80; // max value for kp or krp
const int LSGR = 3; // shift count to convert kp to k
const int UP_GR = 4; // increase in kp after a zero run in RL mode
const int DN_GR = 6; // decrease in kp after a nonzero symbol in RL mode
const int UQ_GR = 3; // increase in kp after nonzero symbol in GR mode
const int DQ_GR = 3; // decrease in kp after zero symbol in GR mode
List<short> decodedList;
byte[] encodedBytes = null;
//BitArray bitsToDecode = null;
int dataOffset = 0;
/// <summary>
/// ALGR decode the input data.
/// </summary>
/// <param name="encodedData">The input data to be decoded.</param>
/// <param name="rlgrMode">The RLGR mode.</param>
/// <param name="lengthToDecode">The expected decoding size.</param>
/// <returns></returns>
public short[] Decode(byte[] encodedData, EntropyAlgorithm rlgrMode, int lengthToDecode)
{
encodedBytes = encodedData;
//bitsToDecode = new BitArray(encodedData);
dataOffset = 0;
decodedList = new List<short>();
this.RLGR_Decode(rlgrMode, lengthToDecode);
return decodedList.ToArray();
}
//
// Gets (returns) the next nBits from the bitstream
// The layout of N bits in the bitstream with regard to a byte array is:
// [0..N] -> [0..7](MSB..LSB),[8..15](MSB..LSB) ...,
// where (MSB..LSB) denotes a byte.
//
uint GetBits(uint nBits)
{
uint output = 0;
int outOffset = (int)nBits - 1;
while (outOffset >= 0)
{
int bitOffset = dataOffset & 7;
int byteOffset = dataOffset >> 3;
//uint outBit = (uint)(bitsToDecode.Get(bitOffset++) ? 1:0);
uint outBit = (uint)((encodedBytes[byteOffset] & (byte)(1 << (7 - bitOffset))) == 0 ? 0 : 1);
output |= (outBit << outOffset--);
dataOffset++;
}
return output;
}
//
// From current output pointer, write "value", check and update *termsToDecode
//
void WriteValue(
int value,
ref int termsToDecode
)
{
if (termsToDecode > 0)
{
this.decodedList.Add((short)value);
termsToDecode--;
}
}
//
// From current output pointer, write next nZeroes terms with value 0;
// check and update *termsToDecode
//
void WriteZeroes(
uint nZeroes,
ref int termsToDecode
)
{
for (int i = 0; i < nZeroes && termsToDecode > 0; i++)
{
WriteValue(0, ref termsToDecode);
}
}
//
// Returns the least number of bits required to represent a given value
//
uint GetMinBits(
uint val// returns ceil(log2(val))
)
{
uint m1 = (uint)Math.Ceiling(Math.Log(val, 2));
while ((val >> (int)m1) != 0)
{
m1++;
}
return m1;
}
//
// Converts from (2 * magnitude - sign) to integer
//
int GetIntFrom2MagSign(
uint twoMs
)
{
uint sign = twoMs & 1;
int vl = (int)(twoMs + sign) / 2;
if (sign == 1) vl *= (-1); //<0
return vl;
}
//
// Update the passed parameter and clamp it to the range [0,KPMAX]
// Return the value of parameter right-shifted by LSGR
//
int UpdateParam(
ref int param, // parameter to update
int deltaP // update delta
)
{
param += deltaP;// adjust parameter
if (param > KPMAX) param = KPMAX;// max clamp
if (param < 0) param = 0;// min clamp
return (param >> LSGR);
}
//
// Outputs the Golomb/Rice encoding of a non-negative integer
//
uint GetGRCode(
ref int krp,
ref int kr
)
{
uint vk;
uint mag;
// chew up/count leading 1s and escape 0
for (vk = 0; GetBits(1) == 1; )
{
vk++;
}
// get next *kr bits, and combine with leading 1s
mag = (uint)((vk << kr) | GetBits((uint)(kr)));
// adjust kpr and kr based on vk
if (vk == 0)
{
kr = UpdateParam(ref krp, -2);
}
else if (vk != 1)// at 1, no change!
{
kr = UpdateParam(ref krp, (int)vk);
}
return (mag);
}
//
// Routine that reads and decodes stream of RLGR data
//
void RLGR_Decode(
EntropyAlgorithm rlgrMode, // RLGR1 || RLGR3
int lenToDecode
)
{
int termsToDecode = lenToDecode;
// initialize the parameters
int k = 1;
int kp = k << LSGR;
int kr = 1;
int krp = kr << LSGR;
while (termsToDecode > 0)
{
int run;
if (k != 0)
{
// RL MODE
while (GetBits(1) == 0)
{
if (termsToDecode > 0)
{
// we have an RL escape "0", which translates to a run (1<<k) of zeros
WriteZeroes((uint)(1 << k), ref termsToDecode);
k = UpdateParam(ref kp, UP_GR); // raise k and kp up because of zero run
}
else
{
break;
}
}
if (termsToDecode > 0)
{
// next k bits will contain remaining run of zeros
run = (int)GetBits((uint)k);
WriteZeroes((uint)run, ref termsToDecode);
}
if (termsToDecode > 0)
{
// get nonzero value, starting with sign bit and
// then GRCode for magnitude - 1
uint sign = GetBits(1);
// magnitude - 1 was coded (because it was nonzero)
int mag = (int)GetGRCode(ref krp, ref kr) + 1;
WriteValue(sign != 0 ? -mag : mag, ref termsToDecode);
k = UpdateParam(ref kp, -DN_GR); // lower k and kp because of nonzero term
}
}
else
{
// GR (GOLOMB-RICE) MODE
uint mag = GetGRCode(ref krp, ref kr); // values coded are 2*magnitude - sign
if (rlgrMode == EntropyAlgorithm.CLW_ENTROPY_RLGR1)
{
if (mag == 0)
{
WriteValue(0, ref termsToDecode);
k = UpdateParam(ref kp, UQ_GR); // raise k and kp due to zero
}
else
{
WriteValue(GetIntFrom2MagSign(mag), ref termsToDecode);
k = UpdateParam(ref kp, -DQ_GR); // lower k and kp due to nonzero
}
}
else // rlgrMode == RLGR3
{
// In GR mode FOR RLGR3, we have encoded the
// sum of two (2*mag - sign) values
// maximum possible bits for first term
uint nIdx = GetMinBits(mag);
// decode val1 is first term's (2*mag - sign) value
uint val1 = GetBits(nIdx);
// val2 is second term's (2*mag - sign) value
uint val2 = mag - val1;
if (val1 != 0 && val2 != 0)
{
// raise k and kp if both terms nonzero
k = UpdateParam(ref kp, -2 * DQ_GR);
}
else if (val1 == 0 && val2 == 0)
{
// lower k and kp if both terms zero
k = UpdateParam(ref kp, 2 * UQ_GR);
}
WriteValue(GetIntFrom2MagSign(val1), ref termsToDecode);
if (termsToDecode > 0)
{
WriteValue(GetIntFrom2MagSign(val2), ref termsToDecode);
}
}
}
}
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Forms;
namespace CslaContrib.Windows
{
/// <summary>
/// Add link to StatusStrip with Status and Animation.
/// <example>
/// 1) Add a StatusStrip to the form and add 2 ToolStripStatusLabels.
/// 2) Add the StatusStripExtender to the form.
/// 3) Set statusStripExtender properties on StatusStrip
/// StatusLabel to toolStripStatusLabel1
/// and AnimationLabel to toolStripStatusLabel2
/// 4) Set status text with
/// statusStripExtender1.SetStatus
/// statusStripExtender1.SetStatusStatic
/// statusStripExtender1.SetStatusWaiting
/// statusStripExtender1.SetStatusWithDuration
/// </example>
///
/// </summary>
[ProvideProperty("StatusLabel", typeof (Control))]
[ProvideProperty("AnimationLabel", typeof (Control))]
public class StatusStripExtender : Component, IExtenderProvider
{
private ToolStripStatusLabel _status;
private ToolStripStatusLabel _animation;
private string _statusDefault = "Ready";
private readonly Timer _timer;
private Timer _progressIndicatorTimer;
private int _statusDefaultDuration = 5000;
private readonly StringCollection _toolTipList;
private int _maximumToolTipLines = 5;
private object _syncRoot = new object();
#region --- Interface IExtenderProvider ----
public bool CanExtend(object extendee)
{
return extendee is StatusStrip;
}
#endregion
#region --- Extender properties ---
[Category("StatusStripExtender")]
public ToolStripStatusLabel GetStatusLabel(Control control)
{
return StatusControl;
}
[Category("StatusStripExtender")]
public void SetStatusLabel(Control control, ToolStripStatusLabel statusLabel)
{
StatusControl = statusLabel;
}
[Category("StatusStripExtender")]
public ToolStripStatusLabel GetAnimationLabel(Control control)
{
return AnimationControl;
}
[Category("StatusStripExtender")]
public void SetAnimationLabel(Control control, ToolStripStatusLabel animationLabel)
{
AnimationControl = animationLabel;
}
#endregion
#region // --- Constructor ---
/// <summary>
/// Initializes a new instance of the <see cref="StatusStripExtender"/> class.
/// </summary>
public StatusStripExtender()
{
_timer = new Timer {Enabled = false, Interval = _statusDefaultDuration};
_timer.Tick += _timer_Tick;
_toolTipList = new StringCollection();
}
#endregion
#region // --- Public properties ---
/// <summary>
/// Gets or sets the ToolStripStatusLabel for Status.
/// </summary>
/// <value>The status control.</value>
[Category("ToolStrip"), Description("Gets or sets the ToolStripStatusLabel for Status.")]
public ToolStripStatusLabel StatusControl
{
set
{
if (value == null && _status != null)
{
ReleaseStatus();
}
else
{
if (_animation == value && value != null)
{
throw new ArgumentException("StatusControl and AnimationControl can't be the same control.");
}
_status = value;
InitStatus();
}
}
get { return _status; }
}
/// <summary>
/// Gets or sets the default Status.
/// </summary>
/// <value>The status default text.</value>
[Category("StatusControl"), Description("Gets or sets the default Status.")]
[Localizable(true)]
[DefaultValue("Klar")]
public string StatusDefault
{
set
{
_statusDefault = value;
SetStatusToDefault();
}
get { return _statusDefault; }
}
/// <summary>
/// Gets or sets the maximum Tool Tip Lines to show (1-10, default 5).
/// </summary>
/// <value>The maximum number of Tool Tip Lines.</value>
[Category("StatusControl"), Description("Maximum lines to show in the ToolTip text. Valid value is 1 to 10.")]
[DefaultValue(5)]
public int MaximumToolTipLines
{
set
{
_maximumToolTipLines = value;
if (_maximumToolTipLines < 1)
{
_maximumToolTipLines = 1;
}
if (_maximumToolTipLines > 10)
{
_maximumToolTipLines = 10;
}
}
get { return _maximumToolTipLines; }
}
private void SetStatusToolTip(string text)
{
if (!DesignMode)
{
_toolTipList.Insert(0, "(" + DateTime.Now.ToLongTimeString() + ") " + text);
if (_toolTipList.Count > _maximumToolTipLines)
{
_toolTipList.RemoveAt(_maximumToolTipLines);
}
string[] toolTipArray = new string[_maximumToolTipLines];
_toolTipList.CopyTo(toolTipArray, 0);
_status.ToolTipText = string.Join("\n", toolTipArray).TrimEnd();
}
}
/// <summary>
/// Gets or sets the delay.
/// </summary>
/// <value>The delay.</value>
[Category("StatusControl"), Description("Delay in milliseconds to show the Status")]
[DefaultValue(5000)]
public int Delay
{
set
{
_statusDefaultDuration = value;
_timer.Interval = _statusDefaultDuration;
}
get { return _statusDefaultDuration; }
}
public void SetStatusToDefault()
{
UpdateStatusStrip(_statusDefault, false, false, -1);
}
#endregion
#region --- Public funtions --
#region // --- Public Animation ---
/// <summary>
/// Gets or sets the Animation control.
/// </summary>
/// <value>The animation control.</value>
[Category("ToolStrip"), Description("Gets or sets the Animation control.")]
public ToolStripStatusLabel AnimationControl
{
set
{
if (value == null && _animation != null)
{
ReleaseAnimation();
}
else
{
if (_status == value && value != null)
{
throw new ArgumentException("AnimationControl and StatusControl can't be the same control.");
}
_animation = value;
InitAnimation();
}
}
get { return _animation; }
}
/// <summary>
/// Gets or sets a value indicating whether the Animation control is visible].
/// </summary>
/// <value><c>true</c> if the Animation control is visible; otherwise, <c>false</c>.</value>
[Browsable(false)]
[ReadOnly(true)]
[DefaultValue(true)]
public bool AnimationVisible
{
set
{
if (_animation != null)
{
_animation.Visible = value;
}
}
get
{
if (_animation != null)
{
return _animation.Visible;
}
else
{
return true;
}
}
}
#endregion
/// <summary>
/// Sets the statu to defaultstatus and stop progress indicator from running.
/// </summary>
public void SetStatus()
{
SetStatus(_statusDefault);
}
/// <summary>
/// Set status message and stops the progress indicator from running
/// </summary>
/// <param name="text">The text.</param>
public void SetStatus(string text)
{
SetStatus(text, _statusDefaultDuration);
}
/// <summary>
/// Set status message and stops the progress indicator from running
/// </summary>
/// <param name="text">The text.</param>
/// <param name="durationMilliseconds">The duration milliseconds.</param>
public void SetStatus(string text, int durationMilliseconds)
{
UpdateStatusStrip(text, false, false, durationMilliseconds);
}
/// <summary>
/// Sets the Status and keep it until new text.
/// </summary>
public void SetStatusStatic()
{
SetStatusStatic(_statusDefault);
}
/// <summary>
/// Sets the Status and keep it until new text.
/// </summary>
/// <param name="text">The text.</param>
public void SetStatusStatic(string text)
{
UpdateStatusStrip(text, false, false, -1);
}
/// <summary>
/// Sets the duration of the status with.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="duration">The duration.</param>
public void SetStatusWithDuration(string text, int duration)
{
UpdateStatusStrip(text, false, false, duration);
}
/// <summary>
/// Updates the status bar with the specified message. The message is reset after a few seconds.
/// Progress indicator is NOT shown
/// </summary>
/// <param name="message">The message.</param>
/// <param name="formatParams">Formatting parameters</param>
public void SetStatusText(string message, params object[] formatParams)
{
var formattedMessage = string.Format(message, formatParams);
UpdateStatusStrip(formattedMessage, false, false, _statusDefaultDuration);
}
/// <summary>
/// Updates the status bar with the specified message. The message is not reset until "SetStatus()" is called
/// Progress indicator IS shown
/// Large IS shown
/// </summary>
/// <param name="message">The message.</param>
/// <param name="formatParams">The format params.</param>
public void SetStatusWaiting(string message, params object[] formatParams)
{
SetStatusWaiting(message, true, formatParams);
}
/// <summary>
/// Updates the status bar with the specified message. The message is not reset until "SetStatus()" is called
/// Progress indicator IS shown
/// Large progress indicator is displayed depending on "displayLargeProgressIndicator"
/// </summary>
/// <param name="message">The message.</param>
/// <param name="displayLargeProgressindicator">if set to <c>true</c> [display large progressindicator].</param>
/// <param name="formatParams">Formatting parameters</param>
public void SetStatusWaiting(string message, bool displayLargeProgressindicator, params object[] formatParams)
{
var formattedMessage = string.Format(message, formatParams);
UpdateStatusStrip(formattedMessage, true, displayLargeProgressindicator, -1);
}
/// <summary>
/// Updates the status strip.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="showProgressIndicator">if set to <c>true</c> [show progress indicator].</param>
/// <param name="showLargeProgressIndicator">if set to <c>true</c> [show large progress indicator].</param>
/// <param name="durationMilliseconds"></param>
public void UpdateStatusStrip(string message, bool showProgressIndicator, bool showLargeProgressIndicator, int durationMilliseconds)
{
//if (this..InvokeRequired)
//{
// ParentForm.Invoke(new StatusStripDelegate(UpdateStatusStrip), message, showProgressIndicator, showLargeProgressIndicator);
//}
lock (_syncRoot)
{
if (_progressIndicatorTimer != null)
_progressIndicatorTimer.Stop();
SplashPanel.Close();
if (showProgressIndicator)
{
SetStatusTextStaticPrivate(message);
if (showLargeProgressIndicator)
{
//If still waiting after 2 seconds, show a larger progressindicator
_progressIndicatorTimer = new Timer {Interval = 2000};
_progressIndicatorTimer.Tick += TimerShowBusyIndicator;
_progressIndicatorTimer.Start();
}
}
else
{
if (string.IsNullOrEmpty(message))
SetStatusToDefaultPrivate();
else
SetStatusTextPrivate(message, durationMilliseconds);
}
AnimationVisible = showProgressIndicator;
}
}
#endregion
#region Private Methods
/// <summary>
/// Sets the Status.
/// </summary>
/// <param name="text">The text.</param>
private void SetStatusTextPrivate(string text)
{
SetStatusWithDurationPrivate(text, _statusDefaultDuration);
}
/// <summary>
/// Sets the Status.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="durationMilliseconds">The duration milliseconds.</param>
private void SetStatusTextPrivate(string text, int durationMilliseconds)
{
SetStatusWithDurationPrivate(text, durationMilliseconds);
}
/// <summary>
/// Sets the Status and keep it until new text.
/// </summary>
/// <param name="text">The text.</param>
private void SetStatusTextStaticPrivate(string text)
{
SetStatusWithDurationPrivate(text, -1);
}
/// <summary>
/// Sets the Status with delay.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="durationMilliseconds">The duration in milliseconds.</param>
private void SetStatusWithDurationPrivate(string text, int durationMilliseconds)
{
_status.Text = text;
SetStatusToolTip(text);
if (durationMilliseconds < 0)
{
_timer.Enabled = false;
_timer.Interval = _statusDefaultDuration;
}
else
{
if (_timer.Enabled)
{
_timer.Enabled = false;
_timer.Interval = durationMilliseconds;
_timer.Enabled = true;
}
else
{
_timer.Enabled = true;
}
}
}
/// <summary>
/// Sets the status to Default.
/// </summary>
private void SetStatusToDefaultPrivate()
{
if (_status != null)
{
if (_status.Text != _statusDefault || _toolTipList.Count == 0)
{
_status.Text = _statusDefault;
SetStatusToolTip(_statusDefault);
}
}
}
/// <summary>
/// Hides the temporary wait indicator.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void HideTemporaryWaitIndicator(object sender, EventArgs e)
{
lock (_syncRoot)
{
var timer = sender as Timer;
if (timer != null) timer.Stop();
SplashPanel.Close();
SetStatusToDefault();
AnimationVisible = false;
}
}
/// <summary>
/// Handles the Tick event of the _progressIndicatorTimer
/// Displays a large progressindicator
/// </summary>
/// <param name="sender">The timer that triggered the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void TimerShowBusyIndicator(object sender, EventArgs e)
{
lock (_syncRoot)
{
var timer = sender as Timer;
if (timer != null) timer.Stop();
SplashPanel.Show((AnimationControl).Owner.FindForm(), StatusControl.Text);
}
}
#endregion
#region // --- Private Status ---
private void InitStatus()
{
if (_status != null)
{
SetStatusToDefault();
_status.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
_status.Spring = true;
if (DesignMode)
{
_status.Owner.ShowItemToolTips = true;
}
}
}
private void _timer_Tick(object sender, EventArgs e)
{
_timer.Enabled = false;
SetStatusToDefault();
_timer.Interval = _statusDefaultDuration;
}
private void ReleaseStatus()
{
if (_status != null)
{
_status.Text = "# Not in use #";
_status.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
_status.Spring = false;
_status = null;
}
}
#endregion
#region // --- Private Animation ---
private void InitAnimation()
{
if (_animation != null)
{
_animation.DisplayStyle = ToolStripItemDisplayStyle.Image;
_animation.ImageScaling = ToolStripItemImageScaling.None;
_animation.Image = Properties.Resources.status_anim;
if (!DesignMode)
{
_animation.Visible = false;
}
}
}
private void ReleaseAnimation()
{
if (_animation != null)
{
_animation.Image = null;
_animation.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
_animation.ImageScaling = ToolStripItemImageScaling.SizeToFit;
_animation.Text = "# Not in use #";
if (!DesignMode)
{
_animation.Visible = true;
}
_animation = null;
}
}
#endregion
} // public class StatusStripExtender
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\combStreamers.tcl
// output file is AVcombStreamers.cs
/// <summary>
/// The testing class derived from AVcombStreamers
/// </summary>
public class AVcombStreamersClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVcombStreamers(String [] argv)
{
//Prefix Content is: ""
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
// create pipeline[]
//[]
pl3d = new vtkPLOT3DReader();
pl3d.SetXYZFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combxyz.bin");
pl3d.SetQFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combq.bin");
pl3d.SetScalarFunctionNumber((int)100);
pl3d.SetVectorFunctionNumber((int)202);
pl3d.Update();
ps = new vtkPlaneSource();
ps.SetXResolution((int)4);
ps.SetYResolution((int)4);
ps.SetOrigin((double)2,(double)-2,(double)26);
ps.SetPoint1((double)2,(double)2,(double)26);
ps.SetPoint2((double)2,(double)-2,(double)32);
psMapper = vtkPolyDataMapper.New();
psMapper.SetInputConnection((vtkAlgorithmOutput)ps.GetOutputPort());
psActor = new vtkActor();
psActor.SetMapper((vtkMapper)psMapper);
psActor.GetProperty().SetRepresentationToWireframe();
rk4 = new vtkRungeKutta4();
streamer = new vtkStreamLine();
streamer.SetInputConnection((vtkAlgorithmOutput)pl3d.GetOutputPort());
streamer.SetSource((vtkDataSet)ps.GetOutput());
streamer.SetMaximumPropagationTime((double)100);
streamer.SetIntegrationStepLength((double).2);
streamer.SetStepLength((double).001);
streamer.SetNumberOfThreads((int)1);
streamer.SetIntegrationDirectionToForward();
streamer.VorticityOn();
streamer.SetIntegrator((vtkInitialValueProblemSolver)rk4);
rf = new vtkRibbonFilter();
rf.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort());
rf.SetWidth((double)0.1);
rf.SetWidthFactor((double)5);
streamMapper = vtkPolyDataMapper.New();
streamMapper.SetInputConnection((vtkAlgorithmOutput)rf.GetOutputPort());
streamMapper.SetScalarRange(
(double)((vtkDataSet)pl3d.GetOutput()).GetScalarRange()[0],
(double)((vtkDataSet)pl3d.GetOutput()).GetScalarRange()[1]);
streamline = new vtkActor();
streamline.SetMapper((vtkMapper)streamMapper);
outline = new vtkStructuredGridOutlineFilter();
outline.SetInputConnection((vtkAlgorithmOutput)pl3d.GetOutputPort());
outlineMapper = vtkPolyDataMapper.New();
outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort());
outlineActor = new vtkActor();
outlineActor.SetMapper((vtkMapper)outlineMapper);
// Add the actors to the renderer, set the background and size[]
//[]
ren1.AddActor((vtkProp)psActor);
ren1.AddActor((vtkProp)outlineActor);
ren1.AddActor((vtkProp)streamline);
ren1.SetBackground((double)1,(double)1,(double)1);
renWin.SetSize((int)300,(int)300);
ren1.SetBackground((double)0.1,(double)0.2,(double)0.4);
cam1 = ren1.GetActiveCamera();
cam1.SetClippingRange((double)3.95297,(double)50);
cam1.SetFocalPoint((double)9.71821,(double)0.458166,(double)29.3999);
cam1.SetPosition((double)2.7439,(double)-37.3196,(double)38.7167);
cam1.SetViewUp((double)-0.16123,(double)0.264271,(double)0.950876);
// render the image[]
//[]
renWin.Render();
// prevent the tk window from showing up then start the event loop[]
// for testing[]
threshold = 15;
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkPLOT3DReader pl3d;
static vtkPlaneSource ps;
static vtkPolyDataMapper psMapper;
static vtkActor psActor;
static vtkRungeKutta4 rk4;
static vtkStreamLine streamer;
static vtkRibbonFilter rf;
static vtkPolyDataMapper streamMapper;
static vtkActor streamline;
static vtkStructuredGridOutlineFilter outline;
static vtkPolyDataMapper outlineMapper;
static vtkActor outlineActor;
static vtkCamera cam1;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPLOT3DReader Getpl3d()
{
return pl3d;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setpl3d(vtkPLOT3DReader toSet)
{
pl3d = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPlaneSource Getps()
{
return ps;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setps(vtkPlaneSource toSet)
{
ps = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetpsMapper()
{
return psMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetpsMapper(vtkPolyDataMapper toSet)
{
psMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetpsActor()
{
return psActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetpsActor(vtkActor toSet)
{
psActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRungeKutta4 Getrk4()
{
return rk4;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setrk4(vtkRungeKutta4 toSet)
{
rk4 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStreamLine Getstreamer()
{
return streamer;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setstreamer(vtkStreamLine toSet)
{
streamer = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRibbonFilter Getrf()
{
return rf;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setrf(vtkRibbonFilter toSet)
{
rf = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetstreamMapper()
{
return streamMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetstreamMapper(vtkPolyDataMapper toSet)
{
streamMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getstreamline()
{
return streamline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setstreamline(vtkActor toSet)
{
streamline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkStructuredGridOutlineFilter Getoutline()
{
return outline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoutline(vtkStructuredGridOutlineFilter toSet)
{
outline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetoutlineMapper()
{
return outlineMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineMapper(vtkPolyDataMapper toSet)
{
outlineMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetoutlineActor()
{
return outlineActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineActor(vtkActor toSet)
{
outlineActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcam1()
{
return cam1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcam1(vtkCamera toSet)
{
cam1 = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(pl3d!= null){pl3d.Dispose();}
if(ps!= null){ps.Dispose();}
if(psMapper!= null){psMapper.Dispose();}
if(psActor!= null){psActor.Dispose();}
if(rk4!= null){rk4.Dispose();}
if(streamer!= null){streamer.Dispose();}
if(rf!= null){rf.Dispose();}
if(streamMapper!= null){streamMapper.Dispose();}
if(streamline!= null){streamline.Dispose();}
if(outline!= null){outline.Dispose();}
if(outlineMapper!= null){outlineMapper.Dispose();}
if(outlineActor!= null){outlineActor.Dispose();}
if(cam1!= null){cam1.Dispose();}
}
}
//--- end of script --//
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Foundation.Build.MSBuild.VisualBasic6
{
public class Vb6ProjectItems : Task
{
private IList<ITaskItem> classes;
private IList<ITaskItem> components;
private IList<ITaskItem> forms;
private IList<ITaskItem> modules;
private IList<ITaskItem> references;
/// <summary>
/// Gets or sets the Visual Basic 6 project file.
/// </summary>
/// <value>
/// The Visual Basic 6 project file.
/// </value>
[Required]
public ITaskItem Project { get; set; }
/// <summary>
/// Gets or sets the modules.
/// </summary>
/// <value>
/// The modules.
/// </value>
[Output]
public ITaskItem[] Modules
{
get { return modules.ToArray(); }
set { modules = value; }
}
[Output]
public ITaskItem[] Classes
{
get { return classes.ToArray(); }
set { classes = value; }
}
[Output]
public ITaskItem[] Forms
{
get { return forms.ToArray(); }
set { forms = value; }
}
[Output]
public ITaskItem ResourceFile { get; set; }
[Output]
public string OutputType { get; set; }
[Output]
public ITaskItem[] References
{
get { return references.ToArray(); }
set { references = value; }
}
[Output]
public ITaskItem[] Components
{
get { return components.ToArray(); }
set { components = value; }
}
public ITaskItem Compatibility { get; set; }
public override bool Execute()
{
var projectFile = new FileInfo(Project.GetMetadata("FullPath"));
if (!projectFile.Exists)
{
throw new FileNotFoundException("Couldn't find project file", projectFile.FullName);
}
modules = new List<ITaskItem>();
classes = new List<ITaskItem>();
forms = new List<ITaskItem>();
references = new List<ITaskItem>();
components = new List<ITaskItem>();
string startup = null;
string iconForm = null;
string compatibilityMode = null;
// Get all the assignment lines in the project file (ignoring blank lines and section headers)
var projectLines = File.ReadAllLines(projectFile.FullName)
.Where(line => line.Contains("="));
foreach (var line in projectLines)
{
// Split the key and value
string[] keyAndValue = line.Split(new[] {"="}, StringSplitOptions.RemoveEmptyEntries);
Debug.Assert(keyAndValue.Length == 2, "Key and value not split correctly", "Project line: {0}", line);
string key = keyAndValue[0].ToLower(CultureInfo.InvariantCulture);
string value = keyAndValue[1].Replace("\"", "").Trim();
switch (key)
{
case "Type":
OutputType = value;
break;
case "Reference":
references.Add(ParseReference(value));
break;
case "Object":
components.Add(ParseReference(value));
break;
case "Class":
classes.Add(ParseSourceFile(value));
break;
case "Module":
modules.Add(ParseSourceFile(value));
break;
case "Form":
modules.Add(ParseSourceFile(value));
break;
case "ResFile32":
ResourceFile = new TaskItem(value);
break;
case "CompatibleMode":
compatibilityMode = value;
break;
case "CompatibleEXE32":
Compatibility = new TaskItem(value);
break;
case "Startup":
startup = value;
break;
case "IconForm":
iconForm = value;
break;
}
}
// Was there a startup form set?
if (!string.IsNullOrWhiteSpace(startup))
{
ITaskItem form = FindForm(startup);
if (form != null) form.SetMetadata("Startup", "true");
}
// Was there an icon form set?
if (!string.IsNullOrWhiteSpace(iconForm))
{
ITaskItem form = FindForm(startup);
if (form != null) form.SetMetadata("Icon", "true");
}
// Set the compatibility mode if specified
if (Compatibility != null && !string.IsNullOrWhiteSpace(compatibilityMode))
{
Compatibility.SetMetadata("Mode", compatibilityMode);
}
return true;
}
private ITaskItem FindForm(string name)
{
return forms.SingleOrDefault(
taskItem => taskItem.GetMetadata("Identity")
.Equals(name, StringComparison.OrdinalIgnoreCase));
}
private static ITaskItem ParseSourceFile(string value)
{
string[] parts = GetReferenceParts(value).ToArray();
// If there's more than one part, we have an
// alias to go with the filename.
string alias = parts.Length > 1 ? parts[0] : null;
string filename = alias == null ? parts[0] : parts[1];
var taskItem = new TaskItem(filename);
if (!string.IsNullOrWhiteSpace(alias)) taskItem.SetMetadata("Alias", alias);
return taskItem;
}
private static ITaskItem ParseReference(string value)
{
VisualBasicReference reference = GetReference(value);
var taskItem = new TaskItem(reference.Filename);
taskItem.SetMetadata("Guid", reference.Guid.ToString());
taskItem.SetMetadata("Version", reference.Version);
if (!string.IsNullOrWhiteSpace(reference.Description))
{
taskItem.SetMetadata("Description", reference.Description);
}
return taskItem;
}
private static VisualBasicReference GetReference(string reference)
{
// Split the reference into its parts, delimited by #
// 0 = GUID
// 1 = Version
// 2 = Not sure. Usually 0 and doesn't seem to mean anything.
// 3 = Path and filename
// 4 = Name (optional)
string[] parts = GetReferenceParts(reference).ToArray();
var guid = new Guid(parts[0]);
string version = parts[1];
string filename = parts[2];
string description = parts.Length > 4 ? parts[4] : null;
return new VisualBasicReference(guid, version, filename, description);
}
private static IEnumerable<string> GetReferenceParts(string reference)
{
return reference.Trim()
.Split(new[] {'#', ';'}, StringSplitOptions.None)
.Select(s => s.Trim())
.ToArray();
}
}
}
| |
/*
* 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>
/// SmartSectionCollapsibleDisplaySettings
/// </summary>
[DataContract]
public partial class SmartSectionCollapsibleDisplaySettings : IEquatable<SmartSectionCollapsibleDisplaySettings>, IValidatableObject
{
public SmartSectionCollapsibleDisplaySettings()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="SmartSectionCollapsibleDisplaySettings" /> class.
/// </summary>
/// <param name="ArrowClosed">ArrowClosed.</param>
/// <param name="ArrowColor">ArrowColor.</param>
/// <param name="ArrowLocation">ArrowLocation.</param>
/// <param name="ArrowOpen">ArrowOpen.</param>
/// <param name="ArrowSize">ArrowSize.</param>
/// <param name="ArrowStyle">ArrowStyle.</param>
/// <param name="ContainerStyle">ContainerStyle.</param>
/// <param name="LabelStyle">LabelStyle.</param>
/// <param name="OnlyArrowIsClickable">OnlyArrowIsClickable.</param>
/// <param name="OuterLabelAndArrowStyle">OuterLabelAndArrowStyle.</param>
public SmartSectionCollapsibleDisplaySettings(string ArrowClosed = default(string), string ArrowColor = default(string), string ArrowLocation = default(string), string ArrowOpen = default(string), string ArrowSize = default(string), string ArrowStyle = default(string), string ContainerStyle = default(string), string LabelStyle = default(string), bool? OnlyArrowIsClickable = default(bool?), string OuterLabelAndArrowStyle = default(string))
{
this.ArrowClosed = ArrowClosed;
this.ArrowColor = ArrowColor;
this.ArrowLocation = ArrowLocation;
this.ArrowOpen = ArrowOpen;
this.ArrowSize = ArrowSize;
this.ArrowStyle = ArrowStyle;
this.ContainerStyle = ContainerStyle;
this.LabelStyle = LabelStyle;
this.OnlyArrowIsClickable = OnlyArrowIsClickable;
this.OuterLabelAndArrowStyle = OuterLabelAndArrowStyle;
}
/// <summary>
/// Gets or Sets ArrowClosed
/// </summary>
[DataMember(Name="arrowClosed", EmitDefaultValue=false)]
public string ArrowClosed { get; set; }
/// <summary>
/// Gets or Sets ArrowColor
/// </summary>
[DataMember(Name="arrowColor", EmitDefaultValue=false)]
public string ArrowColor { get; set; }
/// <summary>
/// Gets or Sets ArrowLocation
/// </summary>
[DataMember(Name="arrowLocation", EmitDefaultValue=false)]
public string ArrowLocation { get; set; }
/// <summary>
/// Gets or Sets ArrowOpen
/// </summary>
[DataMember(Name="arrowOpen", EmitDefaultValue=false)]
public string ArrowOpen { get; set; }
/// <summary>
/// Gets or Sets ArrowSize
/// </summary>
[DataMember(Name="arrowSize", EmitDefaultValue=false)]
public string ArrowSize { get; set; }
/// <summary>
/// Gets or Sets ArrowStyle
/// </summary>
[DataMember(Name="arrowStyle", EmitDefaultValue=false)]
public string ArrowStyle { get; set; }
/// <summary>
/// Gets or Sets ContainerStyle
/// </summary>
[DataMember(Name="containerStyle", EmitDefaultValue=false)]
public string ContainerStyle { get; set; }
/// <summary>
/// Gets or Sets LabelStyle
/// </summary>
[DataMember(Name="labelStyle", EmitDefaultValue=false)]
public string LabelStyle { get; set; }
/// <summary>
/// Gets or Sets OnlyArrowIsClickable
/// </summary>
[DataMember(Name="onlyArrowIsClickable", EmitDefaultValue=false)]
public bool? OnlyArrowIsClickable { get; set; }
/// <summary>
/// Gets or Sets OuterLabelAndArrowStyle
/// </summary>
[DataMember(Name="outerLabelAndArrowStyle", EmitDefaultValue=false)]
public string OuterLabelAndArrowStyle { 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 SmartSectionCollapsibleDisplaySettings {\n");
sb.Append(" ArrowClosed: ").Append(ArrowClosed).Append("\n");
sb.Append(" ArrowColor: ").Append(ArrowColor).Append("\n");
sb.Append(" ArrowLocation: ").Append(ArrowLocation).Append("\n");
sb.Append(" ArrowOpen: ").Append(ArrowOpen).Append("\n");
sb.Append(" ArrowSize: ").Append(ArrowSize).Append("\n");
sb.Append(" ArrowStyle: ").Append(ArrowStyle).Append("\n");
sb.Append(" ContainerStyle: ").Append(ContainerStyle).Append("\n");
sb.Append(" LabelStyle: ").Append(LabelStyle).Append("\n");
sb.Append(" OnlyArrowIsClickable: ").Append(OnlyArrowIsClickable).Append("\n");
sb.Append(" OuterLabelAndArrowStyle: ").Append(OuterLabelAndArrowStyle).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 SmartSectionCollapsibleDisplaySettings);
}
/// <summary>
/// Returns true if SmartSectionCollapsibleDisplaySettings instances are equal
/// </summary>
/// <param name="other">Instance of SmartSectionCollapsibleDisplaySettings to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SmartSectionCollapsibleDisplaySettings other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ArrowClosed == other.ArrowClosed ||
this.ArrowClosed != null &&
this.ArrowClosed.Equals(other.ArrowClosed)
) &&
(
this.ArrowColor == other.ArrowColor ||
this.ArrowColor != null &&
this.ArrowColor.Equals(other.ArrowColor)
) &&
(
this.ArrowLocation == other.ArrowLocation ||
this.ArrowLocation != null &&
this.ArrowLocation.Equals(other.ArrowLocation)
) &&
(
this.ArrowOpen == other.ArrowOpen ||
this.ArrowOpen != null &&
this.ArrowOpen.Equals(other.ArrowOpen)
) &&
(
this.ArrowSize == other.ArrowSize ||
this.ArrowSize != null &&
this.ArrowSize.Equals(other.ArrowSize)
) &&
(
this.ArrowStyle == other.ArrowStyle ||
this.ArrowStyle != null &&
this.ArrowStyle.Equals(other.ArrowStyle)
) &&
(
this.ContainerStyle == other.ContainerStyle ||
this.ContainerStyle != null &&
this.ContainerStyle.Equals(other.ContainerStyle)
) &&
(
this.LabelStyle == other.LabelStyle ||
this.LabelStyle != null &&
this.LabelStyle.Equals(other.LabelStyle)
) &&
(
this.OnlyArrowIsClickable == other.OnlyArrowIsClickable ||
this.OnlyArrowIsClickable != null &&
this.OnlyArrowIsClickable.Equals(other.OnlyArrowIsClickable)
) &&
(
this.OuterLabelAndArrowStyle == other.OuterLabelAndArrowStyle ||
this.OuterLabelAndArrowStyle != null &&
this.OuterLabelAndArrowStyle.Equals(other.OuterLabelAndArrowStyle)
);
}
/// <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.ArrowClosed != null)
hash = hash * 59 + this.ArrowClosed.GetHashCode();
if (this.ArrowColor != null)
hash = hash * 59 + this.ArrowColor.GetHashCode();
if (this.ArrowLocation != null)
hash = hash * 59 + this.ArrowLocation.GetHashCode();
if (this.ArrowOpen != null)
hash = hash * 59 + this.ArrowOpen.GetHashCode();
if (this.ArrowSize != null)
hash = hash * 59 + this.ArrowSize.GetHashCode();
if (this.ArrowStyle != null)
hash = hash * 59 + this.ArrowStyle.GetHashCode();
if (this.ContainerStyle != null)
hash = hash * 59 + this.ContainerStyle.GetHashCode();
if (this.LabelStyle != null)
hash = hash * 59 + this.LabelStyle.GetHashCode();
if (this.OnlyArrowIsClickable != null)
hash = hash * 59 + this.OnlyArrowIsClickable.GetHashCode();
if (this.OuterLabelAndArrowStyle != null)
hash = hash * 59 + this.OuterLabelAndArrowStyle.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using Android.App;
using Android.Content;
using Android.Database;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Interop;
using eidssdroid.model.Database;
using eidss.model.Enums;
using bv.model.Helpers;
namespace eidssdroid.Model
{
public enum HumanCaseStatus
{
NEW = 1,
SYNCHRONIZED = 2,
CHANGED = 3
}
public class HumanCase : Java.Lang.Object, IParcelable
{
public Int64 id { get; set; }
public String strLastSynError { get; set; }
public Int32 intStatus { get; set; } // 1 - new; 2 - synchronized; 3 - changed;
public DateTime datCreateDate { get; set; }
public String uidOfflineCaseID { get; set; }
public String strCaseID { get; set; }
public Int64 idfCase { get; set; }
private string _strLocalIdentifier;
public String strLocalIdentifier { get { return _strLocalIdentifier; } set { bChanged = bChanged || _strLocalIdentifier != value; _strLocalIdentifier = value; } }
private long _idfsTentativeDiagnosis;
public Int64 idfsTentativeDiagnosis { get { return _idfsTentativeDiagnosis; } set { bChanged = bChanged || _idfsTentativeDiagnosis != value; _idfsTentativeDiagnosis = value; } }
private DateTime _datTentativeDiagnosisDate;
public DateTime datTentativeDiagnosisDate { get { return _datTentativeDiagnosisDate; } set { bChanged = bChanged || _datTentativeDiagnosisDate != value; _datTentativeDiagnosisDate = value; } }
private string _strFamilyName;
public String strFamilyName { get { return _strFamilyName; } set { bChanged = bChanged || _strFamilyName != value; _strFamilyName = value; } }
private string _strFirstName;
public String strFirstName { get { return _strFirstName; } set { bChanged = bChanged || _strFirstName != value; _strFirstName = value; } }
private DateTime _datDateofBirth;
public DateTime datDateofBirth { get { return _datDateofBirth; } set { bChanged = bChanged || _datDateofBirth != value; _datDateofBirth = value; } }
private int _intPatientAge;
public Int32 intPatientAge { get { return _intPatientAge; } set { bChanged = bChanged || _intPatientAge != value; _intPatientAge = value; } }
private long _idfsHumanAgeType;
public Int64 idfsHumanAgeType { get { return _idfsHumanAgeType; } set { bChanged = bChanged || _idfsHumanAgeType != value; _idfsHumanAgeType = value; } }
private long _idfsHumanGender;
public Int64 idfsHumanGender { get { return _idfsHumanGender; } set { bChanged = bChanged || _idfsHumanGender != value; _idfsHumanGender = value; } }
private long _idfsRegionCurrentResidence;
public Int64 idfsRegionCurrentResidence { get { return _idfsRegionCurrentResidence; } set { bChanged = bChanged || _idfsRegionCurrentResidence != value; _idfsRegionCurrentResidence = value; } }
private long _idfsRayonCurrentResidence;
public Int64 idfsRayonCurrentResidence { get { return _idfsRayonCurrentResidence; } set { bChanged = bChanged || _idfsRayonCurrentResidence != value; _idfsRayonCurrentResidence = value; } }
private long _idfsSettlementCurrentResidence;
public Int64 idfsSettlementCurrentResidence { get { return _idfsSettlementCurrentResidence; } set { bChanged = bChanged || _idfsSettlementCurrentResidence != value; _idfsSettlementCurrentResidence = value; } }
private string _strBuilding;
public String strBuilding { get { return _strBuilding; } set { bChanged = bChanged || _strBuilding != value; _strBuilding = value; } }
private string _strHouse;
public String strHouse { get { return _strHouse; } set { bChanged = bChanged || _strHouse != value; _strHouse = value; } }
private string _strApartment;
public String strApartment { get { return _strApartment; } set { bChanged = bChanged || _strApartment != value; _strApartment = value; } }
private string _strStreetName;
public String strStreetName { get { return _strStreetName; } set { bChanged = bChanged || _strStreetName != value; _strStreetName = value; } }
private string _strPostCode;
public String strPostCode { get { return _strPostCode; } set { bChanged = bChanged || _strPostCode != value; _strPostCode = value; } }
private string _strHomePhone;
public String strHomePhone { get { return _strHomePhone; } set { bChanged = bChanged || _strHomePhone != value; _strHomePhone = value; } }
private DateTime _datOnSetDate;
public DateTime datOnSetDate { get { return _datOnSetDate; } set { bChanged = bChanged || _datOnSetDate != value; _datOnSetDate = value; } }
private long _idfsFinalState;
public Int64 idfsFinalState { get { return _idfsFinalState; } set { bChanged = bChanged || _idfsFinalState != value; _idfsFinalState = value; } }
private long _idfsHospitalizationStatus;
public Int64 idfsHospitalizationStatus { get { return _idfsHospitalizationStatus; } set { bChanged = bChanged || _idfsHospitalizationStatus != value; _idfsHospitalizationStatus = value; } }
public DateTime datNotificationDate { get; set; }
public String strSentByOffice { get; set; }
public String strSentByPerson { get; set; }
public bool bChanged { get; set; }
public String TentativeDiagnosis(EidssDatabase db)
{
var r =
db.Reference((long)BaseReferenceType.rftDiagnosis, db.CurrentLanguage, 2)
.SingleOrDefault(c => c.idfsBaseReference == idfsTentativeDiagnosis);
if (r != null) return r.name;
return "";
}
//public bool checkd { get; set; }
private HumanCase()
{
}
public static HumanCase CreateNew()
{
return new HumanCase()
{
intStatus = (int)HumanCaseStatus.NEW,
uidOfflineCaseID = Guid.NewGuid().ToString(),
strCaseID = "(new)",
datCreateDate = DateTime.Now,
bChanged = true
};
}
#region Age
private DateTime datD
{
get { return new Func<HumanCase, DateTime>(c => c.datOnSetDate > DateTime.MinValue ? c.datOnSetDate : (c.datNotificationDate > DateTime.MinValue ? c.datNotificationDate : c.datCreateDate.Date))(this); }
}
public int CalcPatientAge()
{
int _intPatientAge = 0;
long _idfsHumanAgeType = 0;
if (GetDOBandAge(ref _intPatientAge, ref _idfsHumanAgeType))
return _intPatientAge;
return this.intPatientAge;
}
public long CalcPatientAgeType()
{
int _intPatientAge = 0;
long _idfsHumanAgeType = 0;
if (GetDOBandAge(ref _intPatientAge, ref _idfsHumanAgeType))
return _idfsHumanAgeType;
return this.idfsHumanAgeType;
}
private bool GetDOBandAge(ref int _intPatientAge, ref long _idfsHumanAgeType)
{
double ddAge = -1;
DateTime? datUp = null;
if (this.datDateofBirth > DateTime.MinValue && this.datD > DateTime.MinValue)
{
datUp = this.datD;
ddAge = -this.datDateofBirth.Date.Subtract(this.datD.Date).TotalDays;
if (ddAge > -1)
{
long yyAge = DateHelper.DateDifference(DateInterval.Year, this.datDateofBirth.Date, datUp.Value);
if (yyAge > 0)
{
//'Years
_intPatientAge = (int)yyAge;
_idfsHumanAgeType = (long)HumanAgeTypeEnum.Years;
return true;
}
else
{
long mmAge = DateHelper.DateDifference(DateInterval.Month, this.datDateofBirth.Date, datUp.Value);
if (mmAge > 0)
{
//'Months
_intPatientAge = (int)mmAge;
_idfsHumanAgeType = (long)HumanAgeTypeEnum.Month;
return true;
}
else
{
//'Days
_intPatientAge = (int)ddAge;
_idfsHumanAgeType = (long)HumanAgeTypeEnum.Days;
return true;
}
}
}
}
return false;
}
#endregion
#region FromCursor
public static HumanCase FromCursor(ICursor cursor)
{
return new HumanCase()
{
id = cursor.GetLong(cursor.GetColumnIndex("id")),
strLastSynError = cursor.GetString(cursor.GetColumnIndex("strLastSynError")),
intStatus = cursor.GetInt(cursor.GetColumnIndex("intStatus")),
datCreateDate = DateTime.ParseExact(
cursor.GetString(cursor.GetColumnIndex("datCreateDate")).Length < 21 ? "00010101 00:00:00.000" :
cursor.GetString(cursor.GetColumnIndex("datCreateDate")),
"yyyyMMdd HH:mm:ss.fff", null),
uidOfflineCaseID = cursor.GetString(cursor.GetColumnIndex("uidOfflineCaseID")),
strCaseID = cursor.GetString(cursor.GetColumnIndex("strCaseID")),
idfCase = cursor.GetLong(cursor.GetColumnIndex("idfCase")),
strLocalIdentifier = cursor.GetString(cursor.GetColumnIndex("strLocalIdentifier")),
idfsTentativeDiagnosis = cursor.GetLong(cursor.GetColumnIndex("idfsTentativeDiagnosis")),
datTentativeDiagnosisDate = DateTime.ParseExact(
cursor.GetString(cursor.GetColumnIndex("datTentativeDiagnosisDate")).Length < 8 ? "00010101" :
cursor.GetString(cursor.GetColumnIndex("datTentativeDiagnosisDate")),
"yyyyMMdd", null),
strFamilyName = cursor.GetString(cursor.GetColumnIndex("strFamilyName")),
strFirstName = cursor.GetString(cursor.GetColumnIndex("strFirstName")),
datDateofBirth = DateTime.ParseExact(
cursor.GetString(cursor.GetColumnIndex("datDateofBirth")).Length < 8 ? "00010101" :
cursor.GetString(cursor.GetColumnIndex("datDateofBirth")),
"yyyyMMdd", null),
intPatientAge = cursor.GetInt(cursor.GetColumnIndex("intPatientAge")),
idfsHumanAgeType = cursor.GetLong(cursor.GetColumnIndex("idfsHumanAgeType")),
idfsHumanGender = cursor.GetLong(cursor.GetColumnIndex("idfsHumanGender")),
idfsRegionCurrentResidence = cursor.GetLong(cursor.GetColumnIndex("idfsRegionCurrentResidence")),
idfsRayonCurrentResidence = cursor.GetLong(cursor.GetColumnIndex("idfsRayonCurrentResidence")),
idfsSettlementCurrentResidence = cursor.GetLong(cursor.GetColumnIndex("idfsSettlementCurrentResidence")),
strBuilding = cursor.GetString(cursor.GetColumnIndex("strBuilding")),
strHouse = cursor.GetString(cursor.GetColumnIndex("strHouse")),
strApartment = cursor.GetString(cursor.GetColumnIndex("strApartment")),
strStreetName = cursor.GetString(cursor.GetColumnIndex("strStreetName")),
strPostCode = cursor.GetString(cursor.GetColumnIndex("strPostCode")),
strHomePhone = cursor.GetString(cursor.GetColumnIndex("strHomePhone")),
datOnSetDate = DateTime.ParseExact(
cursor.GetString(cursor.GetColumnIndex("datOnSetDate")).Length < 8 ? "00010101" :
cursor.GetString(cursor.GetColumnIndex("datOnSetDate")),
"yyyyMMdd", null),
idfsFinalState = cursor.GetLong(cursor.GetColumnIndex("idfsFinalState")),
idfsHospitalizationStatus = cursor.GetLong(cursor.GetColumnIndex("idfsHospitalizationStatus")),
datNotificationDate = DateTime.ParseExact(
cursor.GetString(cursor.GetColumnIndex("datNotificationDate")).Length < 8 ? "00010101" :
cursor.GetString(cursor.GetColumnIndex("datNotificationDate")),
"yyyyMMdd", null),
strSentByOffice = cursor.GetString(cursor.GetColumnIndex("strSentByOffice")),
strSentByPerson = cursor.GetString(cursor.GetColumnIndex("strSentByPerson")),
bChanged = false
};
}
#endregion
#region ContentValues
public ContentValues ContentValues()
{
var ret = new ContentValues();
if (id != 0)
ret.Put("id", id);
ret.Put("strLastSynError", strLastSynError);
ret.Put("intStatus", intStatus);
ret.Put("datCreateDate", datCreateDate.ToString("yyyyMMdd HH:mm:ss.fff"));
ret.Put("uidOfflineCaseID", uidOfflineCaseID);
ret.Put("strCaseID", strCaseID);
ret.Put("idfCase", idfCase);
ret.Put("strLocalIdentifier", strLocalIdentifier);
ret.Put("idfsTentativeDiagnosis", idfsTentativeDiagnosis);
ret.Put("datTentativeDiagnosisDate", datTentativeDiagnosisDate.ToString("yyyyMMdd"));
ret.Put("strFamilyName", strFamilyName);
ret.Put("strFirstName", strFirstName);
ret.Put("datDateofBirth", datDateofBirth.ToString("yyyyMMdd"));
ret.Put("intPatientAge", intPatientAge);
ret.Put("idfsHumanAgeType", idfsHumanAgeType);
ret.Put("idfsHumanGender", idfsHumanGender);
ret.Put("idfsRegionCurrentResidence", idfsRegionCurrentResidence);
ret.Put("idfsRayonCurrentResidence", idfsRayonCurrentResidence);
ret.Put("idfsSettlementCurrentResidence", idfsSettlementCurrentResidence);
ret.Put("strBuilding", strBuilding);
ret.Put("strHouse", strHouse);
ret.Put("strApartment", strApartment);
ret.Put("strStreetName", strStreetName);
ret.Put("strPostCode", strPostCode);
ret.Put("strHomePhone", strHomePhone);
ret.Put("datOnSetDate", datOnSetDate.ToString("yyyyMMdd"));
ret.Put("idfsFinalState", idfsFinalState);
ret.Put("idfsHospitalizationStatus", idfsHospitalizationStatus);
ret.Put("datNotificationDate", datNotificationDate.ToString("yyyyMMdd"));
ret.Put("strSentByOffice", strSentByOffice);
ret.Put("strSentByPerson", strSentByPerson);
return ret;
}
#endregion
#region IParcelable
public class HumanCaseCreator : Java.Lang.Object, IParcelableCreator
{
public Java.Lang.Object CreateFromParcel(Parcel source)
{
return new HumanCase()
{
id = source.ReadLong(),
strLastSynError = source.ReadString(),
intStatus = source.ReadInt(),
datCreateDate = new DateTime(source.ReadInt(), source.ReadInt(), source.ReadInt(), source.ReadInt(), source.ReadInt(), source.ReadInt(), source.ReadInt()),
uidOfflineCaseID = source.ReadString(),
strCaseID = source.ReadString(),
idfCase = source.ReadLong(),
strLocalIdentifier = source.ReadString(),
idfsTentativeDiagnosis = source.ReadLong(),
datTentativeDiagnosisDate = new DateTime(source.ReadInt(), source.ReadInt(), source.ReadInt()),
strFamilyName = source.ReadString(),
strFirstName = source.ReadString(),
datDateofBirth = new DateTime(source.ReadInt(), source.ReadInt(), source.ReadInt()),
intPatientAge = source.ReadInt(),
idfsHumanAgeType = source.ReadLong(),
idfsHumanGender = source.ReadLong(),
idfsRegionCurrentResidence = source.ReadLong(),
idfsRayonCurrentResidence = source.ReadLong(),
idfsSettlementCurrentResidence = source.ReadLong(),
strBuilding = source.ReadString(),
strHouse = source.ReadString(),
strApartment = source.ReadString(),
strStreetName = source.ReadString(),
strPostCode = source.ReadString(),
strHomePhone = source.ReadString(),
datOnSetDate = new DateTime(source.ReadInt(), source.ReadInt(), source.ReadInt()),
idfsFinalState = source.ReadLong(),
idfsHospitalizationStatus = source.ReadLong(),
datNotificationDate = new DateTime(source.ReadInt(), source.ReadInt(), source.ReadInt()),
strSentByOffice = source.ReadString(),
strSentByPerson = source.ReadString(),
bChanged = false
};
}
public Java.Lang.Object[] NewArray(int size)
{
throw new NotImplementedException();
}
}
[ExportField("CREATOR")]
public static IParcelableCreator CREATOR()
{
return _CREATOR;
}
private static IParcelableCreator _CREATOR = new HumanCaseCreator();
public int DescribeContents()
{
return 4;
}
public void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
{
dest.WriteLong(id);
dest.WriteString(strLastSynError);
dest.WriteInt(intStatus);
dest.WriteInt(datCreateDate.Year);
dest.WriteInt(datCreateDate.Month);
dest.WriteInt(datCreateDate.Day);
dest.WriteInt(datCreateDate.Hour);
dest.WriteInt(datCreateDate.Minute);
dest.WriteInt(datCreateDate.Second);
dest.WriteInt(datCreateDate.Millisecond);
dest.WriteString(uidOfflineCaseID);
dest.WriteString(strCaseID);
dest.WriteLong(idfCase);
dest.WriteString(strLocalIdentifier);
dest.WriteLong(idfsTentativeDiagnosis);
dest.WriteInt(datTentativeDiagnosisDate.Year);
dest.WriteInt(datTentativeDiagnosisDate.Month);
dest.WriteInt(datTentativeDiagnosisDate.Day);
dest.WriteString(strFamilyName);
dest.WriteString(strFirstName);
dest.WriteInt(datDateofBirth.Year);
dest.WriteInt(datDateofBirth.Month);
dest.WriteInt(datDateofBirth.Day);
dest.WriteInt(intPatientAge);
dest.WriteLong(idfsHumanAgeType);
dest.WriteLong(idfsHumanGender);
dest.WriteLong(idfsRegionCurrentResidence);
dest.WriteLong(idfsRayonCurrentResidence);
dest.WriteLong(idfsSettlementCurrentResidence);
dest.WriteString(strBuilding);
dest.WriteString(strHouse);
dest.WriteString(strApartment);
dest.WriteString(strStreetName);
dest.WriteString(strPostCode);
dest.WriteString(strHomePhone);
dest.WriteInt(datOnSetDate.Year);
dest.WriteInt(datOnSetDate.Month);
dest.WriteInt(datOnSetDate.Day);
dest.WriteLong(idfsFinalState);
dest.WriteLong(idfsHospitalizationStatus);
dest.WriteInt(datNotificationDate.Year);
dest.WriteInt(datNotificationDate.Month);
dest.WriteInt(datNotificationDate.Day);
dest.WriteString(strSentByOffice);
dest.WriteString(strSentByPerson);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
namespace System.Xml
{
// Represents an attribute of the XMLElement object. Valid and default
// values for the attribute are defined in a DTD or schema.
public class XmlAttribute : XmlNode
{
private XmlName _name;
private XmlLinkedNode _lastChild;
internal XmlAttribute(XmlName name, XmlDocument doc) : base(doc)
{
Debug.Assert(name != null);
Debug.Assert(doc != null);
this.parentNode = null;
if (!doc.IsLoading)
{
XmlDocument.CheckName(name.Prefix);
XmlDocument.CheckName(name.LocalName);
}
if (name.LocalName.Length == 0)
throw new ArgumentException(SR.Xdom_Attr_Name);
_name = name;
}
internal int LocalNameHash
{
get { return _name.HashCode; }
}
protected internal XmlAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc)
: this(doc.AddAttrXmlName(prefix, localName, namespaceURI), doc)
{
}
internal XmlName XmlName
{
get { return _name; }
}
// Creates a duplicate of this node.
public override XmlNode CloneNode(bool deep)
{
// CloneNode for attributes is deep irrespective of parameter 'deep' value
Debug.Assert(OwnerDocument != null);
XmlDocument doc = OwnerDocument;
XmlAttribute attr = doc.CreateAttribute(Prefix, LocalName, NamespaceURI);
attr.CopyChildren(doc, this, true);
return attr;
}
// Gets the parent of this node (for nodes that can have parents).
public override XmlNode ParentNode
{
get { return null; }
}
// Gets the name of the node.
public override String Name
{
get { return _name.Name; }
}
// Gets the name of the node without the namespace prefix.
public override String LocalName
{
get { return _name.LocalName; }
}
// Gets the namespace URI of this node.
public override String NamespaceURI
{
get { return _name.NamespaceURI; }
}
// Gets or sets the namespace prefix of this node.
public override String Prefix
{
get { return _name.Prefix; }
set { _name = _name.OwnerDocument.AddAttrXmlName(value, LocalName, NamespaceURI); }
}
// Gets the type of the current node.
public override XmlNodeType NodeType
{
get { return XmlNodeType.Attribute; }
}
// Gets the XmlDocument that contains this node.
public override XmlDocument OwnerDocument
{
get
{
return _name.OwnerDocument;
}
}
// Gets or sets the value of the node.
public override String Value
{
get { return InnerText; }
set { InnerText = value; } //use InnerText which has perf optimization
}
public override String InnerText
{
set
{
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = base.InnerText;
base.InnerText = value;
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
base.InnerText = value;
}
}
}
// This function returns false because it is implication of removing schema.
// If removed more methods would have to be removed as well and it would make adding schema back much harder.
internal bool PrepareOwnerElementInElementIdAttrMap()
{
return false;
}
internal void ResetOwnerElementInElementIdAttrMap(string oldInnerText)
{
XmlElement ownerElement = OwnerElement;
if (ownerElement != null)
{
ownerElement.Attributes.ResetParentInElementIdAttrMap(oldInnerText, InnerText);
}
}
internal override bool IsContainer
{
get { return true; }
}
//the function is provided only at Load time to speed up Load process
internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc)
{
XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this);
if (args != null)
doc.BeforeEvent(args);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (_lastChild == null)
{ // if LastNode == null
newNode.next = newNode;
_lastChild = newNode;
newNode.SetParentForLoad(this);
}
else
{
XmlLinkedNode refNode = _lastChild; // refNode = LastNode;
newNode.next = refNode.next;
refNode.next = newNode;
_lastChild = newNode; // LastNode = newNode;
if (refNode.IsText
&& newNode.IsText)
{
NestTextNodes(refNode, newNode);
}
else
{
newNode.SetParentForLoad(this);
}
}
if (args != null)
doc.AfterEvent(args);
return newNode;
}
internal override XmlLinkedNode LastNode
{
get { return _lastChild; }
set { _lastChild = value; }
}
internal override bool IsValidChildType(XmlNodeType type)
{
return (type == XmlNodeType.Text) || (type == XmlNodeType.EntityReference);
}
// Gets a value indicating whether the value was explicitly set.
public virtual bool Specified
{
get { return true; }
}
public override XmlNode InsertBefore(XmlNode newChild, XmlNode refChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.InsertBefore(newChild, refChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.InsertBefore(newChild, refChild);
}
return node;
}
public override XmlNode InsertAfter(XmlNode newChild, XmlNode refChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.InsertAfter(newChild, refChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.InsertAfter(newChild, refChild);
}
return node;
}
public override XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.ReplaceChild(newChild, oldChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.ReplaceChild(newChild, oldChild);
}
return node;
}
public override XmlNode RemoveChild(XmlNode oldChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.RemoveChild(oldChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.RemoveChild(oldChild);
}
return node;
}
public override XmlNode PrependChild(XmlNode newChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.PrependChild(newChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.PrependChild(newChild);
}
return node;
}
public override XmlNode AppendChild(XmlNode newChild)
{
XmlNode node;
if (PrepareOwnerElementInElementIdAttrMap())
{
string innerText = InnerText;
node = base.AppendChild(newChild);
ResetOwnerElementInElementIdAttrMap(innerText);
}
else
{
node = base.AppendChild(newChild);
}
return node;
}
// DOM Level 2
// Gets the XmlElement node that contains this attribute.
public virtual XmlElement OwnerElement
{
get
{
return parentNode as XmlElement;
}
}
// Gets or sets the markup representing just the children of this node.
public override string InnerXml
{
set
{
RemoveAll();
XmlLoader loader = new XmlLoader();
loader.LoadInnerXmlAttribute(this, value);
}
}
// Saves the node to the specified XmlWriter.
public override void WriteTo(XmlWriter w)
{
w.WriteStartAttribute(Prefix, LocalName, NamespaceURI);
WriteContentTo(w);
w.WriteEndAttribute();
}
// Saves all the children of the node to the specified XmlWriter.
public override void WriteContentTo(XmlWriter w)
{
for (XmlNode node = FirstChild; node != null; node = node.NextSibling)
{
node.WriteTo(w);
}
}
public override String BaseURI
{
get
{
if (OwnerElement != null)
return OwnerElement.BaseURI;
return String.Empty;
}
}
internal override void SetParent(XmlNode node)
{
this.parentNode = node;
}
internal override XmlSpace XmlSpace
{
get
{
if (OwnerElement != null)
return OwnerElement.XmlSpace;
return XmlSpace.None;
}
}
internal override String XmlLang
{
get
{
if (OwnerElement != null)
return OwnerElement.XmlLang;
return String.Empty;
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public class SoftwareFloatingPoint
{
const string c_CompareAndSet_FloatEqual = "SoftFP_CompareAndSet_FloatEqual";
const string c_CompareAndSet_FloatGreaterOrEqual = "SoftFP_CompareAndSet_FloatGreaterOrEqual";
const string c_CompareAndSet_FloatGreater = "SoftFP_CompareAndSet_FloatGreater";
const string c_CompareAndSet_FloatLessOrEqual = "SoftFP_CompareAndSet_FloatLessOrEqual";
const string c_CompareAndSet_FloatLess = "SoftFP_CompareAndSet_FloatLess";
const string c_CompareAndSet_FloatNotEqual = "SoftFP_CompareAndSet_FloatNotEqual";
const string c_CompareAndSet_DoubleEqual = "SoftFP_CompareAndSet_DoubleEqual";
const string c_CompareAndSet_DoubleGreaterOrEqual = "SoftFP_CompareAndSet_DoubleGreaterOrEqual";
const string c_CompareAndSet_DoubleGreater = "SoftFP_CompareAndSet_DoubleGreater";
const string c_CompareAndSet_DoubleLessOrEqual = "SoftFP_CompareAndSet_DoubleLessOrEqual";
const string c_CompareAndSet_DoubleLess = "SoftFP_CompareAndSet_DoubleLess";
const string c_CompareAndSet_DoubleNotEqual = "SoftFP_CompareAndSet_DoubleNotEqual";
//--//
const string c_BinaryOperations_FloatAdd = "SoftFP_BinaryOperations_FloatAdd";
const string c_BinaryOperations_FloatSub = "SoftFP_BinaryOperations_FloatSub";
const string c_BinaryOperations_FloatMul = "SoftFP_BinaryOperations_FloatMul";
const string c_BinaryOperations_FloatDiv = "SoftFP_BinaryOperations_FloatDiv";
const string c_BinaryOperations_FloatRem = "SoftFP_BinaryOperations_FloatRem";
const string c_BinaryOperations_DoubleAdd = "SoftFP_BinaryOperations_DoubleAdd";
const string c_BinaryOperations_DoubleSub = "SoftFP_BinaryOperations_DoubleSub";
const string c_BinaryOperations_DoubleMul = "SoftFP_BinaryOperations_DoubleMul";
const string c_BinaryOperations_DoubleDiv = "SoftFP_BinaryOperations_DoubleDiv";
const string c_BinaryOperations_DoubleRem = "SoftFP_BinaryOperations_DoubleRem";
//--//
const string c_UnaryOperations_FloatNeg = "SoftFP_UnaryOperations_FloatNeg";
const string c_UnaryOperations_FloatFinite = "SoftFP_UnaryOperations_FloatFinite";
const string c_UnaryOperations_DoubleNeg = "SoftFP_UnaryOperations_DoubleNeg";
const string c_UnaryOperations_DoubleFinite = "SoftFP_UnaryOperations_DoubleFinite";
//--//
const string c_Convert_IntToFloat = "SoftFP_Convert_IntToFloat";
const string c_Convert_LongToFloat = "SoftFP_Convert_LongToFloat";
const string c_Convert_UnsignedIntToFloat = "SoftFP_Convert_UnsignedIntToFloat";
const string c_Convert_UnsignedLongToFloat = "SoftFP_Convert_UnsignedLongToFloat";
const string c_Convert_DoubleToFloat = "SoftFP_Convert_DoubleToFloat";
const string c_Convert_IntToDouble = "SoftFP_Convert_IntToDouble";
const string c_Convert_LongToDouble = "SoftFP_Convert_LongToDouble";
const string c_Convert_UnsignedIntToDouble = "SoftFP_Convert_UnsignedIntToDouble";
const string c_Convert_UnsignedLongToDouble = "SoftFP_Convert_UnsignedLongToDouble";
const string c_Convert_FloatToDouble = "SoftFP_Convert_FloatToDouble";
const string c_Convert_FloatToInt = "SoftFP_Convert_FloatToInt";
const string c_Convert_FloatToUnsignedInt = "SoftFP_Convert_FloatToUnsignedInt";
const string c_Convert_DoubleToInt = "SoftFP_Convert_DoubleToInt";
const string c_Convert_DoubleToUnsignedInt = "SoftFP_Convert_DoubleToUnsignedInt";
const string c_Convert_FloatToLong = "SoftFP_Convert_FloatToLong";
const string c_Convert_FloatToUnsignedLong = "SoftFP_Convert_FloatToUnsignedLong";
const string c_Convert_DoubleToLong = "SoftFP_Convert_DoubleToLong";
const string c_Convert_DoubleToUnsignedLong = "SoftFP_Convert_DoubleToUnsignedLong";
//--//
[CompilationSteps.CallClosureHandler( typeof(CompareConditionalControlOperator) )]
private static void Protect_CompareConditionalControlOperator( ComputeCallsClosure.Context host ,
Operator target )
{
CompareConditionalControlOperator op = (CompareConditionalControlOperator)target;
Protect_CommonFloatingPointCompare( host, op, op.Condition );
}
[CompilationSteps.CallClosureHandler( typeof(CompareAndSetOperator) )]
private static void Protect_CompareAndSetOperators( ComputeCallsClosure.Context host ,
Operator target )
{
CompareAndSetOperator op = (CompareAndSetOperator)target;
Protect_CommonFloatingPointCompare( host, op, op.Condition );
}
private static void Protect_CommonFloatingPointCompare( ComputeCallsClosure.Context host ,
Operator target ,
CompareAndSetOperator.ActionCondition condition )
{
TypeRepresentation td = target.FirstArgument.Type;
TypeSystemForCodeTransformation ts = host.TypeSystem;
WellKnownTypes wkt = ts.WellKnownTypes;
string name = null;
if(td == wkt.System_Single)
{
switch(condition)
{
case CompareAndSetOperator.ActionCondition.EQ: name = c_CompareAndSet_FloatEqual ; break;
case CompareAndSetOperator.ActionCondition.GE: name = c_CompareAndSet_FloatGreaterOrEqual; break;
case CompareAndSetOperator.ActionCondition.GT: name = c_CompareAndSet_FloatGreater ; break;
case CompareAndSetOperator.ActionCondition.LE: name = c_CompareAndSet_FloatLessOrEqual ; break;
case CompareAndSetOperator.ActionCondition.LT: name = c_CompareAndSet_FloatLess ; break;
case CompareAndSetOperator.ActionCondition.NE: name = c_CompareAndSet_FloatNotEqual ; break;
}
}
else if(td == wkt.System_Double)
{
switch(condition)
{
case CompareAndSetOperator.ActionCondition.EQ: name = c_CompareAndSet_DoubleEqual ; break;
case CompareAndSetOperator.ActionCondition.GE: name = c_CompareAndSet_DoubleGreaterOrEqual; break;
case CompareAndSetOperator.ActionCondition.GT: name = c_CompareAndSet_DoubleGreater ; break;
case CompareAndSetOperator.ActionCondition.LE: name = c_CompareAndSet_DoubleLessOrEqual ; break;
case CompareAndSetOperator.ActionCondition.LT: name = c_CompareAndSet_DoubleLess ; break;
case CompareAndSetOperator.ActionCondition.NE: name = c_CompareAndSet_DoubleNotEqual ; break;
}
}
if(name != null)
{
host.CoverObject( ts.GetWellKnownMethod( name ) );
}
}
[CompilationSteps.CallClosureHandler( typeof(BinaryOperator) )]
private static void Protect_BinaryOperator( ComputeCallsClosure.Context host ,
Operator target )
{
BinaryOperator op = (BinaryOperator)target;
TypeRepresentation td = op.FirstArgument.Type;
TypeSystemForCodeTransformation ts = host.TypeSystem;
WellKnownTypes wkt = ts.WellKnownTypes;
string name = null;
if(td == wkt.System_Single)
{
switch(op.Alu)
{
case BinaryOperator.ALU.ADD: name = c_BinaryOperations_FloatAdd; break;
case BinaryOperator.ALU.SUB: name = c_BinaryOperations_FloatSub; break;
case BinaryOperator.ALU.MUL: name = c_BinaryOperations_FloatMul; break;
case BinaryOperator.ALU.DIV: name = c_BinaryOperations_FloatDiv; break;
case BinaryOperator.ALU.REM: name = c_BinaryOperations_FloatRem; break;
}
}
else if(td == wkt.System_Double)
{
switch(op.Alu)
{
case BinaryOperator.ALU.ADD: name = c_BinaryOperations_DoubleAdd; break;
case BinaryOperator.ALU.SUB: name = c_BinaryOperations_DoubleSub; break;
case BinaryOperator.ALU.MUL: name = c_BinaryOperations_DoubleMul; break;
case BinaryOperator.ALU.DIV: name = c_BinaryOperations_DoubleDiv; break;
case BinaryOperator.ALU.REM: name = c_BinaryOperations_DoubleRem; break;
}
}
if(name != null)
{
host.CoverObject( ts.GetWellKnownMethod( name ) );
}
}
[CompilationSteps.CallClosureHandler( typeof(UnaryOperator) )]
private static void Protect_UnaryOperator( ComputeCallsClosure.Context host ,
Operator target )
{
UnaryOperator op = (UnaryOperator)target;
TypeRepresentation td = op.FirstArgument.Type;
TypeSystemForCodeTransformation ts = host.TypeSystem;
WellKnownTypes wkt = ts.WellKnownTypes;
string name = null;
if(td == wkt.System_Single)
{
switch(op.Alu)
{
case UnaryOperator.ALU.NEG : name = c_UnaryOperations_FloatNeg ; break;
case UnaryOperator.ALU.FINITE: name = c_UnaryOperations_FloatFinite; break;
}
}
else if(td == wkt.System_Double)
{
switch(op.Alu)
{
case UnaryOperator.ALU.NEG : name = c_UnaryOperations_DoubleNeg ; break;
case UnaryOperator.ALU.FINITE: name = c_UnaryOperations_DoubleFinite; break;
}
}
if(name != null)
{
host.CoverObject( ts.GetWellKnownMethod( name ) );
}
}
[CompilationSteps.CallClosureHandler( typeof(ConvertOperator) )]
private static void Protect_ConvertOperator( ComputeCallsClosure.Context host ,
Operator target )
{
ConvertOperator op = (ConvertOperator)target;
TypeSystemForCodeTransformation ts = host.TypeSystem;
TypeRepresentation.BuiltInTypes kindInput = op.InputKind;
TypeRepresentation.BuiltInTypes kindOutput = op.OutputKind;
string name = null;
switch(kindOutput)
{
case TypeRepresentation.BuiltInTypes.R4:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.I4: name = c_Convert_IntToFloat ; break;
case TypeRepresentation.BuiltInTypes.U4: name = c_Convert_UnsignedIntToFloat ; break;
case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToFloat ; break;
case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToFloat; break;
case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToFloat ; break;
}
break;
case TypeRepresentation.BuiltInTypes.R8:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.I4: name = c_Convert_IntToDouble ; break;
case TypeRepresentation.BuiltInTypes.U4: name = c_Convert_UnsignedIntToDouble ; break;
case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToDouble ; break;
case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToDouble; break;
case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToDouble ; break;
}
break;
case TypeRepresentation.BuiltInTypes.I4:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToInt ; break;
case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToInt; break;
}
break;
case TypeRepresentation.BuiltInTypes.U4:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToUnsignedInt ; break;
case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToUnsignedInt; break;
}
break;
case TypeRepresentation.BuiltInTypes.I8:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToLong ; break;
case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToLong; break;
}
break;
case TypeRepresentation.BuiltInTypes.U8:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToUnsignedLong ; break;
case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToUnsignedLong; break;
}
break;
}
if(name != null)
{
host.CoverObject( ts.GetWellKnownMethod( name ) );
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )]
[CompilationSteps.OperatorHandler( typeof(CompareConditionalControlOperator) )]
private static void Handle_CompareConditionalControlOperator( PhaseExecution.NotificationContext nc )
{
CompareConditionalControlOperator op = (CompareConditionalControlOperator)nc.CurrentOperator;
if(op.FirstArgument.Type.IsFloatingPoint)
{
ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG;
TypeSystemForCodeTransformation ts = nc.TypeSystem;
TemporaryVariableExpression tmp = cfg.AllocateTemporary( ts.WellKnownTypes.System_Boolean, null );
CompareAndSetOperator opCmp = CompareAndSetOperator.New( op.DebugInfo, op.Condition, op.Signed, tmp, op.FirstArgument, op.SecondArgument );
op.AddOperatorBefore( opCmp );
BinaryConditionalControlOperator opCtrl = BinaryConditionalControlOperator.New( op.DebugInfo, tmp, op.TargetBranchNotTaken, op.TargetBranchTaken );
op.SubstituteWithOperator( opCtrl, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )]
[CompilationSteps.OperatorHandler( typeof(CompareAndSetOperator) )]
private static void Handle_CompareAndSetOperator( PhaseExecution.NotificationContext nc )
{
CompareAndSetOperator op = (CompareAndSetOperator)nc.CurrentOperator;
Expression exSrc1 = op.FirstArgument;
Expression exSrc2 = op.SecondArgument;
TypeRepresentation tdSrc1 = exSrc1.Type;
TypeRepresentation tdSrc2 = exSrc2.Type;
if(tdSrc1.IsFloatingPoint &&
tdSrc2.IsFloatingPoint )
{
ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG;
TypeSystemForCodeTransformation ts = nc.TypeSystem;
uint sizeSrc1 = tdSrc1.SizeOfHoldingVariableInWords;
uint sizeSrc2 = tdSrc2.SizeOfHoldingVariableInWords;
string name;
CHECKS.ASSERT( sizeSrc1 == sizeSrc2, "Cannot compare entities of different size: {0} <=> {1}", exSrc1, exSrc2 );
if(sizeSrc1 == 1)
{
switch(op.Condition)
{
case CompareAndSetOperator.ActionCondition.EQ: name = c_CompareAndSet_FloatEqual ; break;
case CompareAndSetOperator.ActionCondition.GE: name = c_CompareAndSet_FloatGreaterOrEqual; break;
case CompareAndSetOperator.ActionCondition.GT: name = c_CompareAndSet_FloatGreater ; break;
case CompareAndSetOperator.ActionCondition.LE: name = c_CompareAndSet_FloatLessOrEqual ; break;
case CompareAndSetOperator.ActionCondition.LT: name = c_CompareAndSet_FloatLess ; break;
case CompareAndSetOperator.ActionCondition.NE: name = c_CompareAndSet_FloatNotEqual ; break;
default: throw TypeConsistencyErrorException.Create( "Unexpected value {0} in {1}", op.Condition, op );
}
}
else if(sizeSrc1 == 2)
{
switch(op.Condition)
{
case CompareAndSetOperator.ActionCondition.EQ: name = c_CompareAndSet_DoubleEqual ; break;
case CompareAndSetOperator.ActionCondition.GE: name = c_CompareAndSet_DoubleGreaterOrEqual; break;
case CompareAndSetOperator.ActionCondition.GT: name = c_CompareAndSet_DoubleGreater ; break;
case CompareAndSetOperator.ActionCondition.LE: name = c_CompareAndSet_DoubleLessOrEqual ; break;
case CompareAndSetOperator.ActionCondition.LT: name = c_CompareAndSet_DoubleLess ; break;
case CompareAndSetOperator.ActionCondition.NE: name = c_CompareAndSet_DoubleNotEqual ; break;
default: throw TypeConsistencyErrorException.Create( "Unexpected value {0} in {1}", op.Condition, op );
}
}
else
{
throw TypeConsistencyErrorException.Create( "Unsupported compare operation larger than 64 bits: {0}", op );
}
ts.SubstituteWithCallToHelper( name, op );
nc.MarkAsModified();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )]
[CompilationSteps.OperatorHandler( typeof(BinaryOperator) )]
private static void Handle_BinaryOperator( PhaseExecution.NotificationContext nc )
{
BinaryOperator op = (BinaryOperator)nc.CurrentOperator;
Expression exSrc1 = op.FirstArgument;
Expression exSrc2 = op.SecondArgument;
TypeRepresentation tdSrc1 = exSrc1.Type;
TypeRepresentation tdSrc2 = exSrc2.Type;
if(tdSrc1.IsFloatingPoint &&
tdSrc2.IsFloatingPoint )
{
ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG;
TypeSystemForCodeTransformation ts = nc.TypeSystem;
VariableExpression exRes = op.FirstResult;
TypeRepresentation tdRes = exRes .Type;
uint sizeRes = tdRes .SizeOfHoldingVariableInWords;
uint sizeSrc1 = tdSrc1.SizeOfHoldingVariableInWords;
uint sizeSrc2 = tdSrc2.SizeOfHoldingVariableInWords;
string name;
CHECKS.ASSERT( sizeSrc1 == sizeSrc2, "Cannot compare entities of different size: {0} <=> {1}", exSrc1, exSrc2 );
if(sizeSrc1 == 1)
{
switch(op.Alu)
{
case BinaryOperator.ALU.ADD: name = c_BinaryOperations_FloatAdd; break;
case BinaryOperator.ALU.SUB: name = c_BinaryOperations_FloatSub; break;
case BinaryOperator.ALU.MUL: name = c_BinaryOperations_FloatMul; break;
case BinaryOperator.ALU.DIV: name = c_BinaryOperations_FloatDiv; break;
case BinaryOperator.ALU.REM: name = c_BinaryOperations_FloatRem; break;
default:
throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op );
}
}
else if(sizeSrc1 == 2)
{
switch(op.Alu)
{
case BinaryOperator.ALU.ADD: name = c_BinaryOperations_DoubleAdd; break;
case BinaryOperator.ALU.SUB: name = c_BinaryOperations_DoubleSub; break;
case BinaryOperator.ALU.MUL: name = c_BinaryOperations_DoubleMul; break;
case BinaryOperator.ALU.DIV: name = c_BinaryOperations_DoubleDiv; break;
case BinaryOperator.ALU.REM: name = c_BinaryOperations_DoubleRem; break;
default:
throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op );
}
}
else
{
throw TypeConsistencyErrorException.Create( "Unsupported inputs for binary operator: {0}", op );
}
ts.SubstituteWithCallToHelper( name, op );
nc.MarkAsModified();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )]
[CompilationSteps.OperatorHandler( typeof(UnaryOperator) )]
private static void Handle_UnaryOperator( PhaseExecution.NotificationContext nc )
{
UnaryOperator op = (UnaryOperator)nc.CurrentOperator;
Expression exSrc = op.FirstArgument;
TypeRepresentation tdSrc = exSrc.Type;
if(tdSrc.IsFloatingPoint)
{
ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG;
TypeSystemForCodeTransformation ts = nc.TypeSystem;
uint sizeSrc = tdSrc.SizeOfHoldingVariableInWords;
string name;
if(sizeSrc == 1)
{
switch(op.Alu)
{
case UnaryOperator.ALU.NEG : name = c_UnaryOperations_FloatNeg ; break;
case UnaryOperator.ALU.FINITE: name = c_UnaryOperations_FloatFinite; break;
default:
throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op );
}
}
else if(sizeSrc == 2)
{
switch(op.Alu)
{
case UnaryOperator.ALU.NEG : name = c_UnaryOperations_DoubleNeg ; break;
case UnaryOperator.ALU.FINITE: name = c_UnaryOperations_DoubleFinite; break;
default:
throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op );
}
}
else
{
throw TypeConsistencyErrorException.Create( "Unsupported inputs for unary operator: {0}", op );
}
ts.SubstituteWithCallToHelper( name, op );
nc.MarkAsModified();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )]
[CompilationSteps.OperatorHandler( typeof(BinaryConditionalControlOperator) )]
private static void Handle_BinaryConditionalControlOperator( PhaseExecution.NotificationContext nc )
{
BinaryConditionalControlOperator op = (BinaryConditionalControlOperator)nc.CurrentOperator;
Expression exSrc = op.FirstArgument;
TypeRepresentation tdSrc = exSrc.Type;
//--//
if(tdSrc.IsFloatingPoint)
{
TypeSystemForCodeTransformation ts = nc.TypeSystem;
ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG;
Debugging.DebugInfo debugInfo = op.DebugInfo;
uint sizeSrc = tdSrc.SizeOfHoldingVariableInWords;
string name;
object val;
if(sizeSrc == 1)
{
name = c_CompareAndSet_FloatEqual;
val = (float)0;
}
else if(sizeSrc == 2)
{
name = c_CompareAndSet_DoubleEqual;
val = (double)0;
}
else
{
throw TypeConsistencyErrorException.Create( "Unsupported inputs for compare: {0}", op );
}
MethodRepresentation md = ts.GetWellKnownMethod( name );
VariableExpression tmpFragment = cfg.AllocatePseudoRegister( ts.WellKnownTypes.System_Boolean );
Expression[] rhs = ts.AddTypePointerToArgumentsOfStaticMethod( md, op.FirstArgument, ts.CreateConstant( md.OwnerType, val ) );
StaticCallOperator opCall = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, VariableExpression.ToArray( tmpFragment ), rhs );
op.AddOperatorBefore( opCall );
//--//
var cc = cfg.AllocateConditionCode();
op.AddOperatorBefore( CompareOperator.New( debugInfo, cc, tmpFragment, ts.CreateConstant( 0 ) ) );
ConditionCodeConditionalControlOperator opNew = ConditionCodeConditionalControlOperator.New( debugInfo, ConditionCodeExpression.Comparison.NotEqual, cc, op.TargetBranchNotTaken, op.TargetBranchTaken );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.FromImplicitToExplicitExceptions) )]
[CompilationSteps.OperatorHandler( typeof(ConvertOperator) )]
private static void Handle_ConvertOperator_Exceptions( PhaseExecution.NotificationContext nc )
{
ConvertOperator op = (ConvertOperator)nc.CurrentOperator;
VariableExpression lhs = op.FirstResult;
Expression rhs = op.FirstArgument;
if(op.CheckOverflow)
{
ConvertOperator opNew = ConvertOperator.New( op.DebugInfo, op.InputKind, op.OutputKind, false, lhs, rhs );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations );
//
// BUGBUG: We are dropping the overflow check!!
//
//// CreateOverflowCheck( nc, op, opNew );
nc.MarkAsModified();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.ConvertUnsupportedOperatorsToMethodCalls) )]
[CompilationSteps.OperatorHandler( typeof(ConvertOperator) )]
private static void Handle_ConvertOperator( PhaseExecution.NotificationContext nc )
{
ConvertOperator op = (ConvertOperator)nc.CurrentOperator;
TypeSystemForCodeTransformation ts = nc.TypeSystem;
TypeRepresentation.BuiltInTypes kindInput = op.InputKind;
TypeRepresentation.BuiltInTypes kindOutput = op.OutputKind;
string name = null;
switch(kindOutput)
{
case TypeRepresentation.BuiltInTypes.R4:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.I4: name = c_Convert_IntToFloat ; break;
case TypeRepresentation.BuiltInTypes.U4: name = c_Convert_UnsignedIntToFloat ; break;
case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToFloat ; break;
case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToFloat; break;
case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToFloat ; break;
}
break;
case TypeRepresentation.BuiltInTypes.R8:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.I4: name = c_Convert_IntToDouble ; break;
case TypeRepresentation.BuiltInTypes.U4: name = c_Convert_UnsignedIntToDouble ; break;
case TypeRepresentation.BuiltInTypes.I8: name = c_Convert_LongToDouble ; break;
case TypeRepresentation.BuiltInTypes.U8: name = c_Convert_UnsignedLongToDouble; break;
case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToDouble ; break;
}
break;
case TypeRepresentation.BuiltInTypes.I4:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToInt ; break;
case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToInt; break;
}
break;
case TypeRepresentation.BuiltInTypes.U4:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToUnsignedInt ; break;
case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToUnsignedInt; break;
}
break;
case TypeRepresentation.BuiltInTypes.I8:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToLong ; break;
case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToLong; break;
}
break;
case TypeRepresentation.BuiltInTypes.U8:
switch(kindInput)
{
case TypeRepresentation.BuiltInTypes.R4: name = c_Convert_FloatToUnsignedLong ; break;
case TypeRepresentation.BuiltInTypes.R8: name = c_Convert_DoubleToUnsignedLong; break;
}
break;
}
if(name != null)
{
MethodRepresentation md = ts.GetWellKnownMethod( name );
Expression[] rhs = ts.AddTypePointerToArgumentsOfStaticMethod( md, op.FirstArgument, ts.CreateConstant( ts.WellKnownTypes.System_Boolean, op.CheckOverflow ) );
StaticCallOperator opCall = StaticCallOperator.New( op.DebugInfo, CallOperator.CallKind.Direct, md, op.Results, rhs );
op.SubstituteWithOperator( opCall, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Remoting;
using System.Threading;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This cmdlet suspends the jobs that are Job2. Errors are added for each Job that is not Job2.
/// </summary>
#if !CORECLR
[SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")]
[Cmdlet(VerbsLifecycle.Suspend, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210613")]
[OutputType(typeof(Job))]
#endif
public class SuspendJobCommand : JobCmdletBase, IDisposable
{
#region Parameters
/// <summary>
/// Specifies the Jobs objects which need to be
/// suspended.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = JobParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Job[] Job
{
get
{
return _jobs;
}
set
{
_jobs = value;
}
}
private Job[] _jobs;
/// <summary>
/// </summary>
public override string[] Command
{
get
{
return null;
}
}
/// <summary>
/// If state of the job is running , this will forcefully suspend it.
/// </summary>
[Parameter(ParameterSetName = RemoveJobCommand.InstanceIdParameterSet)]
[Parameter(ParameterSetName = RemoveJobCommand.JobParameterSet)]
[Parameter(ParameterSetName = RemoveJobCommand.NameParameterSet)]
[Parameter(ParameterSetName = RemoveJobCommand.SessionIdParameterSet)]
[Parameter(ParameterSetName = RemoveJobCommand.FilterParameterSet)]
[Parameter(ParameterSetName = RemoveJobCommand.StateParameterSet)]
[Alias("F")]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
private bool _force = false;
/// <summary>
/// </summary>
[Parameter()]
public SwitchParameter Wait
{
get
{
return _wait;
}
set
{
_wait = value;
}
}
private bool _wait = false;
#endregion Parameters
#region Overrides
/// <summary>
/// Suspend the Job.
/// </summary>
protected override void ProcessRecord()
{
// List of jobs to suspend
List<Job> jobsToSuspend = null;
switch (ParameterSetName)
{
case NameParameterSet:
{
jobsToSuspend = FindJobsMatchingByName(true, false, true, false);
}
break;
case InstanceIdParameterSet:
{
jobsToSuspend = FindJobsMatchingByInstanceId(true, false, true, false);
}
break;
case SessionIdParameterSet:
{
jobsToSuspend = FindJobsMatchingBySessionId(true, false, true, false);
}
break;
case StateParameterSet:
{
jobsToSuspend = FindJobsMatchingByState(false);
}
break;
case FilterParameterSet:
{
jobsToSuspend = FindJobsMatchingByFilter(false);
}
break;
default:
{
jobsToSuspend = CopyJobsToList(_jobs, false, false);
}
break;
}
_allJobsToSuspend.AddRange(jobsToSuspend);
foreach (Job job in jobsToSuspend)
{
var job2 = job as Job2;
// If the job is not Job2, the suspend operation is not supported.
if (job2 == null)
{
WriteError(
new ErrorRecord(
PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobSuspendNotSupported, job.Id),
"Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job));
continue;
}
string targetString =
PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget,
job.Command, job.Id);
if (ShouldProcess(targetString, VerbsLifecycle.Suspend))
{
if (_wait)
{
_cleanUpActions.Add(job2, HandleSuspendJobCompleted);
}
else
{
if (job2.IsFinishedState(job2.JobStateInfo.State) || job2.JobStateInfo.State == JobState.Stopping)
{
_warnInvalidState = true;
continue;
}
if (job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended)
continue;
job2.StateChanged += noWait_Job2_StateChanged;
}
job2.SuspendJobCompleted += HandleSuspendJobCompleted;
lock (_syncObject)
{
if (!_pendingJobs.Contains(job2.InstanceId))
{
_pendingJobs.Add(job2.InstanceId);
}
}
// there could be possibility that the job gets completed before or after the
// subscribing to nowait_job2_statechanged event so checking it again.
if (!_wait && (job2.IsFinishedState(job2.JobStateInfo.State) || job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended))
{
this.ProcessExecutionErrorsAndReleaseWaitHandle(job2);
}
job2.SuspendJobAsync(_force, RemotingErrorIdStrings.ForceSuspendJob);
}
}
}
private bool _warnInvalidState = false;
private readonly HashSet<Guid> _pendingJobs = new HashSet<Guid>();
private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false);
private readonly Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>> _cleanUpActions =
new Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>>();
private readonly List<ErrorRecord> _errorsToWrite = new List<ErrorRecord>();
private readonly List<Job> _allJobsToSuspend = new List<Job>();
private readonly object _syncObject = new object();
private bool _needToCheckForWaitingJobs;
private void noWait_Job2_StateChanged(object sender, JobStateEventArgs e)
{
Job job = sender as Job;
switch (e.JobStateInfo.State)
{
case JobState.Completed:
case JobState.Stopped:
case JobState.Failed:
case JobState.Suspended:
case JobState.Suspending:
this.ProcessExecutionErrorsAndReleaseWaitHandle(job);
break;
}
}
private void HandleSuspendJobCompleted(object sender, AsyncCompletedEventArgs eventArgs)
{
Job job = sender as Job;
if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException)
{
_warnInvalidState = true;
}
this.ProcessExecutionErrorsAndReleaseWaitHandle(job);
}
private void ProcessExecutionErrorsAndReleaseWaitHandle(Job job)
{
bool releaseWait = false;
lock (_syncObject)
{
if (_pendingJobs.Contains(job.InstanceId))
{
_pendingJobs.Remove(job.InstanceId);
}
else
{
// there could be a possibility of race condition where this function is getting called twice
// so if job doesn't present in the _pendingJobs then just return
return;
}
if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0)
releaseWait = true;
}
if (!_wait)
{
job.StateChanged -= noWait_Job2_StateChanged;
Job2 job2 = job as Job2;
if (job2 != null)
job2.SuspendJobCompleted -= HandleSuspendJobCompleted;
}
var parentJob = job as ContainerParentJob;
if (parentJob != null && parentJob.ExecutionError.Count > 0)
{
foreach (
var e in
parentJob.ExecutionError.Where(static e => e.FullyQualifiedErrorId == "ContainerParentJobSuspendAsyncError")
)
{
if (e.Exception is InvalidJobStateException)
{
// if any errors were invalid job state exceptions, warn the user.
// This is to support Get-Job | Resume-Job scenarios when many jobs
// are Completed, etc.
_warnInvalidState = true;
}
else
{
_errorsToWrite.Add(e);
}
}
}
// end processing has been called
// set waithandle if this is the last one
if (releaseWait)
_waitForJobs.Set();
}
/// <summary>
/// End Processing.
/// </summary>
protected override void EndProcessing()
{
bool haveToWait = false;
lock (_syncObject)
{
_needToCheckForWaitingJobs = true;
if (_pendingJobs.Count > 0)
haveToWait = true;
}
if (haveToWait)
_waitForJobs.WaitOne();
if (_warnInvalidState) WriteWarning(RemotingErrorIdStrings.SuspendJobInvalidJobState);
foreach (var e in _errorsToWrite) WriteError(e);
foreach (var j in _allJobsToSuspend) WriteObject(j);
base.EndProcessing();
}
/// <summary>
/// </summary>
protected override void StopProcessing()
{
_waitForJobs.Set();
}
#endregion Overrides
#region Dispose
/// <summary>
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// </summary>
/// <param name="disposing"></param>
protected void Dispose(bool disposing)
{
if (!disposing) return;
foreach (var pair in _cleanUpActions)
{
pair.Key.SuspendJobCompleted -= pair.Value;
}
_waitForJobs.Dispose();
}
#endregion Dispose
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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.Reflection;
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 ConvertToVector256Int64UInt32()
{
var test = new SimpleUnaryOpTest__ConvertToVector256Int64UInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using the pointer overload
test.RunBasicScenario_Ptr();
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();
// Validates calling via reflection works, using the pointer overload
test.RunReflectionScenario_Ptr();
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();
// 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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ConvertToVector256Int64UInt32
{
private const int VectorSize = 32;
private const int Op1ElementCount = 16 / sizeof(UInt32);
private const int RetElementCount = VectorSize / sizeof(Int64);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector128<UInt32> _clsVar;
private Vector128<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt32> _dataTable;
static SimpleUnaryOpTest__ConvertToVector256Int64UInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), 16);
}
public SimpleUnaryOpTest__ConvertToVector256Int64UInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), 16);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt32>(_data, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ConvertToVector256Int64(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Ptr()
{
var result = Avx2.ConvertToVector256Int64(
(UInt32*)(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ConvertToVector256Int64(
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ConvertToVector256Int64(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Ptr()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(UInt32*) })
.Invoke(null, new object[] {
Pointer.Box(_dataTable.inArrayPtr, typeof(UInt32*))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ConvertToVector256Int64), new Type[] { typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ConvertToVector256Int64(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr);
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ConvertToVector256Int64(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ConvertToVector256Int64UInt32();
var result = Avx2.ConvertToVector256Int64(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ConvertToVector256Int64(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), 16);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
if (result[0] != firstOp[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != firstOp[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ConvertToVector256Int64)}<UInt64>(Vector128<UInt32>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.UnitTests;
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using Xunit;
namespace Avalonia.Input.UnitTests
{
public class InputElement_HitTesting
{
[Fact]
public void InputHitTest_Should_Find_Control_At_Point()
{
using (var application = UnitTestApplication.Start(new TestServices(renderInterface: new MockRenderInterface())))
{
var container = new Decorator
{
Width = 200,
Height = 200,
Child = new Border
{
Width = 100,
Height = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
}
};
container.Measure(Size.Infinity);
container.Arrange(new Rect(container.DesiredSize));
var context = new DrawingContext(Mock.Of<IDrawingContextImpl>());
context.Render(container);
var result = container.InputHitTest(new Point(100, 100));
Assert.Equal(container.Child, result);
}
}
[Fact]
public void InputHitTest_Should_Not_Find_Control_Outside_Point()
{
using (UnitTestApplication.Start(new TestServices(renderInterface: new MockRenderInterface())))
{
var container = new Decorator
{
Width = 200,
Height = 200,
Child = new Border
{
Width = 100,
Height = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
}
};
container.Measure(Size.Infinity);
container.Arrange(new Rect(container.DesiredSize));
var context = new DrawingContext(Mock.Of<IDrawingContextImpl>());
context.Render(container);
var result = container.InputHitTest(new Point(10, 10));
Assert.Equal(container, result);
}
}
[Fact]
public void InputHitTest_Should_Find_Top_Control_At_Point()
{
using (UnitTestApplication.Start(new TestServices(renderInterface: new MockRenderInterface())))
{
var container = new Panel
{
Width = 200,
Height = 200,
Children = new Controls.Controls
{
new Border
{
Width = 100,
Height = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
},
new Border
{
Width = 50,
Height = 50,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
}
}
};
container.Measure(Size.Infinity);
container.Arrange(new Rect(container.DesiredSize));
var context = new DrawingContext(Mock.Of<IDrawingContextImpl>());
context.Render(container);
var result = container.InputHitTest(new Point(100, 100));
Assert.Equal(container.Children[1], result);
}
}
[Fact]
public void InputHitTest_Should_Find_Top_Control_At_Point_With_ZOrder()
{
using (UnitTestApplication.Start(new TestServices(renderInterface: new MockRenderInterface())))
{
var container = new Panel
{
Width = 200,
Height = 200,
Children = new Controls.Controls
{
new Border
{
Width = 100,
Height = 100,
ZIndex = 1,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
},
new Border
{
Width = 50,
Height = 50,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
}
}
};
container.Measure(Size.Infinity);
container.Arrange(new Rect(container.DesiredSize));
var context = new DrawingContext(Mock.Of<IDrawingContextImpl>());
context.Render(container);
var result = container.InputHitTest(new Point(100, 100));
Assert.Equal(container.Children[0], result);
}
}
[Fact]
public void InputHitTest_Should_Find_Control_Translated_Outside_Parent_Bounds()
{
using (UnitTestApplication.Start(new TestServices(renderInterface: new MockRenderInterface())))
{
Border target;
var container = new Panel
{
Width = 200,
Height = 200,
ClipToBounds = false,
Children = new Controls.Controls
{
new Border
{
Width = 100,
Height = 100,
ZIndex = 1,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Child = target = new Border
{
Width = 50,
Height = 50,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
RenderTransform = new TranslateTransform(110, 110),
}
},
}
};
container.Measure(Size.Infinity);
container.Arrange(new Rect(container.DesiredSize));
var context = new DrawingContext(Mock.Of<IDrawingContextImpl>());
context.Render(container);
var result = container.InputHitTest(new Point(120, 120));
Assert.Equal(target, result);
}
}
[Fact]
public void InputHitTest_Should_Not_Find_Control_Outside_Parent_Bounds_When_Clipped()
{
using (UnitTestApplication.Start(new TestServices(renderInterface: new MockRenderInterface())))
{
Border target;
var container = new Panel
{
Width = 100,
Height = 200,
Children = new Controls.Controls
{
new Panel()
{
Width = 100,
Height = 100,
Margin = new Thickness(0, 100, 0, 0),
ClipToBounds = true,
Children = new Controls.Controls
{
(target = new Border()
{
Width = 100,
Height = 100,
Margin = new Thickness(0, -100, 0, 0)
})
}
}
}
};
container.Measure(Size.Infinity);
container.Arrange(new Rect(container.DesiredSize));
var context = new DrawingContext(Mock.Of<IDrawingContextImpl>());
context.Render(container);
var result = container.InputHitTest(new Point(50, 50));
Assert.NotEqual(target, result);
Assert.Equal(container, result);
}
}
[Fact]
public void InputHitTest_Should_Not_Find_Control_Outside_Scroll_ViewPort()
{
using (UnitTestApplication.Start(new TestServices(renderInterface: new MockRenderInterface())))
{
Border target;
Border item1;
Border item2;
ScrollContentPresenter scroll;
var container = new Panel
{
Width = 100,
Height = 200,
Children = new Controls.Controls
{
(target = new Border()
{
Width = 100,
Height = 100
}),
new Border()
{
Width = 100,
Height = 100,
Margin = new Thickness(0, 100, 0, 0),
Child = scroll = new ScrollContentPresenter()
{
Content = new StackPanel()
{
Children = new Controls.Controls
{
(item1 = new Border()
{
Width = 100,
Height = 100,
}),
(item2 = new Border()
{
Width = 100,
Height = 100,
}),
}
}
}
}
}
};
scroll.UpdateChild();
container.Measure(Size.Infinity);
container.Arrange(new Rect(container.DesiredSize));
var context = new DrawingContext(Mock.Of<IDrawingContextImpl>());
context.Render(container);
var result = container.InputHitTest(new Point(50, 150));
Assert.Equal(item1, result);
result = container.InputHitTest(new Point(50, 50));
Assert.Equal(target, result);
scroll.Offset = new Vector(0, 100);
//we don't have setup LayoutManager so we will make it manually
scroll.Parent.InvalidateArrange();
container.InvalidateArrange();
container.Arrange(new Rect(container.DesiredSize));
context.Render(container);
result = container.InputHitTest(new Point(50, 150));
Assert.Equal(item2, result);
result = container.InputHitTest(new Point(50, 50));
Assert.NotEqual(item1, result);
Assert.Equal(target, result);
}
}
class MockRenderInterface : IPlatformRenderInterface
{
public IFormattedTextImpl CreateFormattedText(string text, string fontFamilyName, double fontSize, FontStyle fontStyle, TextAlignment textAlignment, FontWeight fontWeight, TextWrapping wrapping)
{
throw new NotImplementedException();
}
public IRenderTarget CreateRenderTarget(IPlatformHandle handle)
{
throw new NotImplementedException();
}
public IRenderTargetBitmapImpl CreateRenderTargetBitmap(int width, int height)
{
throw new NotImplementedException();
}
public IStreamGeometryImpl CreateStreamGeometry()
{
return new MockStreamGeometry();
}
public IBitmapImpl LoadBitmap(Stream stream)
{
throw new NotImplementedException();
}
public IBitmapImpl LoadBitmap(string fileName)
{
throw new NotImplementedException();
}
class MockStreamGeometry : Avalonia.Platform.IStreamGeometryImpl
{
private MockStreamGeometryContext _impl = new MockStreamGeometryContext();
public Rect Bounds
{
get
{
throw new NotImplementedException();
}
}
public Matrix Transform
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public IStreamGeometryImpl Clone()
{
return this;
}
public bool FillContains(Point point)
{
return _impl.FillContains(point);
}
public Rect GetRenderBounds(double strokeThickness)
{
throw new NotImplementedException();
}
public IStreamGeometryContextImpl Open()
{
return _impl;
}
class MockStreamGeometryContext : IStreamGeometryContextImpl
{
private List<Point> points = new List<Point>();
public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection)
{
throw new NotImplementedException();
}
public void BeginFigure(Point startPoint, bool isFilled)
{
points.Add(startPoint);
}
public void CubicBezierTo(Point point1, Point point2, Point point3)
{
throw new NotImplementedException();
}
public void Dispose()
{
}
public void EndFigure(bool isClosed)
{
}
public void LineTo(Point point)
{
points.Add(point);
}
public void QuadraticBezierTo(Point control, Point endPoint)
{
throw new NotImplementedException();
}
public void SetFillRule(FillRule fillRule)
{
}
public bool FillContains(Point point)
{
// Use the algorithm from http://www.blackpawn.com/texts/pointinpoly/default.html
// to determine if the point is in the geometry (since it will always be convex in this situation)
for (int i = 0; i < points.Count; i++)
{
var a = points[i];
var b = points[(i + 1) % points.Count];
var c = points[(i + 2) % points.Count];
Vector v0 = c - a;
Vector v1 = b - a;
Vector v2 = point - a;
var dot00 = v0 * v0;
var dot01 = v0 * v1;
var dot02 = v0 * v2;
var dot11 = v1 * v1;
var dot12 = v1 * v2;
var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
if ((u >= 0) && (v >= 0) && (u + v < 1)) return true;
}
return false;
}
}
}
}
}
}
| |
// InstallerTest.cs
// NUnit Test Cases for System.Configuration.Install.Installer class
//
// Author:
// Muthu Kannan (t.manki@gmail.com)
//
// (C) 2005 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 NUnit.Framework;
using System;
using System.Collections;
using System.Configuration.Install;
using System.Threading;
namespace MonoTests.System.Configuration.Install
{
[TestFixture]
public class InstallerTest {
private Installer ins;
private MyInstaller sub1, sub2;
private CallInfo BfInstEvt, AfInstEvt;
private CallInfo CommittingEvt, CommittedEvt;
private CallInfo BfRbackEvt, AfRbackEvt;
private CallInfo BfUninsEvt, AfUninsEvt;
private Hashtable state;
[SetUp]
public void SetUp ()
{
ins = new Installer ();
state = new Hashtable ();
sub1 = new MyInstaller ();
sub2 = new MyInstaller ();
BfInstEvt = new CallInfo ();
AfInstEvt = new CallInfo ();
CommittingEvt = new CallInfo ();
CommittedEvt = new CallInfo ();
BfRbackEvt = new CallInfo ();
AfRbackEvt = new CallInfo ();
BfUninsEvt = new CallInfo ();
AfUninsEvt = new CallInfo ();;
ins.Installers.Add (sub1);
ins.Installers.Add (sub2);
ins.BeforeInstall += new InstallEventHandler (onBeforeInstall);
ins.AfterInstall += new InstallEventHandler (onAfterInstall);
ins.Committing += new InstallEventHandler (onCommitting);
ins.Committed += new InstallEventHandler (onCommitted);
ins.BeforeRollback += new InstallEventHandler (onBeforeRollback);
ins.AfterRollback += new InstallEventHandler (onAfterRollback);
ins.BeforeUninstall += new InstallEventHandler (onBeforeUninstall);
ins.AfterUninstall += new InstallEventHandler (onAfterUninstall);
}
// Testing Install method with invalid argument
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TestInstall01 ()
{
ins.Install (null);
}
// Testing Install method
[Test]
public void TestInstall02 ()
{
ins.Install (state);
Assert.IsTrue (sub1.ciInstall.methodCalled, "#INSTaa01");
Assert.IsFalse (sub1.ciCommit.methodCalled, "#INSTaa02");
Assert.IsFalse (sub1.ciRollback.methodCalled, "#INSTaa03");
Assert.IsFalse (sub1.ciUninstall.methodCalled, "#INSTaa04");
Assert.IsTrue (sub2.ciInstall.methodCalled, "#INSTaa05");
Assert.IsFalse (sub2.ciCommit.methodCalled, "#INSTaa06");
Assert.IsFalse (sub2.ciRollback.methodCalled, "#INSTaa07");
Assert.IsFalse (sub2.ciUninstall.methodCalled, "#INSTaa08");
Assert.IsTrue (sub1.ciInstall.timeOfCall > BfInstEvt.timeOfCall,
"#INSTaa09");
Assert.IsTrue (sub2.ciInstall.timeOfCall > BfInstEvt.timeOfCall,
"#INSTaa10");
Assert.IsTrue (sub1.ciInstall.timeOfCall < AfInstEvt.timeOfCall,
"#INSTaa11");
Assert.IsTrue (sub2.ciInstall.timeOfCall < AfInstEvt.timeOfCall,
"#INSTaa12");
}
// Testing Commit method with null argument
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TestCommit01 ()
{
ins.Commit (null);
}
// Testing Commit method with empty hashtable argument
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TestCommit02 ()
{
ins.Commit (state);
}
// Testing Commit with proper arguments
[Test]
public void TestCommit03 ()
{
TestInstall02 (); // Call Install method so that
// state hash table is prepared
ins.Commit (state);
/*
Assert.IsTrue (sub1.ciInstall.methodCalled, "#INSTab01");
Assert.IsTrue (sub1.ciCommit.methodCalled, "#INSTab02");
Assert.IsFalse (sub1.ciRollback.methodCalled, "#INSTab03");
Assert.IsFalse (sub1.ciUninstall.methodCalled, "#INSTab04");
Assert.IsTrue (sub2.ciInstall.methodCalled, "#INSTab05");
Assert.IsTrue (sub2.ciCommit.methodCalled, "#INSTab06");
Assert.IsFalse (sub2.ciRollback.methodCalled, "#INSTab07");
Assert.IsFalse (sub2.ciUninstall.methodCalled, "#INSTab08");
Assert.IsTrue (sub1.ciCommit.timeOfCall > CommittingEvt.timeOfCall,
"#INSTab09");
Assert.IsTrue (sub2.ciCommit.timeOfCall > CommittingEvt.timeOfCall,
"#INSTab10");
Assert.IsTrue (sub1.ciCommit.timeOfCall < CommittedEvt.timeOfCall,
"#INSTab11");
Assert.IsTrue (sub2.ciCommit.timeOfCall < CommittedEvt.timeOfCall,
"#INSTab12");
*/
}
// Testing Rollback method with null argument
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TestRollback01 ()
{
ins.Rollback (null);
}
// Testing Rollback method with empty hashtable argument
[Test]
[ExpectedException (typeof (ArgumentException))]
public void TestRollback02 ()
{
ins.Rollback (state);
}
// Testing Rollback with proper arguments
[Test]
public void TestRollback03 ()
{
TestInstall02 (); // Call Install method so that
// state hash table is prepared
ins.Rollback (state);
Assert.IsTrue (sub1.ciInstall.methodCalled, "#INSTac01");
Assert.IsFalse (sub1.ciCommit.methodCalled, "#INSTac02");
Assert.IsTrue (sub1.ciRollback.methodCalled, "#INSTac03");
Assert.IsFalse (sub1.ciUninstall.methodCalled, "#INSTac04");
Assert.IsTrue (sub2.ciInstall.methodCalled, "#INSTac05");
Assert.IsFalse (sub2.ciCommit.methodCalled, "#INSTac06");
Assert.IsTrue (sub2.ciRollback.methodCalled, "#INSTac07");
Assert.IsFalse (sub2.ciUninstall.methodCalled, "#INSTac08");
Assert.IsTrue (sub1.ciRollback.timeOfCall > BfRbackEvt.timeOfCall,
"#INSTac09");
Assert.IsTrue (sub2.ciRollback.timeOfCall > BfRbackEvt.timeOfCall,
"#INSTac10");
Assert.IsTrue (sub1.ciRollback.timeOfCall < AfRbackEvt.timeOfCall,
"#INSTac11");
Assert.IsTrue (sub2.ciRollback.timeOfCall < AfRbackEvt.timeOfCall,
"#INSTac12");
}
// Testing Uninstall method with proper argument
[Test]
public void TestUninstall01 ()
{
TestInstall02 (); // Call Install method so that
// state hash table is prepared
ins.Uninstall (state);
Assert.IsTrue (sub1.ciInstall.methodCalled, "#INSTad01");
Assert.IsFalse (sub1.ciCommit.methodCalled, "#INSTad02");
Assert.IsFalse (sub1.ciRollback.methodCalled, "#INSTad03");
Assert.IsTrue (sub1.ciUninstall.methodCalled, "#INSTad04");
Assert.IsTrue (sub2.ciInstall.methodCalled, "#INSTad05");
Assert.IsFalse (sub2.ciCommit.methodCalled, "#INSTad06");
Assert.IsFalse (sub2.ciRollback.methodCalled, "#INSTad07");
Assert.IsTrue (sub2.ciUninstall.methodCalled, "#INSTad08");
Assert.IsTrue (sub1.ciUninstall.timeOfCall > BfUninsEvt.timeOfCall,
"#INSTad09");
Assert.IsTrue (sub2.ciUninstall.timeOfCall > BfUninsEvt.timeOfCall,
"#INSTad10");
Assert.IsTrue (sub1.ciUninstall.timeOfCall < AfUninsEvt.timeOfCall,
"#INSTad11");
Assert.IsTrue (sub2.ciUninstall.timeOfCall < AfUninsEvt.timeOfCall,
"#INSTad12");
}
// Testing Parent property
[Test]
public void TestParent01 ()
{
Assert.AreEqual (ins, sub1.Parent, "#INSTae01");
Assert.AreEqual (ins, sub2.Parent, "#INSTae02");
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void TestParent02 ()
{
ins.Parent = sub1;
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void TestParent03 ()
{
Installer ins1 = new Installer ();
sub1.Installers.Add (ins1);
ins.Parent = ins1;
}
[Test]
[ExpectedException (typeof (InvalidOperationException))]
public void TestParent04 ()
{
Installer ins1 = new Installer ();
Installer ins2 = new Installer ();
ins1.Installers.Add (ins2);
sub1.Installers.Add (ins1);
ins.Parent = ins1;
}
private void onBeforeInstall (object sender, InstallEventArgs e)
{
BfInstEvt.SetCalled ();
}
private void onAfterInstall (object sender, InstallEventArgs e)
{
AfInstEvt.SetCalled ();
}
private void onCommitting (object sender, InstallEventArgs e)
{
CommittingEvt.SetCalled ();
}
private void onCommitted (object sender, InstallEventArgs e)
{
CommittedEvt.SetCalled ();
}
private void onBeforeRollback (object sender, InstallEventArgs e)
{
BfRbackEvt.SetCalled ();
}
private void onAfterRollback (object sender, InstallEventArgs e)
{
AfRbackEvt.SetCalled ();
}
private void onBeforeUninstall (object sender, InstallEventArgs e)
{
BfUninsEvt.SetCalled ();
}
private void onAfterUninstall (object sender, InstallEventArgs e)
{
AfUninsEvt.SetCalled ();
}
private struct CallInfo
{
public bool methodCalled;
public DateTime timeOfCall;
private const int SLEEP_TIME = 60; // waiting time in ms
public void SetCalled ()
{
methodCalled = true;
// Wait for some time so that time comparison is effective
Thread.Sleep (SLEEP_TIME);
timeOfCall = DateTime.Now;
}
}
// This is a custom installer base class
private class MyInstaller : Installer {
public CallInfo ciInstall;
public CallInfo ciCommit;
public CallInfo ciRollback;
public CallInfo ciUninstall;
public MyInstaller ()
{
ciInstall = new CallInfo ();
ciCommit = new CallInfo ();
ciRollback = new CallInfo ();
ciUninstall = new CallInfo ();
}
public override void Install (IDictionary state)
{
base.Install (state);
ciInstall.SetCalled ();
}
public override void Commit (IDictionary state)
{
base.Commit (state);
ciCommit.SetCalled ();
}
public override void Rollback (IDictionary state)
{
base.Rollback (state);
ciRollback.SetCalled ();
}
public override void Uninstall (IDictionary state)
{
base.Uninstall (state);
ciUninstall.SetCalled ();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.IO
{
/// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
internal sealed partial class UnixFileSystem : FileSystem
{
public override int MaxPath { get { return Interop.Sys.MaxPath; } }
public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } }
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);
}
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
// The destination path may just be a directory into which the file should be copied.
// If it is, append the filename from the source onto the destination directory
if (DirectoryExists(destFullPath))
{
destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
}
// Copy the contents of the file from the source to the destination, creating the destination in the process
using (var src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None))
using (var dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, FileStream.DefaultBufferSize, FileOptions.None))
{
Interop.CheckIo(Interop.Sys.CopyFile(src.SafeFileHandle, dst.SafeFileHandle));
}
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
// The desired behavior for Move(source, dest) is to not overwrite the destination file
// if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,
// link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move
// as a Creation and Deletion instead of a Rename and thus differ from Windows.
if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)
{
// If link fails, we can fall back to doing a full copy, but we'll only do so for
// cases where we expect link could fail but such a copy could succeed. We don't
// want to do so for all errors, because the copy could incur a lot of cost
// even if we know it'll eventually fail, e.g. EROFS means that the source file
// system is read-only and couldn't support the link being added, but if it's
// read-only, then the move should fail any way due to an inability to delete
// the source file.
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EXDEV || // rename fails across devices / mount points
errorInfo.Error == Interop.Error.EPERM || // permissions might not allow creating hard links even if a copy would work
errorInfo.Error == Interop.Error.EOPNOTSUPP || // links aren't supported by the source file system
errorInfo.Error == Interop.Error.EMLINK) // too many hard links to the source file
{
CopyFile(sourceFullPath, destFullPath, overwrite: false);
}
else
{
// The operation failed. Within reason, try to determine which path caused the problem
// so we can throw a detailed exception.
string path = null;
bool isDirectory = false;
if (errorInfo.Error == Interop.Error.ENOENT)
{
if (!Directory.Exists(Path.GetDirectoryName(destFullPath)))
{
// The parent directory of destFile can't be found.
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
path = destFullPath;
isDirectory = true;
}
else
{
path = sourceFullPath;
}
}
else if (errorInfo.Error == Interop.Error.EEXIST)
{
path = destFullPath;
}
throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory);
}
}
DeleteFile(sourceFullPath);
}
public override void DeleteFile(string fullPath)
{
if (Interop.Sys.Unlink(fullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// ENOENT means it already doesn't exist; nop
if (errorInfo.Error != Interop.Error.ENOENT)
{
if (errorInfo.Error == Interop.Error.EISDIR)
errorInfo = Interop.Error.EACCES.Info();
throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);
}
}
}
public override void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
{
length--;
}
// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
}
// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
{
return;
}
// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
Stack<string> stackDir = new Stack<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
string dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
{
stackDir.Push(dir);
}
else
{
somepathexists = true;
}
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
{
i--;
}
i--;
}
}
int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
string root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
return;
}
// Create all the directories
int result = 0;
Interop.ErrorInfo firstError = default(Interop.ErrorInfo);
string errorString = fullPath;
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
if (name.Length >= MaxDirectoryPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
// The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally).
// We do the same.
result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask);
if (result < 0 && firstError.Error == 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errorInfo.Error != Interop.Error.EEXIST)
{
firstError = errorInfo;
}
else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errorInfo;
errorString = name;
}
}
}
// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError.Error != 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
}
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES: // match Win32 exception
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno);
default:
throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true);
}
}
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
var di = new DirectoryInfo(fullPath);
if (!di.Exists)
{
throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);
}
RemoveDirectoryInternal(di, recursive, throwOnTopLevelDirectoryNotFound: true);
}
private void RemoveDirectoryInternal(DirectoryInfo directory, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
Exception firstException = null;
if ((directory.Attributes & FileAttributes.ReparsePoint) != 0)
{
DeleteFile(directory.FullName);
return;
}
if (recursive)
{
try
{
foreach (string item in EnumeratePaths(directory.FullName, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
{
if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
{
try
{
var childDirectory = new DirectoryInfo(item);
if (childDirectory.Exists)
{
RemoveDirectoryInternal(childDirectory, recursive, throwOnTopLevelDirectoryNotFound: false);
}
else
{
DeleteFile(item);
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
}
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
if (firstException != null)
{
throw firstException;
}
}
if (Interop.Sys.RmDir(directory.FullName) < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
switch (errorInfo.Error)
{
case Interop.Error.EACCES:
case Interop.Error.EPERM:
case Interop.Error.EROFS:
case Interop.Error.EISDIR:
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, directory.FullName)); // match Win32 exception
case Interop.Error.ENOENT:
if (!throwOnTopLevelDirectoryNotFound)
{
return;
}
goto default;
default:
throw Interop.GetExceptionForIoErrno(errorInfo, directory.FullName, isDirectory: true);
}
}
}
public override bool DirectoryExists(string fullPath)
{
Interop.ErrorInfo ignored;
return DirectoryExists(fullPath, out ignored);
}
private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo)
{
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo);
}
public override bool FileExists(string fullPath)
{
Interop.ErrorInfo ignored;
return FileExists(fullPath, Interop.Sys.FileTypes.S_IFREG, out ignored);
}
private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo)
{
Debug.Assert(fileType == Interop.Sys.FileTypes.S_IFREG || fileType == Interop.Sys.FileTypes.S_IFDIR);
Interop.Sys.FileStatus fileinfo;
errorInfo = default(Interop.ErrorInfo);
// First use stat, as we want to follow symlinks. If that fails, it could be because the symlink
// is broken, we don't have permissions, etc., in which case fall back to using LStat to evaluate
// based on the symlink itself.
if (Interop.Sys.Stat(fullPath, out fileinfo) < 0 &&
Interop.Sys.LStat(fullPath, out fileinfo) < 0)
{
errorInfo = Interop.Sys.GetLastErrorInfo();
return false;
}
// Something exists at this path. If the caller is asking for a directory, return true if it's
// a directory and false for everything else. If the caller is asking for a file, return false for
// a directory and true for everything else.
return
(fileType == Interop.Sys.FileTypes.S_IFDIR) ==
((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR);
}
public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Files:
return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new FileInfo(path, null));
case SearchTarget.Directories:
return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new DirectoryInfo(path, null));
default:
return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?
(FileSystemInfo)new DirectoryInfo(path, null) :
(FileSystemInfo)new FileInfo(path, null));
}
}
private sealed class FileSystemEnumerable<T> : IEnumerable<T>
{
private readonly PathPair _initialDirectory;
private readonly string _searchPattern;
private readonly SearchOption _searchOption;
private readonly bool _includeFiles;
private readonly bool _includeDirectories;
private readonly Func<string, bool, T> _translateResult;
private IEnumerator<T> _firstEnumerator;
internal FileSystemEnumerable(
string userPath, string searchPattern,
SearchOption searchOption, SearchTarget searchTarget,
Func<string, bool, T> translateResult)
{
// Basic validation of the input path
if (userPath == null)
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrWhiteSpace(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
// Validate and normalize the search pattern. If after doing so it's empty,
// matching Win32 behavior we can skip all additional validation and effectively
// return an empty enumerable.
searchPattern = NormalizeSearchPattern(searchPattern);
if (searchPattern.Length > 0)
{
PathHelpers.CheckSearchPattern(searchPattern);
PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);
// If the search pattern contains any paths, make sure we factor those into
// the user path, and then trim them off.
int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (lastSlash >= 0)
{
if (lastSlash >= 1)
{
userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));
}
searchPattern = searchPattern.Substring(lastSlash + 1);
}
string fullPath = Path.GetFullPath(userPath);
// Store everything for the enumerator
_initialDirectory = new PathPair(userPath, fullPath);
_searchPattern = searchPattern;
_searchOption = searchOption;
_includeFiles = (searchTarget & SearchTarget.Files) != 0;
_includeDirectories = (searchTarget & SearchTarget.Directories) != 0;
_translateResult = translateResult;
}
// Open the first enumerator so that any errors are propagated synchronously.
_firstEnumerator = Enumerate();
}
public IEnumerator<T> GetEnumerator()
{
return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private IEnumerator<T> Enumerate()
{
return Enumerate(
_initialDirectory.FullPath != null ?
OpenDirectory(_initialDirectory.FullPath) :
null);
}
private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle)
{
if (dirHandle == null)
{
// Empty search
yield break;
}
Debug.Assert(!dirHandle.IsInvalid);
Debug.Assert(!dirHandle.IsClosed);
// Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories
// Lazily-initialized only if we find subdirectories that will be explored.
Stack<PathPair> toExplore = null;
PathPair dirPath = _initialDirectory;
while (dirHandle != null)
{
try
{
// Read each entry from the enumerator
Interop.Sys.DirectoryEntry dirent;
while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0)
{
// Get from the dir entry whether the entry is a file or directory.
// We classify everything as a file unless we know it to be a directory.
bool isDir;
if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR)
{
// We know it's a directory.
isDir = true;
}
else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN)
{
// It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
// If we can't (e.g. symlink to a file, broken symlink, etc.), we'll just treat it as a file.
Interop.ErrorInfo errnoIgnored;
isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored);
}
else
{
// Otherwise, treat it as a file. This includes regular files, FIFOs, etc.
isDir = false;
}
// Yield the result if the user has asked for it. In the case of directories,
// always explore it by pushing it onto the stack, regardless of whether
// we're returning directories.
if (isDir)
{
if (!ShouldIgnoreDirectory(dirent.InodeName))
{
string userPath = null;
if (_searchOption == SearchOption.AllDirectories)
{
if (toExplore == null)
{
toExplore = new Stack<PathPair>();
}
userPath = Path.Combine(dirPath.UserPath, dirent.InodeName);
toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName)));
}
if (_includeDirectories &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true);
}
}
}
else if (_includeFiles &&
Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false);
}
}
}
finally
{
// Close the directory enumerator
dirHandle.Dispose();
dirHandle = null;
}
if (toExplore != null && toExplore.Count > 0)
{
// Open the next directory.
dirPath = toExplore.Pop();
dirHandle = OpenDirectory(dirPath.FullPath);
}
}
}
private static string NormalizeSearchPattern(string searchPattern)
{
if (searchPattern == "." || searchPattern == "*.*")
{
searchPattern = "*";
}
else if (PathHelpers.EndsInDirectorySeparator(searchPattern))
{
searchPattern += "*";
}
return searchPattern;
}
private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath)
{
Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath);
if (handle.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true);
}
return handle;
}
}
/// <summary>Determines whether the specified directory name should be ignored.</summary>
/// <param name="name">The name to evaluate.</param>
/// <returns>true if the name is "." or ".."; otherwise, false.</returns>
private static bool ShouldIgnoreDirectory(string name)
{
return name == "." || name == "..";
}
public override string GetCurrentDirectory()
{
return Interop.Sys.GetCwd();
}
public override void SetCurrentDirectory(string fullPath)
{
Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath, isDirectory:true);
}
public override FileAttributes GetAttributes(string fullPath)
{
return new FileInfo(fullPath, null).Attributes;
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
new FileInfo(fullPath, null).Attributes = attributes;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return new FileInfo(fullPath, null).CreationTime;
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.CreationTime = time;
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return new FileInfo(fullPath, null).LastAccessTime;
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastAccessTime = time;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return new FileInfo(fullPath, null).LastWriteTime;
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
IFileSystemObject info = asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
info.LastWriteTime = time;
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return asDirectory ?
(IFileSystemObject)new DirectoryInfo(fullPath, null) :
(IFileSystemObject)new FileInfo(fullPath, null);
}
}
}
| |
// 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.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Identity.Core;
namespace Microsoft.AspNetCore.Identity
{
/// <summary>
/// Helper functions for configuring identity services.
/// </summary>
public class IdentityBuilder
{
/// <summary>
/// Creates a new instance of <see cref="IdentityBuilder"/>.
/// </summary>
/// <param name="user">The <see cref="Type"/> to use for the users.</param>
/// <param name="services">The <see cref="IServiceCollection"/> to attach to.</param>
public IdentityBuilder(Type user, IServiceCollection services)
{
UserType = user;
Services = services;
}
/// <summary>
/// Creates a new instance of <see cref="IdentityBuilder"/>.
/// </summary>
/// <param name="user">The <see cref="Type"/> to use for the users.</param>
/// <param name="role">The <see cref="Type"/> to use for the roles.</param>
/// <param name="services">The <see cref="IServiceCollection"/> to attach to.</param>
public IdentityBuilder(Type user, Type role, IServiceCollection services) : this(user, services)
=> RoleType = role;
/// <summary>
/// Gets the <see cref="Type"/> used for users.
/// </summary>
/// <value>
/// The <see cref="Type"/> used for users.
/// </value>
public Type UserType { get; private set; }
/// <summary>
/// Gets the <see cref="Type"/> used for roles.
/// </summary>
/// <value>
/// The <see cref="Type"/> used for roles.
/// </value>
public Type RoleType { get; private set; }
/// <summary>
/// Gets the <see cref="IServiceCollection"/> services are attached to.
/// </summary>
/// <value>
/// The <see cref="IServiceCollection"/> services are attached to.
/// </value>
public IServiceCollection Services { get; private set; }
private IdentityBuilder AddScoped(Type serviceType, Type concreteType)
{
Services.AddScoped(serviceType, concreteType);
return this;
}
/// <summary>
/// Adds an <see cref="IUserValidator{TUser}"/> for the <see cref="UserType"/>.
/// </summary>
/// <typeparam name="TValidator">The user validator type.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddUserValidator<TValidator>() where TValidator : class
=> AddScoped(typeof(IUserValidator<>).MakeGenericType(UserType), typeof(TValidator));
/// <summary>
/// Adds an <see cref="IUserClaimsPrincipalFactory{TUser}"/> for the <see cref="UserType"/>.
/// </summary>
/// <typeparam name="TFactory">The type of the claims principal factory.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddClaimsPrincipalFactory<TFactory>() where TFactory : class
=> AddScoped(typeof(IUserClaimsPrincipalFactory<>).MakeGenericType(UserType), typeof(TFactory));
/// <summary>
/// Adds an <see cref="IdentityErrorDescriber"/>.
/// </summary>
/// <typeparam name="TDescriber">The type of the error describer.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddErrorDescriber<TDescriber>() where TDescriber : IdentityErrorDescriber
{
Services.AddScoped<IdentityErrorDescriber, TDescriber>();
return this;
}
/// <summary>
/// Adds an <see cref="IPasswordValidator{TUser}"/> for the <see cref="UserType"/>.
/// </summary>
/// <typeparam name="TValidator">The validator type used to validate passwords.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddPasswordValidator<TValidator>() where TValidator : class
=> AddScoped(typeof(IPasswordValidator<>).MakeGenericType(UserType), typeof(TValidator));
/// <summary>
/// Adds an <see cref="IUserStore{TUser}"/> for the <see cref="UserType"/>.
/// </summary>
/// <typeparam name="TStore">The user store type.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddUserStore<TStore>() where TStore : class
=> AddScoped(typeof(IUserStore<>).MakeGenericType(UserType), typeof(TStore));
/// <summary>
/// Adds a token provider.
/// </summary>
/// <typeparam name="TProvider">The type of the token provider to add.</typeparam>
/// <param name="providerName">The name of the provider to add.</param>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddTokenProvider<TProvider>(string providerName) where TProvider : class
=> AddTokenProvider(providerName, typeof(TProvider));
/// <summary>
/// Adds a token provider for the <see cref="UserType"/>.
/// </summary>
/// <param name="providerName">The name of the provider to add.</param>
/// <param name="provider">The type of the <see cref="IUserTwoFactorTokenProvider{TUser}"/> to add.</param>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddTokenProvider(string providerName, Type provider)
{
if (!typeof(IUserTwoFactorTokenProvider<>).MakeGenericType(UserType).IsAssignableFrom(provider))
{
throw new InvalidOperationException(Resources.FormatInvalidManagerType(provider.Name, "IUserTwoFactorTokenProvider", UserType.Name));
}
Services.Configure<IdentityOptions>(options =>
{
options.Tokens.ProviderMap[providerName] = new TokenProviderDescriptor(provider);
});
Services.AddTransient(provider);
return this;
}
/// <summary>
/// Adds a <see cref="UserManager{TUser}"/> for the <see cref="UserType"/>.
/// </summary>
/// <typeparam name="TUserManager">The type of the user manager to add.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddUserManager<TUserManager>() where TUserManager : class
{
var userManagerType = typeof(UserManager<>).MakeGenericType(UserType);
var customType = typeof(TUserManager);
if (!userManagerType.IsAssignableFrom(customType))
{
throw new InvalidOperationException(Resources.FormatInvalidManagerType(customType.Name, "UserManager", UserType.Name));
}
if (userManagerType != customType)
{
Services.AddScoped(customType, services => services.GetRequiredService(userManagerType));
}
return AddScoped(userManagerType, customType);
}
/// <summary>
/// Adds Role related services for TRole, including IRoleStore, IRoleValidator, and RoleManager.
/// </summary>
/// <typeparam name="TRole">The role type.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddRoles<TRole>() where TRole : class
{
RoleType = typeof(TRole);
AddRoleValidator<RoleValidator<TRole>>();
Services.TryAddScoped<RoleManager<TRole>>();
Services.AddScoped(typeof(IUserClaimsPrincipalFactory<>).MakeGenericType(UserType), typeof(UserClaimsPrincipalFactory<,>).MakeGenericType(UserType, RoleType));
return this;
}
/// <summary>
/// Adds an <see cref="IRoleValidator{TRole}"/> for the <see cref="RoleType"/>.
/// </summary>
/// <typeparam name="TRole">The role validator type.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddRoleValidator<TRole>() where TRole : class
{
if (RoleType == null)
{
throw new InvalidOperationException(Resources.NoRoleType);
}
return AddScoped(typeof(IRoleValidator<>).MakeGenericType(RoleType), typeof(TRole));
}
/// <summary>
/// Adds an <see cref="ILookupProtector"/> and <see cref="ILookupProtectorKeyRing"/>.
/// </summary>
/// <typeparam name="TProtector">The personal data protector type.</typeparam>
/// <typeparam name="TKeyRing">The personal data protector key ring type.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddPersonalDataProtection<TProtector, TKeyRing>()
where TProtector : class,ILookupProtector
where TKeyRing : class, ILookupProtectorKeyRing
{
Services.AddSingleton<IPersonalDataProtector, DefaultPersonalDataProtector>();
Services.AddSingleton<ILookupProtector, TProtector>();
Services.AddSingleton<ILookupProtectorKeyRing, TKeyRing>();
return this;
}
/// <summary>
/// Adds a <see cref="IRoleStore{TRole}"/> for the <see cref="RoleType"/>.
/// </summary>
/// <typeparam name="TStore">The role store.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddRoleStore<TStore>() where TStore : class
{
if (RoleType == null)
{
throw new InvalidOperationException(Resources.NoRoleType);
}
return AddScoped(typeof(IRoleStore<>).MakeGenericType(RoleType), typeof(TStore));
}
/// <summary>
/// Adds a <see cref="RoleManager{TRole}"/> for the <see cref="RoleType"/>.
/// </summary>
/// <typeparam name="TRoleManager">The type of the role manager to add.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddRoleManager<TRoleManager>() where TRoleManager : class
{
if (RoleType == null)
{
throw new InvalidOperationException(Resources.NoRoleType);
}
var managerType = typeof(RoleManager<>).MakeGenericType(RoleType);
var customType = typeof(TRoleManager);
if (!managerType.IsAssignableFrom(customType))
{
throw new InvalidOperationException(Resources.FormatInvalidManagerType(customType.Name, "RoleManager", RoleType.Name));
}
if (managerType != customType)
{
Services.AddScoped(typeof(TRoleManager), services => services.GetRequiredService(managerType));
}
return AddScoped(managerType, typeof(TRoleManager));
}
/// <summary>
/// Adds a <see cref="IUserConfirmation{TUser}"/> for the <seealso cref="UserType"/>.
/// </summary>
/// <typeparam name="TUserConfirmation">The type of the user confirmation to add.</typeparam>
/// <returns>The current <see cref="IdentityBuilder"/> instance.</returns>
public virtual IdentityBuilder AddUserConfirmation<TUserConfirmation>() where TUserConfirmation : class
=> AddScoped(typeof(IUserConfirmation<>).MakeGenericType(UserType), typeof(TUserConfirmation));
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models;
using Microsoft.Rest.Azure;
using Newtonsoft.Json;
namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
public static class SiteRecoveryMapperExtension
{
public static IMappingExpression<TSource, TDestination> ForItems<TSource, TDestination, T>(
this IMappingExpression<TSource, TDestination> mapper) where TSource : IEnumerable
where TDestination : ICollection<T>
{
mapper.AfterMap(
(
c,
s) =>
{
if ((c != null) &&
(s != null))
{
foreach (var t in c)
{
s.Add(Mapper.Map<T>(t));
}
}
});
return mapper;
}
}
public class SiteRecoveryAutoMapperProfile : AutoMapper.Profile
{
private static IMapper _mapper;
private static readonly object _lock = new object();
public static IMapper Mapper
{
get
{
lock (_lock)
{
if (_mapper == null)
{
Initialize();
}
return _mapper;
}
}
}
public override string ProfileName => "SiteRecoveryAutoMapperProfile";
private static void Initialize()
{
var config = new MapperConfiguration(cfg =>
{
var mappingExpression = cfg
.CreateMap<Rest.Azure.AzureOperationResponse, PSSiteRecoveryLongRunningOperation>();
mappingExpression.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionFabric = cfg
.CreateMap<AzureOperationResponse<Fabric>, PSSiteRecoveryLongRunningOperation>();
mappingExpressionFabric.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionPolicy = cfg
.CreateMap<AzureOperationResponse<Policy>, PSSiteRecoveryLongRunningOperation>();
mappingExpressionPolicy.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionProtectionContainer = cfg
.CreateMap<AzureOperationResponse<ProtectionContainer>,
PSSiteRecoveryLongRunningOperation>();
mappingExpressionProtectionContainer.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionProtectableItem = cfg
.CreateMap<AzureOperationResponse<ProtectableItem>,
PSSiteRecoveryLongRunningOperation>();
mappingExpressionProtectableItem.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionReplicationProtectedItem = cfg
.CreateMap<AzureOperationResponse<ReplicationProtectedItem>,
PSSiteRecoveryLongRunningOperation>();
mappingExpressionReplicationProtectedItem.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionRecoveryPlan = cfg
.CreateMap<AzureOperationResponse<RecoveryPlan>, PSSiteRecoveryLongRunningOperation
>();
mappingExpressionRecoveryPlan.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionJob = cfg
.CreateMap<AzureOperationResponse<Job>, PSSiteRecoveryLongRunningOperation>();
mappingExpressionJob.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionProtectionContainerMapping = cfg
.CreateMap<AzureOperationResponse<ProtectionContainerMapping>,
PSSiteRecoveryLongRunningOperation>();
mappingExpressionProtectionContainerMapping.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionProtectionNetworkMapping = cfg
.CreateMap<AzureOperationResponse<NetworkMapping>,
PSSiteRecoveryLongRunningOperation>();
mappingExpressionProtectionNetworkMapping.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionProtectionStorageClassification = cfg
.CreateMap<AzureOperationResponse<StorageClassification>,
PSSiteRecoveryLongRunningOperation>();
mappingExpressionProtectionStorageClassification.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionProtectionStorageClassificationMapping = cfg
.CreateMap<AzureOperationResponse<StorageClassificationMapping>,
PSSiteRecoveryLongRunningOperation>();
mappingExpressionProtectionStorageClassificationMapping.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingExpressionvCenter = cfg
.CreateMap<AzureOperationResponse<VCenter>,
PSSiteRecoveryLongRunningOperation>();
mappingExpressionvCenter.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingAzureSiteRecoveryAlert = cfg
.CreateMap<AzureOperationResponse<Alert>,
PSSiteRecoveryLongRunningOperation>();
mappingAzureSiteRecoveryAlert.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
var mappingRecoveryServiceProvider = cfg
.CreateMap<AzureOperationResponse<RecoveryServicesProvider>,
PSSiteRecoveryLongRunningOperation>();
mappingRecoveryServiceProvider.ForMember(
c => c.Location,
o => o.MapFrom(
r => r.Response.Headers.Contains("Location")
? r.Response.Headers
.GetValues("Location")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.Status,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.Status))
.ForMember(
c => c.CorrelationRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-correlation-request-id")
? r.Response
.Headers.GetValues("x-ms-correlation-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ClientRequestId,
o => o.MapFrom(
r => r.Response.Headers.Contains("x-ms-request-id")
? r.Response.Headers
.GetValues("x-ms-request-id")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.ContentType,
o => o.MapFrom(
r => JsonConvert.DeserializeObject<PSSiteRecoveryLongRunningOperation>(
r.Response.Content.ReadAsStringAsync()
.Result)
.ContentType))
.ForMember(
c => c.RetryAfter,
o => o.MapFrom(
r => r.Response.Headers.Contains("Retry-After")
? r.Response.Headers
.GetValues("Retry-After")
.FirstOrDefault()
: null))
.ForMember(
c => c.Date,
o => o.MapFrom(
r => r.Response.Headers.Contains("Date")
? r.Response.Headers
.GetValues("Date")
.FirstOrDefault()
: string.Empty))
.ForMember(
c => c.AsyncOperation,
o => o.MapFrom(
r => r.Response.Headers.Contains("Azure-AsyncOperation")
? r.Response
.Headers.GetValues("Azure-AsyncOperation")
.FirstOrDefault()
: string.Empty));
});
_mapper = config.CreateMapper();
}
}
}
| |
// 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.Diagnostics;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
namespace System.ServiceModel.Channels
{
internal abstract class RequestContextBase : RequestContext
{
private TimeSpan _defaultSendTimeout;
private TimeSpan _defaultCloseTimeout;
private CommunicationState _state = CommunicationState.Opened;
private Message _requestMessage;
private Exception _requestMessageException;
private bool _replySent;
private bool _replyInitiated;
private bool _aborted;
private object _thisLock = new object();
protected RequestContextBase(Message requestMessage, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
{
_defaultSendTimeout = defaultSendTimeout;
_defaultCloseTimeout = defaultCloseTimeout;
_requestMessage = requestMessage;
}
public void ReInitialize(Message requestMessage)
{
_state = CommunicationState.Opened;
_requestMessageException = null;
_replySent = false;
_replyInitiated = false;
_aborted = false;
_requestMessage = requestMessage;
}
public override Message RequestMessage
{
get
{
if (_requestMessageException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_requestMessageException);
}
return _requestMessage;
}
}
protected void SetRequestMessage(Message requestMessage)
{
Fx.Assert(_requestMessageException == null, "Cannot have both a requestMessage and a requestException.");
_requestMessage = requestMessage;
}
protected void SetRequestMessage(Exception requestMessageException)
{
Fx.Assert(_requestMessage == null, "Cannot have both a requestMessage and a requestException.");
_requestMessageException = requestMessageException;
}
protected bool ReplyInitiated
{
get { return _replyInitiated; }
}
protected object ThisLock
{
get
{
return _thisLock;
}
}
public bool Aborted
{
get
{
return _aborted;
}
}
public TimeSpan DefaultCloseTimeout
{
get { return _defaultCloseTimeout; }
}
public TimeSpan DefaultSendTimeout
{
get { return _defaultSendTimeout; }
}
public override void Abort()
{
lock (ThisLock)
{
if (_state == CommunicationState.Closed)
return;
_state = CommunicationState.Closing;
_aborted = true;
}
try
{
this.OnAbort();
}
finally
{
_state = CommunicationState.Closed;
}
}
public override void Close()
{
this.Close(_defaultCloseTimeout);
}
public override void Close(TimeSpan timeout)
{
if (timeout < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("timeout", timeout, SRServiceModel.ValueMustBeNonNegative));
}
bool sendAck = false;
lock (ThisLock)
{
if (_state != CommunicationState.Opened)
return;
if (TryInitiateReply())
{
sendAck = true;
}
_state = CommunicationState.Closing;
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
bool throwing = true;
try
{
if (sendAck)
{
OnReply(null, timeoutHelper.RemainingTime());
}
OnClose(timeoutHelper.RemainingTime());
_state = CommunicationState.Closed;
throwing = false;
}
finally
{
if (throwing)
this.Abort();
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!disposing)
return;
if (_replySent)
{
this.Close();
}
else
{
this.Abort();
}
}
protected abstract void OnAbort();
protected abstract void OnClose(TimeSpan timeout);
protected abstract void OnReply(Message message, TimeSpan timeout);
protected abstract IAsyncResult OnBeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state);
protected abstract void OnEndReply(IAsyncResult result);
protected void ThrowIfInvalidReply()
{
if (_state == CommunicationState.Closed || _state == CommunicationState.Closing)
{
if (_aborted)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationObjectAbortedException(SRServiceModel.RequestContextAborted));
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
if (_replyInitiated)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.ReplyAlreadySent));
}
/// <summary>
/// Attempts to initiate the reply. If a reply is not initiated already (and the object is opened),
/// then it initiates the reply and returns true. Otherwise, it returns false.
/// </summary>
protected bool TryInitiateReply()
{
lock (_thisLock)
{
if ((_state != CommunicationState.Opened) || _replyInitiated)
{
return false;
}
else
{
_replyInitiated = true;
return true;
}
}
}
public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state)
{
return this.BeginReply(message, _defaultSendTimeout, callback, state);
}
public override IAsyncResult BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
// "null" is a valid reply (signals a 202-style "ack"), so we don't have a null-check here
lock (_thisLock)
{
this.ThrowIfInvalidReply();
_replyInitiated = true;
}
return OnBeginReply(message, timeout, callback, state);
}
public override void EndReply(IAsyncResult result)
{
OnEndReply(result);
_replySent = true;
}
public override void Reply(Message message)
{
this.Reply(message, _defaultSendTimeout);
}
public override void Reply(Message message, TimeSpan timeout)
{
// "null" is a valid reply (signals a 202-style "ack"), so we don't have a null-check here
lock (_thisLock)
{
this.ThrowIfInvalidReply();
_replyInitiated = true;
}
this.OnReply(message, timeout);
_replySent = true;
}
// This method is designed for WebSocket only, and will only be used once the WebSocket response was sent.
// For WebSocket, we never call HttpRequestContext.Reply to send the response back.
// Instead we call AcceptWebSocket directly. So we need to set the replyInitiated and
// replySent boolean to be true once the response was sent successfully. Otherwise when we
// are disposing the HttpRequestContext, we will see a bunch of warnings in trace log.
protected void SetReplySent()
{
lock (_thisLock)
{
this.ThrowIfInvalidReply();
_replyInitiated = true;
}
_replySent = true;
}
}
internal class RequestContextMessageProperty : IDisposable
{
private RequestContext _context;
private object _thisLock = new object();
public RequestContextMessageProperty(RequestContext context)
{
_context = context;
}
public static string Name
{
get { return "requestContext"; }
}
void IDisposable.Dispose()
{
bool success = false;
RequestContext thisContext;
lock (_thisLock)
{
if (_context == null)
return;
thisContext = _context;
_context = null;
}
try
{
thisContext.Close();
success = true;
}
catch (CommunicationException)
{
}
catch (TimeoutException e)
{
if (WcfEventSource.Instance.CloseTimeoutIsEnabled())
{
WcfEventSource.Instance.CloseTimeout(e.Message);
}
}
finally
{
if (!success)
{
thisContext.Abort();
}
}
}
}
}
| |
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 SignNowCSharpExample.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.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
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;
}
}
}
| |
//
// Error.cs
//
// Author:
// Scott Thomas <lunchtimemama@gmail.com>
//
// Copyright (c) 2010 Scott Thomas
//
// 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 Mono.Upnp.Control;
using Mono.Upnp.Internal;
namespace Mono.Upnp.Dcp.MediaServer1
{
public static class Error
{
public static UpnpError NoSuchObject ()
{
return NoSuchObject (null);
}
public static UpnpError NoSuchObject (string message)
{
return new UpnpError (701, Helper.MakeErrorDescription ("No such object", message));
}
public static UpnpError InvalidCurrentTagValue ()
{
return InvalidCurrentTagValue (null);
}
public static UpnpError InvalidCurrentTagValue (string message)
{
return new UpnpError (702, Helper.MakeErrorDescription ("Invalid CurrentTagValue", message));
}
public static UpnpError InvalidNewTagValue ()
{
return InvalidNewTagValue (null);
}
public static UpnpError InvalidNewTagValue (string message)
{
return new UpnpError (703, Helper.MakeErrorDescription ("Invalid NewTagValue", message));
}
public static UpnpError RequiredTag ()
{
return RequiredTag (null);
}
public static UpnpError RequiredTag (string message)
{
return new UpnpError (704, Helper.MakeErrorDescription ("Required tag", message));
}
public static UpnpError ReadOnlyTag ()
{
return ReadOnlyTag (null);
}
public static UpnpError ReadOnlyTag (string message)
{
return new UpnpError (705, Helper.MakeErrorDescription ("Read only tag", message));
}
public static UpnpError ParameterMismatch ()
{
return ParameterMismatch (null);
}
public static UpnpError ParameterMismatch (string message)
{
return new UpnpError (706, Helper.MakeErrorDescription ("Parameter mismatch", message));
}
public static UpnpError UnsupportedOrInvalidSearchCriteria ()
{
return UnsupportedOrInvalidSearchCriteria (null);
}
public static UpnpError UnsupportedOrInvalidSearchCriteria (string message)
{
return new UpnpError (708, Helper.MakeErrorDescription (
"Unsupported or invalid search criteria", message));
}
public static UpnpError UnsupportedOrInvalidSortCriteria ()
{
return UnsupportedOrInvalidSortCriteria (null);
}
public static UpnpError UnsupportedOrInvalidSortCriteria (string message)
{
return new UpnpError (709, Helper.MakeErrorDescription (
"Unsupported or invalid sort criteria", message));
}
public static UpnpError NoSuchContainer ()
{
return NoSuchContainer (null);
}
public static UpnpError NoSuchContainer (string message)
{
return new UpnpError (710, Helper.MakeErrorDescription ("No such container", message));
}
public static UpnpError RestrictedObject ()
{
return RestrictedObject (null);
}
public static UpnpError RestrictedObject (string message)
{
return new UpnpError (711, Helper.MakeErrorDescription ("Restricted object", message));
}
public static UpnpError BadMetadata ()
{
return BadMetadata (null);
}
public static UpnpError BadMetadata (string message)
{
return new UpnpError (712, Helper.MakeErrorDescription ("Bad metadata", message));
}
public static UpnpError RestrictedParentObject ()
{
return RestrictedParentObject (null);
}
public static UpnpError RestrictedParentObject (string message)
{
return new UpnpError (713, Helper.MakeErrorDescription ("Restricted parent object", message));
}
public static UpnpError NoSuchSourceResource ()
{
return NoSuchSourceResource (null);
}
public static UpnpError NoSuchSourceResource (string message)
{
return new UpnpError (714, Helper.MakeErrorDescription ("No such source resource", message));
}
public static UpnpError SourceResourceAccessDenied ()
{
return SourceResourceAccessDenied (null);
}
public static UpnpError SourceResourceAccessDenied (string message)
{
return new UpnpError (715, Helper.MakeErrorDescription ("Source resource access denied", message));
}
public static UpnpError TransferBusy ()
{
return TransferBusy (null);
}
public static UpnpError TransferBusy (string message)
{
return new UpnpError (716, Helper.MakeErrorDescription ("Transfer busy", message));
}
public static UpnpError NoSuchFileTransfer ()
{
return NoSuchFileTransfer (null);
}
public static UpnpError NoSuchFileTransfer (string message)
{
return new UpnpError (717, Helper.MakeErrorDescription ("No such file transfer", message));
}
public static UpnpError NoSuchDestinationResource ()
{
return NoSuchDestinationResource (null);
}
public static UpnpError NoSuchDestinationResource (string message)
{
return new UpnpError (718, Helper.MakeErrorDescription ("No such destination resource", message));
}
public static UpnpError DestinationResourceAccessDenied ()
{
return DestinationResourceAccessDenied (null);
}
public static UpnpError DestinationResourceAccessDenied (string message)
{
return new UpnpError (719, Helper.MakeErrorDescription ("Destination resource access denied", message));
}
public static UpnpError CannotProcessTheRequest ()
{
return CannotProcessTheRequest (null);
}
public static UpnpError CannotProcessTheRequest (string message)
{
return new UpnpError (720, Helper.MakeErrorDescription ("Cannot process the request", message));
}
}
}
| |
using Signum.Entities.Reflection;
using System.ComponentModel;
using Signum.Utilities.Reflection;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Collections.Concurrent;
namespace Signum.Entities;
[DescriptionOptions(DescriptionOptions.All), InTypeScript(false)]
public abstract class Entity : ModifiableEntity, IEntity
{
[Ignore, DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal PrimaryKey? id;
[Ignore, DebuggerBrowsable(DebuggerBrowsableState.Never), ColumnName("ToStr")]
protected internal string? toStr; //for queries and lites on entities with non-expression ToString
[HiddenProperty, Description("Id")]
public PrimaryKey Id
{
get
{
if (id == null)
throw new InvalidOperationException("{0} is new and has no Id".FormatWith(this.GetType().Name));
return id.Value;
}
internal set { id = value; } //Use SetId method to change the Id
}
[HiddenProperty]
public PrimaryKey? IdOrNull
{
get { return id; }
}
[Ignore, DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool isNew = true;
[HiddenProperty]
public bool IsNew
{
get { return isNew; }
internal set { isNew = value; }
}
[Ignore, DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal long ticks;
[HiddenProperty]
public long Ticks
{
get { return ticks; }
set { ticks = value; }
}
protected bool SetIfNew<T>(ref T field, T value, [CallerMemberName]string? automaticPropertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
if (!IsNew)
{
throw new InvalidOperationException("Attempt to modify '{0}' when the entity is not new".FormatWith(automaticPropertyName));
}
return base.Set<T>(ref field, value, automaticPropertyName!);
}
[AutoExpressionField]
public override string ToString() => As.Expression(() => BaseToString());
[AutoExpressionField]
public string BaseToString() => As.Expression(() => IsNew ? GetType().NewNiceName() : GetType().NiceName() + " " + Id);
public override bool Equals(object? obj)
{
if(obj == this)
return true;
if(obj == null)
return false;
if (obj is Entity ident && ident.GetType() == this.GetType() && this.id != null && this.id == ident.id)
return true;
return false;
}
public virtual Dictionary<Guid, IntegrityCheck>? EntityIntegrityCheck()
{
using (Mixins.OfType<CorruptMixin>().Any(c => c.Corrupt) ? Corruption.AllowScope() : null)
{
return EntityIntegrityCheckBase();
}
}
internal virtual Dictionary<Guid, IntegrityCheck>? EntityIntegrityCheckBase()
{
using (HeavyProfiler.LogNoStackTrace("EntityIntegrityCheckBase", () => GetType().Name))
return GraphExplorer.EntityIntegrityCheck(GraphExplorer.FromRootEntity(this));
}
public override int GetHashCode()
{
return id == null ?
base.GetHashCode() :
StringHashEncoder.GetHashCode32(GetType().FullName!) ^ id.Value.GetHashCode();
}
public void SetGraphErrors(IntegrityCheckException ex)
{
GraphExplorer.SetValidationErrors(GraphExplorer.FromRoot(this), ex);
}
}
[InTypeScript(false)]
public interface IEntity : IModifiableEntity, IRootEntity
{
PrimaryKey Id { get; }
[HiddenProperty]
PrimaryKey? IdOrNull { get; }
[HiddenProperty]
bool IsNew { get; }
[HiddenProperty]
string ToStringProperty { get; }
}
public interface IRootEntity
{
}
public static class UnsafeEntityExtensions
{
public static T SetId<T>(this T entity, PrimaryKey? id)
where T : Entity
{
entity.id = id;
return entity;
}
public static T SetReadonly<T, V>(this T entity, Expression<Func<T, V>> readonlyProperty, V value)
where T : ModifiableEntity
{
return SetReadonly(entity, readonlyProperty, value, true);
}
public static T SetReadonly<T, V>(this T entity, Expression<Func<T, V>> readonlyProperty, V value, bool setSelfModified)
where T : ModifiableEntity
{
var pi = ReflectionTools.BasePropertyInfo(readonlyProperty);
Action<T, V> setter = ReadonlySetterCache<T>.Setter<V>(pi);
setter(entity, value);
if (setSelfModified)
entity.SetSelfModified();
return entity;
}
static class ReadonlySetterCache<T> where T : ModifiableEntity
{
static ConcurrentDictionary<string, Delegate> cache = new ConcurrentDictionary<string, Delegate>();
internal static Action<T, V> Setter<V>(PropertyInfo pi)
{
return (Action<T, V>)cache.GetOrAdd(pi.Name, s => ReflectionTools.CreateSetter<T, V>(Reflector.FindFieldInfo(typeof(T), pi))!);
}
}
public static T SetIsNew<T>(this T entity, bool isNew = true)
where T : Entity
{
entity.IsNew = isNew;
entity.SetSelfModified();
return entity;
}
public static T SetNotModified<T>(this T mod)
where T : Modifiable
{
if (mod is Entity)
((Entity)(Modifiable)mod).IsNew = false;
mod.Modified = ModifiedState.Clean; /*Compiler bug*/
return mod;
}
public static T SetModified<T>(this T entity)
where T : Modifiable
{
entity.Modified = ModifiedState.Modified;
return entity;
}
public static T SetNotModifiedGraph<T>(this T entity, PrimaryKey id)
where T : Entity
{
foreach (var item in GraphExplorer.FromRoot(entity).Where(a => a.Modified != ModifiedState.Sealed))
{
item.SetNotModified();
if (item is Entity e && e.IdOrNull == null)
e.SetId(new PrimaryKey("invalidId"));
}
entity.SetId(id);
return entity;
}
}
public static class EntityContext
{
public static PrimaryKey EntityId(object? obj)
{
throw new InvalidOperationException("EntityContext.EntityId can only be called inside LINQ queries");
}
public static PrimaryKey? MListRowId(object? obj)
{
throw new NotImplementedException("EntityContext.MListRowId can only be called inside LINQ queries");
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Common;
using Mosa.Compiler.Framework;
using Mosa.Compiler.Linker;
using System;
using System.Diagnostics;
namespace Mosa.Platform.x86
{
/// <summary>
/// An x86 machine code emitter.
/// </summary>
public sealed class MachineCodeEmitter : BaseCodeEmitter
{
#region Code Generation
/// <summary>
/// Emits relative branch code.
/// </summary>
/// <param name="code">The branch instruction code.</param>
/// <param name="dest">The destination label.</param>
public void EmitRelativeBranch(byte[] code, int dest)
{
codeStream.Write(code, 0, code.Length);
EmitRelativeBranchTarget(dest);
}
/// <summary>
/// Calls the specified target.
/// </summary>
/// <param name="symbolOperand">The symbol operand.</param>
public void EmitCallSite(Operand symbolOperand)
{
linker.Link(
LinkType.RelativeOffset,
BuiltInPatch.I4,
MethodName,
SectionKind.Text,
(int)codeStream.Position,
-4,
symbolOperand.Name,
SectionKind.Text,
0
);
codeStream.WriteZeroBytes(4);
}
/// <summary>
/// Emits the specified op code.
/// </summary>
/// <param name="opCode">The op code.</param>
/// <param name="dest">The dest.</param>
public void Emit(OpCode opCode, Operand dest)
{
// Write the opcode
codeStream.Write(opCode.Code, 0, opCode.Code.Length);
byte? sib = null, modRM = null;
Operand displacement = null;
// Write the mod R/M byte
modRM = CalculateModRM(opCode.RegField, dest, null, out sib, out displacement);
if (modRM != null)
{
codeStream.WriteByte(modRM.Value);
if (sib.HasValue)
codeStream.WriteByte(sib.Value);
}
// Add displacement to the code
if (displacement != null)
WriteDisplacement(displacement);
}
/// <summary>
/// Emits the given code.
/// </summary>
/// <param name="opCode">The op code.</param>
/// <param name="dest">The destination operand.</param>
/// <param name="src">The source operand.</param>
public void Emit(OpCode opCode, Operand dest, Operand src)
{
// Write the opcode
codeStream.Write(opCode.Code, 0, opCode.Code.Length);
if (dest == null && src == null)
return;
byte? sib = null, modRM = null;
Operand displacement = null;
// Write the mod R/M byte
modRM = CalculateModRM(opCode.RegField, dest, src, out sib, out displacement);
if (modRM != null)
{
codeStream.WriteByte(modRM.Value);
if (sib.HasValue)
codeStream.WriteByte(sib.Value);
}
// Add displacement to the code
if (displacement != null)
WriteDisplacement(displacement);
// Add immediate bytes
if (dest.IsConstant)
WriteImmediate(dest);
else if (dest.IsSymbol)
WriteDisplacement(dest);
else if (src != null && src.IsConstant)
WriteImmediate(src);
else if (src != null && src.IsSymbol)
WriteDisplacement(src);
}
/// <summary>
/// Emits the given code.
/// </summary>
/// <param name="opCode">The op code.</param>
/// <param name="dest">The dest.</param>
/// <param name="src">The source.</param>
/// <param name="third">The third.</param>
public void Emit(OpCode opCode, Operand dest, Operand src, Operand third)
{
// Write the opcode
codeStream.Write(opCode.Code, 0, opCode.Code.Length);
if (dest == null && src == null)
return;
byte? sib = null, modRM = null;
Operand displacement = null;
// Write the mod R/M byte
modRM = CalculateModRM(opCode.RegField, dest, src, out sib, out displacement);
if (modRM != null)
{
codeStream.WriteByte(modRM.Value);
if (sib.HasValue)
codeStream.WriteByte(sib.Value);
}
// Add displacement to the code
if (displacement != null)
WriteDisplacement(displacement);
// Add immediate bytes
if (third != null && third.IsConstant)
WriteImmediate(third);
}
/// <summary>
/// Emits the displacement operand.
/// </summary>
/// <param name="displacement">The displacement operand.</param>
private void WriteDisplacement(Operand displacement)
{
if (displacement.IsLabel)
{
// FIXME! remove assertion
Debug.Assert(displacement.Displacement == 0);
linker.Link(LinkType.AbsoluteAddress, BuiltInPatch.I4, MethodName, SectionKind.Text, (int)codeStream.Position, 0, displacement.Name, SectionKind.ROData, 0);
codeStream.WriteZeroBytes(4);
}
else if (displacement.IsField)
{
SectionKind section = displacement.Field.Data != null ? section = SectionKind.ROData : section = SectionKind.BSS;
linker.Link(LinkType.AbsoluteAddress, BuiltInPatch.I4, MethodName, SectionKind.Text, (int)codeStream.Position, 0, displacement.Field.FullName, section, (int)displacement.Displacement);
codeStream.WriteZeroBytes(4);
}
else if (displacement.IsSymbol)
{
// FIXME! remove assertion
Debug.Assert(displacement.Displacement == 0);
SectionKind section = (displacement.Method != null) ? SectionKind.Text : SectionKind.ROData;
var symbol = linker.FindSymbol(displacement.Name);
if (symbol == null)
symbol = linker.GetSymbol(displacement.Name, section);
linker.Link(LinkType.AbsoluteAddress, BuiltInPatch.I4, MethodName, SectionKind.Text, (int)codeStream.Position, 0, symbol.Name, symbol.SectionKind, 0);
codeStream.WriteZeroBytes(4);
}
else if (displacement.IsMemoryAddress && displacement.OffsetBase != null && displacement.OffsetBase.IsConstant)
{
codeStream.Write((int)(displacement.OffsetBase.ConstantSignedLongInteger + displacement.Displacement), Endianness.Little);
}
else
{
codeStream.Write((int)displacement.Displacement, Endianness.Little);
}
}
/// <summary>
/// Emits an immediate operand.
/// </summary>
/// <param name="op">The immediate operand to emit.</param>
private void WriteImmediate(Operand op)
{
if (op.IsRegister)
return; // nothing to do.
if (op.IsStackLocal || op.IsMemoryAddress)
{
codeStream.Write((int)op.Displacement, Endianness.Little);
return;
}
if (!op.IsConstant)
{
throw new InvalidCompilerException();
}
if (op.IsI1)
codeStream.WriteByte((byte)op.ConstantSignedInteger);
else if (op.IsU1 || op.IsBoolean)
codeStream.WriteByte(Convert.ToByte(op.ConstantUnsignedInteger));
else if (op.IsU2 || op.IsChar)
codeStream.Write(Convert.ToUInt16(op.ConstantUnsignedInteger), Endianness.Little);
else if (op.IsI2)
codeStream.Write(Convert.ToInt16(op.ConstantSignedInteger), Endianness.Little);
else if (op.IsI4 || op.IsI)
codeStream.Write(Convert.ToInt32(op.ConstantSignedInteger), Endianness.Little);
else if (op.IsU4 || op.IsPointer || op.IsU || !op.IsValueType)
codeStream.Write(Convert.ToUInt32(op.ConstantUnsignedInteger), Endianness.Little);
else
throw new InvalidCompilerException();
}
/// <summary>
/// Emits the relative branch target.
/// </summary>
/// <param name="label">The label.</param>
private void EmitRelativeBranchTarget(int label)
{
// The relative offset of the label
int relOffset = 0;
// The position in the code stream of the label
int position;
// Did we see the label?
if (TryGetLabel(label, out position))
{
// Yes, calculate the relative offset
relOffset = (int)position - ((int)codeStream.Position + 4);
}
else
{
// Forward jump, we can't resolve yet - store a patch
AddPatch(label, (int)codeStream.Position);
}
// Emit the relative jump offset (zero if we don't know it yet!)
codeStream.Write(relOffset, Endianness.Little);
}
public override void ResolvePatches()
{
// Save the current position
long currentPosition = codeStream.Position;
foreach (var p in Patches)
{
int labelPosition;
if (!TryGetLabel(p.Label, out labelPosition))
{
throw new ArgumentException("Missing label while resolving patches.", "label=" + labelPosition.ToString());
}
codeStream.Position = p.Position;
// Compute relative branch offset
int relOffset = (int)labelPosition - ((int)p.Position + 4);
// Write relative offset to stream
var bytes = BitConverter.GetBytes(relOffset);
codeStream.Write(bytes, 0, bytes.Length);
}
// Reset the position
codeStream.Position = currentPosition;
}
/// <summary>
/// Emits a far jump to next instruction.
/// </summary>
public void EmitFarJumpToNextInstruction()
{
codeStream.WriteByte(0xEA);
linker.Link(LinkType.AbsoluteAddress, BuiltInPatch.I4, MethodName, SectionKind.Text, (int)codeStream.Position, 6, MethodName, SectionKind.Text, (int)codeStream.Position);
codeStream.WriteZeroBytes(4);
codeStream.WriteByte(0x08);
codeStream.WriteByte(0x00);
}
/// <summary>
/// Calculates the value of the modR/M byte and SIB bytes.
/// </summary>
/// <param name="regField">The modR/M regfield value.</param>
/// <param name="op1">The destination operand.</param>
/// <param name="op2">The source operand.</param>
/// <param name="sib">A potential SIB byte to emit.</param>
/// <param name="displacement">An immediate displacement to emit.</param>
/// <returns>The value of the modR/M byte.</returns>
private static byte? CalculateModRM(byte? regField, Operand op1, Operand op2, out byte? sib, out Operand displacement)
{
byte? modRM = null;
displacement = null;
// FIXME: Handle the SIB byte
sib = null;
Operand mop1 = op1 != null && op1.IsMemoryAddress ? op1 : null;
Operand mop2 = op2 != null && op2.IsMemoryAddress ? op2 : null;
bool op1IsRegister = (op1 != null) && op1.IsRegister;
bool op2IsRegister = (op2 != null) && op2.IsRegister;
// Normalize the operand order
if (!op1IsRegister && op2IsRegister)
{
// Swap the memory operands
op1 = op2;
op2 = null;
mop2 = mop1;
mop1 = null;
op1IsRegister = op2IsRegister;
op2IsRegister = false;
}
if (regField != null)
modRM = (byte)(regField.Value << 3);
if (op1IsRegister && op2IsRegister)
{
// mod = 11b, reg = rop1, r/m = rop2
modRM = (byte)((3 << 6) | (op1.Register.RegisterCode << 3) | op2.Register.RegisterCode);
}
// Check for register/memory combinations
else if (mop2 != null && mop2.EffectiveOffsetBase != null)
{
// mod = 10b, reg = rop1, r/m = mop2
modRM = (byte)(modRM.GetValueOrDefault() | (2 << 6) | (byte)mop2.EffectiveOffsetBase.RegisterCode);
if (op1 != null)
modRM |= (byte)(op1.Register.RegisterCode << 3);
displacement = mop2;
if (mop2.EffectiveOffsetBase.RegisterCode == 4)
sib = 0x24;
}
else if (mop2 != null)
{
// mod = 10b, r/m = mop1, reg = rop2
modRM = (byte)(modRM.GetValueOrDefault() | 5);
if (op1IsRegister)
modRM |= (byte)(op1.Register.RegisterCode << 3);
displacement = mop2;
}
else if (mop1 != null && mop1.EffectiveOffsetBase != null)
{
// mod = 10b, r/m = mop1, reg = rop2
modRM = (byte)(modRM.GetValueOrDefault() | (2 << 6) | mop1.EffectiveOffsetBase.RegisterCode);
if (op2IsRegister)
modRM |= (byte)(op2.Register.RegisterCode << 3);
displacement = mop1;
if (mop1.EffectiveOffsetBase.RegisterCode == 4)
sib = 0xA4;
}
else if (mop1 != null)
{
// mod = 10b, r/m = mop1, reg = rop2
modRM = (byte)(modRM.GetValueOrDefault() | 5);
if (op2IsRegister)
modRM |= (byte)(op2.Register.RegisterCode << 3);
displacement = mop1;
}
else if (op1IsRegister)
{
modRM = (byte)(modRM.GetValueOrDefault() | (3 << 6) | op1.Register.RegisterCode);
}
return modRM;
}
#endregion Code Generation
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// The Windows Azure SQL Database management API provides a RESTful set of
/// web services that interact with Windows Azure SQL Database services to
/// manage your databases. The API enables users to create, retrieve,
/// update, and delete databases and servers.
/// </summary>
public static partial class AuditingPolicyOperationsExtensions
{
/// <summary>
/// Creates or updates an Azure SQL Database auditing policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IAuditingPolicyOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the auditing
/// policy applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a Azure
/// SQL Database auditing policy.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse CreateOrUpdateDatabasePolicy(this IAuditingPolicyOperations operations, string resourceGroupName, string serverName, string databaseName, DatabaseAuditingPolicyCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAuditingPolicyOperations)s).CreateOrUpdateDatabasePolicyAsync(resourceGroupName, serverName, databaseName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an Azure SQL Database auditing policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IAuditingPolicyOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the auditing
/// policy applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a Azure
/// SQL Database auditing policy.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateOrUpdateDatabasePolicyAsync(this IAuditingPolicyOperations operations, string resourceGroupName, string serverName, string databaseName, DatabaseAuditingPolicyCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateDatabasePolicyAsync(resourceGroupName, serverName, databaseName, parameters, CancellationToken.None);
}
/// <summary>
/// Creates or updates an Azure SQL Database Server auditing policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IAuditingPolicyOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a Azure
/// SQL Database Server auditing policy.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse CreateOrUpdateServerPolicy(this IAuditingPolicyOperations operations, string resourceGroupName, string serverName, ServerAuditingPolicyCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAuditingPolicyOperations)s).CreateOrUpdateServerPolicyAsync(resourceGroupName, serverName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates an Azure SQL Database Server auditing policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IAuditingPolicyOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a Azure
/// SQL Database Server auditing policy.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateOrUpdateServerPolicyAsync(this IAuditingPolicyOperations operations, string resourceGroupName, string serverName, ServerAuditingPolicyCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateServerPolicyAsync(resourceGroupName, serverName, parameters, CancellationToken.None);
}
/// <summary>
/// Returns an Azure SQL Database auditing policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IAuditingPolicyOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the auditing
/// policy applies.
/// </param>
/// <returns>
/// Represents the response to a get database auditing policy request.
/// </returns>
public static DatabaseAuditingPolicyGetResponse GetDatabasePolicy(this IAuditingPolicyOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAuditingPolicyOperations)s).GetDatabasePolicyAsync(resourceGroupName, serverName, databaseName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns an Azure SQL Database auditing policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IAuditingPolicyOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the auditing
/// policy applies.
/// </param>
/// <returns>
/// Represents the response to a get database auditing policy request.
/// </returns>
public static Task<DatabaseAuditingPolicyGetResponse> GetDatabasePolicyAsync(this IAuditingPolicyOperations operations, string resourceGroupName, string serverName, string databaseName)
{
return operations.GetDatabasePolicyAsync(resourceGroupName, serverName, databaseName, CancellationToken.None);
}
/// <summary>
/// Returns an Azure SQL Database server auditing policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IAuditingPolicyOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <returns>
/// Represents the response to a get database auditing policy request.
/// </returns>
public static ServerAuditingPolicyGetResponse GetServerPolicy(this IAuditingPolicyOperations operations, string resourceGroupName, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IAuditingPolicyOperations)s).GetServerPolicyAsync(resourceGroupName, serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns an Azure SQL Database server auditing policy.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.IAuditingPolicyOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <returns>
/// Represents the response to a get database auditing policy request.
/// </returns>
public static Task<ServerAuditingPolicyGetResponse> GetServerPolicyAsync(this IAuditingPolicyOperations operations, string resourceGroupName, string serverName)
{
return operations.GetServerPolicyAsync(resourceGroupName, serverName, CancellationToken.None);
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComProduction.DCP.DS
{
public class PRO_DCPResultMasterDS
{
public PRO_DCPResultMasterDS()
{
}
private const string THIS = "PCSComProduction.DCP.DS.PRO_DCPResultMasterDS";
/// <summary>
/// This method uses to add data to PRO_DCPResultMaster
/// </summary>
/// <Inputs>
/// PRO_DCPResultMasterVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Monday, September 05, 2005
/// </History>
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
PRO_DCPResultMasterVO objObject = (PRO_DCPResultMasterVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO PRO_DCPResultMaster("
+ PRO_DCPResultMasterTable.WOROUTINGID_FLD + ","
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.CHECKPOINTID_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.CPOID_FLD + ","
+ PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.WOROUTINGID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.WOROUTINGID_FLD].Value = objObject.WORoutingID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.STARTDATETIME_FLD, OleDbType.Date));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.STARTDATETIME_FLD].Value = objObject.StartDateTime;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.DUEDATETIME_FLD, OleDbType.Date));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.DUEDATETIME_FLD].Value = objObject.DueDateTime;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.QUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.QUANTITY_FLD].Value = objObject.Quantity;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD].Value = objObject.DCOptionMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.CHECKPOINTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.CHECKPOINTID_FLD].Value = objObject.CheckPointID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.CPOID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.CPOID_FLD].Value = objObject.CPOID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD].Value = objObject.WorkOrderDetailID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.WORKCENTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.WORKCENTERID_FLD].Value = objObject.WorkCenterID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResultMaster
/// </summary>
/// <Inputs>
/// PRO_DCPResultMasterVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Monday, September 05, 2005
/// </History>
public int AddAndReturnID(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".AddAndReturnID()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
PRO_DCPResultMasterVO objObject = (PRO_DCPResultMasterVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO PRO_DCPResultMaster("
+ PRO_DCPResultMasterTable.WOROUTINGID_FLD + ","
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DELIVERYQUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
// + PRO_DCPResultMasterTable.CHECKPOINTID_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.CPOID_FLD + ","
+ PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultMasterTable.ROUTINGID_FLD + ","
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?)";
strSql += "; SELECT @@IDENTITY as LatestID";
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.WOROUTINGID_FLD, OleDbType.Integer));
if(objObject.WORoutingID > 0)
ocmdPCS.Parameters[PRO_DCPResultMasterTable.WOROUTINGID_FLD].Value = objObject.WORoutingID;
else ocmdPCS.Parameters[PRO_DCPResultMasterTable.WOROUTINGID_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.STARTDATETIME_FLD, OleDbType.Date));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.STARTDATETIME_FLD].Value = objObject.StartDateTime;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.DUEDATETIME_FLD, OleDbType.Date));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.DUEDATETIME_FLD].Value = objObject.DueDateTime;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.QUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.QUANTITY_FLD].Value = objObject.Quantity;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.DELIVERYQUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.DELIVERYQUANTITY_FLD].Value = objObject.DeliveryQuantity;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD].Value = objObject.DCOptionMasterID;
// ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.CHECKPOINTID_FLD, OleDbType.Integer));
// ocmdPCS.Parameters[PRO_DCPResultMasterTable.CHECKPOINTID_FLD].Value = objObject.CheckPointID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.CPOID_FLD, OleDbType.Integer));
if(objObject.CPOID > 0)
ocmdPCS.Parameters[PRO_DCPResultMasterTable.CPOID_FLD].Value = objObject.CPOID;
else ocmdPCS.Parameters[PRO_DCPResultMasterTable.CPOID_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD, OleDbType.Integer));
if(objObject.WorkOrderDetailID > 0)
ocmdPCS.Parameters[PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD].Value = objObject.WorkOrderDetailID;
else ocmdPCS.Parameters[PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.ROUTINGID_FLD, OleDbType.Integer));
if(objObject.RoutingID > 0)
ocmdPCS.Parameters[PRO_DCPResultMasterTable.ROUTINGID_FLD].Value = objObject.RoutingID;
else ocmdPCS.Parameters[PRO_DCPResultMasterTable.ROUTINGID_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.WORKCENTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.WORKCENTERID_FLD].Value = objObject.WorkCenterID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
//Add and return latest Id
return int.Parse(ocmdPCS.ExecuteScalar().ToString());
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResultMaster
/// </summary>
/// <Inputs>
/// PRO_DCPResultMasterVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Monday, September 05, 2005
/// </History>
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + PRO_DCPResultMasterTable.TABLE_NAME + " WHERE " + "DCPResultMasterID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// DeleteMultiRows
/// </summary>
/// <param name="pstrMasterID"></param>
/// <author>Trada</author>
/// <date>Tuesday, April 25 2006</date>
public void DeleteMultiRows(string pstrMasterID)
{
const string METHOD_NAME = THIS + ".DeleteMultiRows()";
string strSql = String.Empty;
strSql= "DELETE " + PRO_DCPResultMasterTable.TABLE_NAME
+ " WHERE " + PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + " IN (" + pstrMasterID + ")";
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResultMaster
/// </summary>
/// <Inputs>
/// PRO_DCPResultMasterVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Monday, September 05, 2005
/// </History>
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.WOROUTINGID_FLD + ","
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.CHECKPOINTID_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.CPOID_FLD + ","
+ PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultMasterTable.TABLE_NAME
+" WHERE " + PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
PRO_DCPResultMasterVO objObject = new PRO_DCPResultMasterVO();
while (odrPCS.Read())
{
objObject.DCPResultMasterID = int.Parse(odrPCS[PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD].ToString().Trim());
objObject.WORoutingID = int.Parse(odrPCS[PRO_DCPResultMasterTable.WOROUTINGID_FLD].ToString().Trim());
objObject.StartDateTime = DateTime.Parse(odrPCS[PRO_DCPResultMasterTable.STARTDATETIME_FLD].ToString().Trim());
objObject.DueDateTime = DateTime.Parse(odrPCS[PRO_DCPResultMasterTable.DUEDATETIME_FLD].ToString().Trim());
objObject.Quantity = Decimal.Parse(odrPCS[PRO_DCPResultMasterTable.QUANTITY_FLD].ToString().Trim());
objObject.DCOptionMasterID = int.Parse(odrPCS[PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD].ToString().Trim());
objObject.CheckPointID = int.Parse(odrPCS[PRO_DCPResultMasterTable.CHECKPOINTID_FLD].ToString().Trim());
objObject.ProductID = int.Parse(odrPCS[PRO_DCPResultMasterTable.PRODUCTID_FLD].ToString().Trim());
objObject.CPOID = int.Parse(odrPCS[PRO_DCPResultMasterTable.CPOID_FLD].ToString().Trim());
objObject.WorkOrderDetailID = int.Parse(odrPCS[PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD].ToString().Trim());
objObject.WorkCenterID = int.Parse(odrPCS[PRO_DCPResultMasterTable.WORKCENTERID_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResultMaster
/// </summary>
/// <Inputs>
/// PRO_DCPResultMasterVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Monday, September 05, 2005
/// </History>
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
PRO_DCPResultMasterVO objObject = (PRO_DCPResultMasterVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE PRO_DCPResultMaster SET "
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + "= ?" + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + "= ?" + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + "= ?"
+" WHERE " + PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.STARTDATETIME_FLD, OleDbType.Date));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.STARTDATETIME_FLD].Value = objObject.StartDateTime;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.DUEDATETIME_FLD, OleDbType.Date));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.DUEDATETIME_FLD].Value = objObject.DueDateTime;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.QUANTITY_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.QUANTITY_FLD].Value = objObject.Quantity;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD].Value = objObject.DCPResultMasterID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResultMaster
/// </summary>
/// <Inputs>
/// PRO_DCPResultMasterVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Monday, September 05, 2005
/// </History>
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.WOROUTINGID_FLD + ","
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.CHECKPOINTID_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.CPOID_FLD + ","
+ PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,PRO_DCPResultMasterTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataTable GetTableStruct()
{
const string METHOD_NAME = THIS + ".List()";
DataTable dstPCS = new DataTable();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT TOP 0 "
+ PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.WOROUTINGID_FLD + ","
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DELIVERYQUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.CPOID_FLD + ","
+ PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultMasterTable.ROUTINGID_FLD + ","
+ "MasterShiftID, MasterTotalSecond,"
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultMasterTable.TABLE_NAME
+ " WHERE 0=1";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// GetDCPResultMasterByArrayMasterID
/// </summary>
/// <param name="pstrMasterID"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Tuesday, April 25 2006</date>
public DataSet GetDCPResultMasterByArrayMasterID(string pstrMasterID)
{
const string METHOD_NAME = THIS + ".GetDCPResultMasterByArrayMasterID()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.WOROUTINGID_FLD + ","
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.ROUTINGID_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.CPOID_FLD + ","
+ PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultMasterTable.TABLE_NAME
+ " WHERE " + PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + " IN (" + pstrMasterID + ")";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,PRO_DCPResultMasterTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResultMaster
/// </summary>
/// <Inputs>
/// PRO_DCPResultMasterVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Monday, September 05, 2005
/// </History>
public void UpdateDataTable(DataTable pdtbData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.WOROUTINGID_FLD + ","
+ "RoutingID , MasterTotalSecond, MasterShiftID, "
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DELIVERYQUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.CPOID_FLD + ","
+ PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
//pdtbData.EnforceConstraints = false;
odadPCS.Update(pdtbData);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void InsertDCPResultDetail(int pintDCOptionMasterID,string pstrChildWorkCenterIDs)
{
const string METHOD_NAME = THIS + ".Update()";
//PRO_DCPResultMasterVO objObject = (PRO_DCPResultMasterVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "insert into pro_dcpresultdetail(StartTime,EndTime," +
" TotalSecond,Quantity,Percentage, " +
" DCPResultMasterID, " +
" Type, " +
" WorkingDate, " +
" ShiftID, " +
" IsManual " +
" ) " +
" select StartDateTime StartTime, " +
" DueDateTime EndTime, " +
" Isnull(MasterTotalSecond,0) TotalSecond ,Quantity,100 Percentage, " +
" DCPResultMasterID, " +
" 0 Type, " +
" cast(cast(dateadd(hh,-datepart(hh,StartDateTime),StartDateTime) as int) as datetime) WorkingDate, " +
" MasterShiftID, " +
" 0 IsManual from pro_dcpresultmaster " +
" where DCOptionMasterID= " + pintDCOptionMasterID +
" AND WorkCenterID IN " + pstrChildWorkCenterIDs +
" and Isnull(Quantity,0) > 0 " +
" and DCPResultMasterID NOT IN (Select DCPResultMasterID from pro_dcpresultdetail)";
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void InsertDCPOrderProduce(DataTable pdtbData, int pintDCOptionMasterID, string strChildWCIDs)
{
const string METHOD_NAME = THIS + ".Update()";
//PRO_DCPResultMasterVO objObject = (PRO_DCPResultMasterVO) pobjObjecVO;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
//prepare value for parameters
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "Delete from DCP_OrderProduce where DCOptionMasterID =" + pintDCOptionMasterID
+ " AND WorkCenterID IN " + strChildWCIDs;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
strSql= "SELECT WorkCenterID,ColumnName,OrderNo,OrderPlan,ShiftID,DCOptionMasterID From DCP_OrderProduce";
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
//pdtbData.EnforceConstraints = false;
odadPCS.Update(pdtbData);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// UpdateDataSetDeleteMultiRows
/// </summary>
/// <param name="pdstData"></param>
/// <author>Trada</author>
/// <date>Tuesday, April 25 2006</date>
public void UpdateDataSetDeleteMultiRows(DataSet pdstData)
{
const string METHOD_NAME = THIS + ".UpdateDataSetDeleteMultiRows()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.WOROUTINGID_FLD + ","
+ "RoutingID ,"
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.CPOID_FLD + ","
+ PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pdstData.EnforceConstraints = false;
odadPCS.Update(pdstData,PRO_DCPResultMasterTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// This method uses to add data to PRO_DCPResult
/// </summary>
/// <Inputs>
/// PRO_DCPResultVO
/// </Inputs>
/// <Returns>
/// void
/// </Returns>
/// <History>
/// Tuesday, August 30, 2005
/// </History>
public DataSet ListDetailStructTable()
{
const string METHOD_NAME = THIS + ".ListDetailStructTable()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT TOP 0 DCPResultDetailID, 0 WorkCenterID, StartTime DATE, StartTime, EndTime, TotalSecond, Quantity, Percentage, DCPResultMasterID, Type, WorkingDate, Converted, ShiftID, '' WorkCenterCode"
+ " FROM PRO_DCPResultDetail"; //+ PRO_DCPResultTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,PRO_DCPResultDetailTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataSet ListMasterStructTable()
{
const string METHOD_NAME = THIS + ".ListMasterStructTable()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT TOP 0 DCPResultMasterID, 0 DetailID, StartDateTime, DueDateTime, Quantity, DCOptionMasterID, CPOID, WORoutingID, WorkOrderDetailID, ProductID, RoutingID, WorkCenterID"
// + PRO_DCPResultTable.DCPRESULTID_FLD + ","
// + PRO_DCPResultTable.WOROUTINGID_FLD + ","
// + PRO_DCPResultTable.STARTDATETIME_FLD + ","
// + PRO_DCPResultTable.DUEDATETIME_FLD + ","
// + PRO_DCPResultTable.QUANTITY_FLD + ","
// + PRO_DCPResultTable.DCOPTIONMASTERID_FLD + ","
// + PRO_DCPResultTable.CHECKPOINTID_FLD + ","
// + PRO_DCPResultTable.PRODUCTID_FLD + ","
// + PRO_DCPResultTable.CPOID_FLD + ","
// + PRO_DCPResultTable.WORKORDERDETAILID_FLD + ","
// + PRO_DCPResultTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,PRO_DCPResultMasterTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
/// <summary>
/// Delete all record in Detail and Master result table
/// </summary>
/// <param name="pintDCOptionMasterID"></param>
public void DeleteOldResult(int pintDCOptionMasterID)
{
const string METHOD_NAME = THIS + ".DeleteOldResult()";
string strSql = "DELETE FROM PRO_DCPResultDetail WHERE "
+ " DCPResultMasterID IN (SELECT DCPResultMasterID FROM PRO_DCPResultMaster WHERE DCOptionMasterID = " + pintDCOptionMasterID + ")";
strSql += " DELETE " + PRO_DCPResultMasterTable.TABLE_NAME + " WHERE " + PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + "=" + pintDCOptionMasterID;
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void UpdateDCPResultMaster(DataSet pdstData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD + ","
+ PRO_DCPResultMasterTable.ROUTINGID_FLD
+ " FROM " + PRO_DCPResultMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pdstData.EnforceConstraints = false;
odadPCS.Update(pdstData,PRO_DCPResultMasterTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public int GetRoutingID(int pintProductID, int pintWorkCenterID)
{
const string METHOD_NAME = THIS + ".AddAndReturnID()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "select RoutingID from Itm_routing where ProductID = " + pintProductID
+ " and WorkCenterID = " + pintWorkCenterID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
//Add and return latest Id
return int.Parse(ocmdPCS.ExecuteScalar().ToString());
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void UpdateDataSet(DataSet pdstData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ PRO_DCPResultMasterTable.DCPRESULTMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.WOROUTINGID_FLD + ","
+ "RoutingID ,"
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.CPOID_FLD + ","
+ PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD
+ " FROM " + PRO_DCPResultMasterTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
//odcbPCS = new OleDbCommandBuilder(odadPCS);
pdstData.EnforceConstraints = false;
OleDbCommand ocmdPCS = new OleDbCommand("", oconPCS);
string strInsSql= "INSERT INTO PRO_DCPResultMaster("
+ PRO_DCPResultMasterTable.WOROUTINGID_FLD + ","
+ "RoutingID ,"
+ PRO_DCPResultMasterTable.STARTDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.DUEDATETIME_FLD + ","
+ PRO_DCPResultMasterTable.QUANTITY_FLD + ","
+ PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD + ","
+ PRO_DCPResultMasterTable.PRODUCTID_FLD + ","
+ PRO_DCPResultMasterTable.CPOID_FLD + ","
+ PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD + ","
+ PRO_DCPResultMasterTable.WORKCENTERID_FLD + ")"
+ " VALUES (?,?,?,?,?,?,?,?,?,?);"
+ " SELECT SCOPE_IDENTITY() AS DCPResultMasterID";
ocmdPCS.CommandText = strInsSql;
ocmdPCS.CommandType = CommandType.Text;
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.WOROUTINGID_FLD, OleDbType.Integer,0,"WORouting"));
ocmdPCS.Parameters.Add(new OleDbParameter("RoutingID", OleDbType.Integer,0,"Routing"));
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.STARTDATETIME_FLD, OleDbType.Date,0,"StartDateTime"));
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.DUEDATETIME_FLD, OleDbType.Date,0,"DueDateTime"));
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.QUANTITY_FLD, OleDbType.Decimal,0,"Quantity"));
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.DCOPTIONMASTERID_FLD, OleDbType.Integer,0,"DCOptionMasterID"));
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.PRODUCTID_FLD, OleDbType.Integer,0,"ProductID"));
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.CPOID_FLD, OleDbType.Integer,0,"CPOID"));
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.WORKORDERDETAILID_FLD, OleDbType.Integer,0,"WorkOrderDetailID"));
ocmdPCS.Parameters.Add(new OleDbParameter(PRO_DCPResultMasterTable.WORKCENTERID_FLD, OleDbType.Integer,0,"WorkCenterID"));
ocmdPCS.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
odadPCS.InsertCommand = ocmdPCS;
//odadPCS.
odadPCS.Update(pdstData,PRO_DCPResultMasterTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Branding.DeployCustomThemeWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using SharpVectors.Dom.Events;
using SharpVectors.Dom.Svg;
namespace SharpVectors.Dom.Events
{
/// <summary>
/// Summary description for EventTarget.
/// </summary>
public class EventTarget : IEventTargetSupport
{
#region Private Fields
private IEventTargetSupport eventTarget;
private EventListenerMap captureMap;
private EventListenerMap bubbleMap;
private ArrayList _ancestors;
#endregion
#region Constructors
public EventTarget(IEventTargetSupport eventTarget)
{
this.eventTarget = eventTarget;
this.captureMap = new EventListenerMap();
this.bubbleMap = new EventListenerMap();
this._ancestors = new ArrayList();
}
#endregion
#region IEventTarget interface
#region Methods
#region DOM Level 2
public void AddEventListener(string type, EventListener listener,
bool useCapture)
{
if (useCapture)
{
captureMap.AddEventListener(null, type, null, listener);
}
else
{
bubbleMap.AddEventListener(null, type, null, listener);
}
}
public void RemoveEventListener(string type, EventListener listener,
bool useCapture)
{
if (useCapture)
{
captureMap.RemoveEventListener(null, type, listener);
}
else
{
bubbleMap.RemoveEventListener(null, type, listener);
}
}
public bool DispatchEvent(IEvent eventInfo)
{
if (eventInfo.Type == null || eventInfo.Type == "")
{
throw new EventException(EventExceptionCode.UnspecifiedEventTypeErr);
}
try
{
// The actual target may be an SvgElement or an SvgElementInstance from
// a conceptual tree <see href="http://www.w3.org/TR/SVG/struct.html#UseElement"/>
XmlNode currNode = null;
ISvgElementInstance currInstance = null;
if (this.eventTarget is ISvgElementInstance)
currInstance = (ISvgElementInstance)this.eventTarget;
else
currNode = (XmlNode)this.eventTarget;
// We can't use an XPath ancestor axe because we must account for
// conceptual nodes
_ancestors.Clear();
// Build the ancestors from the conceptual tree
if (currInstance != null)
{
while (currInstance.ParentNode != null)
{
currInstance = currInstance.ParentNode;
_ancestors.Add(currInstance);
}
currNode = (XmlNode)currInstance.CorrespondingUseElement;
_ancestors.Add(currNode);
}
// Build actual ancestors
while (currNode != null && currNode.ParentNode != null)
{
currNode = currNode.ParentNode;
_ancestors.Add(currNode);
}
Event realEvent = (Event)eventInfo;
realEvent.eventTarget = this.eventTarget;
if (!realEvent.stopped)
{
realEvent.eventPhase = EventPhase.CapturingPhase;
for (int i = _ancestors.Count - 1; i >= 0; i--)
{
if (realEvent.stopped)
{
break;
}
IEventTarget ancestor = _ancestors[i] as IEventTarget;
if (ancestor != null)
{
realEvent.currentTarget = ancestor;
if (ancestor is IEventTargetSupport)
{
((IEventTargetSupport)ancestor).FireEvent(realEvent);
}
}
}
}
if (!realEvent.stopped)
{
realEvent.eventPhase = EventPhase.AtTarget;
realEvent.currentTarget = this.eventTarget;
this.eventTarget.FireEvent(realEvent);
}
if (!realEvent.stopped)
{
realEvent.eventPhase = EventPhase.BubblingPhase;
for (int i = 0; i < _ancestors.Count; i++)
{
if (realEvent.stopped)
{
break;
}
IEventTarget ancestor = _ancestors[i] as IEventTarget;
if (ancestor != null)
{
realEvent.currentTarget = ancestor;
((IEventTargetSupport)ancestor).FireEvent(realEvent);
}
}
}
return realEvent.stopped;
}
catch (InvalidCastException)
{
throw new DomException(DomExceptionType.WrongDocumentErr);
}
}
#endregion
#region DOM Level 3 Experimental
public void AddEventListenerNs(string namespaceUri, string type,
EventListener listener, bool useCapture, object evtGroup)
{
if (useCapture)
{
captureMap.AddEventListener(namespaceUri, type, evtGroup, listener);
}
else
{
bubbleMap.AddEventListener(namespaceUri, type, evtGroup, listener);
}
}
public void RemoveEventListenerNs(string namespaceUri, string type,
EventListener listener, bool useCapture)
{
if (useCapture)
{
captureMap.RemoveEventListener(namespaceUri, type, listener);
}
else
{
bubbleMap.RemoveEventListener(namespaceUri, type, listener);
}
}
public bool WillTriggerNs(string namespaceUri, string type)
{
XmlNode node = (XmlNode)this.eventTarget;
XmlNodeList ancestors = node.SelectNodes("ancestor::node()");
for (int i = 0; i < ancestors.Count; i++)
{
IEventTarget ancestor = ancestors[i] as IEventTarget;
if (ancestor.HasEventListenerNs(namespaceUri, type))
{
return true;
}
}
return false;
}
public bool HasEventListenerNs(string namespaceUri, string eventType)
{
return captureMap.HasEventListenerNs(namespaceUri, eventType) ||
bubbleMap.HasEventListenerNs(namespaceUri, eventType);
}
#endregion
#endregion
#region NON-DOM
public void FireEvent(IEvent eventInfo)
{
switch (eventInfo.EventPhase)
{
case EventPhase.AtTarget:
case EventPhase.BubblingPhase:
bubbleMap.Lock();
bubbleMap.FireEvent(eventInfo);
bubbleMap.Unlock();
break;
case EventPhase.CapturingPhase:
captureMap.Lock();
captureMap.FireEvent(eventInfo);
captureMap.Unlock();
break;
}
}
public event EventListener OnMouseMove
{
add
{
throw new NotImplementedException();
}
remove
{
throw new NotImplementedException();
}
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommandLine;
using NuGet.Frameworks;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectManagement;
namespace nuget2bazel
{
public class WorkspaceEntry
{
public WorkspaceEntry()
{
}
public WorkspaceEntry(IDictionary<string, string> knownDependencies,
PackageIdentity identity, string sha256, IEnumerable<PackageDependencyGroup> deps,
IEnumerable<FrameworkSpecificGroup> libs, IEnumerable<FrameworkSpecificGroup> tools,
IEnumerable<FrameworkSpecificGroup> references, IEnumerable<FrameworkSpecificGroup> buildFiles,
IEnumerable<FrameworkSpecificGroup> runtimeFiles, string mainFile, string variable, bool nugetSourceCustom)
{
var netFrameworkTFMs = new string[]
{
"net45", "net451", "net452", "net46", "net461", "net462", "net47", "net471", "net472", "net48", "netstandard1.0",
"netstandard1.1", "netstandard1.2", "netstandard1.3",
"netstandard1.4", "netstandard1.5", "netstandard1.6", "netstandard2.0", "netstandard2.1",
};
var coreFrameworkTFMs = new string[]
{
"netcoreapp2.0", "netcoreapp2.1", "netcoreapp2.2", "netcoreapp3.0", "netcoreapp3.1", "net5.0", "net6.0"
};
PackageIdentity = identity;
Sha256 = sha256;
Variable = variable;
NugetSourceCustom = nugetSourceCustom;
var coreFrameworks = coreFrameworkTFMs.Select(x => NuGetFramework.Parse(x));
var netFrameworks = netFrameworkTFMs.Select(x => NuGetFramework.Parse(x));
var monoFramework = NuGetFramework.Parse("net70");
Core_Files = GetFiles(coreFrameworks, libs, tools, buildFiles, runtimeFiles);
Net_Files = GetFiles(netFrameworks, libs, tools, buildFiles, runtimeFiles);
Mono_Files = GetFiles(monoFramework, libs, tools, buildFiles, runtimeFiles);
var depConverted = deps.Select(x =>
new FrameworkSpecificGroup(x.TargetFramework, x.Packages.Select(y => y.Id.ToLower())));
Core_Deps = GetDepsCore(coreFrameworks, depConverted, knownDependencies);
Net_Deps = GetDepsNet(netFrameworks, depConverted, knownDependencies);
Mono_Deps = MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(monoFramework, depConverted)?.Items?.Select(x => ToRefMono(x));
CoreLib = new Dictionary<string, string>();
foreach (var framework in coreFrameworks)
{
var lib = GetMostCompatibleItem(framework, libs, mainFile);
if (!string.IsNullOrEmpty(lib))
CoreLib.Add(framework.GetShortFolderName(), lib);
}
CoreRef = new Dictionary<string, string>();
foreach (var framework in coreFrameworks)
{
var reflib = GetMostCompatibleItem(framework, references, mainFile);
if (!string.IsNullOrEmpty(reflib))
CoreRef.Add(framework.GetShortFolderName(), reflib);
}
NetLib = new Dictionary<string, string>();
foreach (var framework in netFrameworks)
{
var lib = GetMostCompatibleItem(framework, libs, mainFile);
if (!string.IsNullOrEmpty(lib))
NetLib.Add(framework.GetShortFolderName(), lib);
}
NetRef = new Dictionary<string, string>();
foreach (var framework in netFrameworks)
{
var reflib = GetMostCompatibleItem(framework, references, mainFile);
if (!string.IsNullOrEmpty(reflib))
NetRef.Add(framework.GetShortFolderName(), reflib);
}
MonoLib = GetMostCompatibleItem(monoFramework, libs, mainFile);
MonoRef = GetMostCompatibleItem(monoFramework, references, mainFile);
CoreTool = new Dictionary<string, string>();
foreach (var framework in coreFrameworks)
{
var tool = GetMostCompatibleItem(framework, tools, mainFile);
if (!string.IsNullOrEmpty(tool))
CoreTool.Add(framework.GetShortFolderName(), tool);
}
NetTool = new Dictionary<string, string>();
foreach (var framework in netFrameworks)
{
var tool = GetMostCompatibleItem(framework, tools, mainFile);
if (!string.IsNullOrEmpty(tool))
NetTool.Add(framework.GetShortFolderName(), tool);
}
MonoTool = GetMostCompatibleItem(monoFramework, tools, mainFile);
//if (NetLib == null || !NetLib.Any())
// NetLib = Net_Files?.ToDictionary(key => key.Key, val => val.Value.FirstOrDefault(z => Path.GetExtension(z) == ".dll"));
//if (CoreLib == null || !CoreLib.Any())
// CoreLib = Core_Files?.ToDictionary(key => key.Key, val => val.Value.FirstOrDefault(z => Path.GetExtension(z) == ".dll"));
//if (MonoLib == null)
// MonoLib = Mono_Files?.FirstOrDefault(x => Path.GetExtension(x) == ".dll");
}
private IDictionary<string, IEnumerable<string>> GetDepsNet(IEnumerable<NuGetFramework> frameworks, IEnumerable<FrameworkSpecificGroup> groups, IDictionary<string, string> knownDependencies)
{
var result = new Dictionary<string, IEnumerable<string>>();
var knownDependenciesLower = knownDependencies.Keys.Select(x => x.ToLower()).ToList();
foreach (var framework in frameworks)
{
var rawDeps = MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(framework, groups)?.Items;
var knownRawDeps = rawDeps?.Where(knownDependenciesLower.Contains);
var deps = knownRawDeps?.Select(x => ToRefNet(x, framework))?.Where(y => y != null);
if (deps != null)
result.Add(framework.GetShortFolderName(), deps);
}
return result;
}
private IDictionary<string, IEnumerable<string>> GetDepsCore(IEnumerable<NuGetFramework> frameworks, IEnumerable<FrameworkSpecificGroup> groups, IDictionary<string, string> knownDependencies)
{
var result = new Dictionary<string, IEnumerable<string>>();
var knownDependenciesLower = knownDependencies.Keys.Select(x => x.ToLower()).ToList();
foreach (var framework in frameworks)
{
var rawDeps = MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(framework, groups)?.Items;
var knownRawDeps = rawDeps?.Where(knownDependenciesLower.Contains);
var deps = knownRawDeps?.Select(x => ToRefCore(x, framework))?.Where(y => y != null);
if (deps != null)
result.Add(framework.GetShortFolderName(), deps);
}
return result;
}
private IEnumerable<string> GetFiles(NuGetFramework framework,
IEnumerable<FrameworkSpecificGroup> libs, IEnumerable<FrameworkSpecificGroup> tools,
IEnumerable<FrameworkSpecificGroup> buildFiles, IEnumerable<FrameworkSpecificGroup> runtimeFiles)
{
var result = new List<string>();
var items = MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(framework, libs)?.Items;
if (items != null)
result.AddRange(items);
items = MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(framework, tools)?.Items;
if (items != null)
result.AddRange(items);
items = MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(framework, buildFiles)?.Items;
if (items != null)
result.AddRange(items);
items = MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(framework, runtimeFiles)?.Items;
if (items != null)
result.AddRange(items);
return result.Where(x => x.Substring(x.Length - 1) != "/");
}
private IDictionary<string, IEnumerable<string>> GetFiles(IEnumerable<NuGetFramework> frameworks, IEnumerable<FrameworkSpecificGroup> libs,
IEnumerable<FrameworkSpecificGroup> tools, IEnumerable<FrameworkSpecificGroup> buildFiles, IEnumerable<FrameworkSpecificGroup> runtimeFiles)
{
var result = new Dictionary<string, IEnumerable<string>>();
foreach (var framework in frameworks)
{
var files = GetFiles(framework, libs, tools, buildFiles, runtimeFiles);
if (files != null && files.Any())
result.Add(framework.GetShortFolderName(), files);
}
return result;
}
private string GetMostCompatibleItem(NuGetFramework framework, IEnumerable<FrameworkSpecificGroup> items, string mainFile)
{
var compatibleItems = MSBuildNuGetProjectSystemUtility.GetMostCompatibleGroup(framework, items)?.Items;
if (compatibleItems == null)
return null;
if (mainFile != null)
{
var f = compatibleItems.FirstOrDefault(x => String.Equals(Path.GetFileName(x), mainFile, StringComparison.CurrentCultureIgnoreCase));
if (f != null)
return f;
f = compatibleItems.FirstOrDefault(x => String.Equals(Path.GetFileName(x), mainFile + ".exe", StringComparison.CurrentCultureIgnoreCase));
if (f != null)
return f;
f = compatibleItems.FirstOrDefault(x => String.Equals(Path.GetFileName(x), mainFile + ".dll", StringComparison.CurrentCultureIgnoreCase));
if (f != null)
return f;
}
return compatibleItems.FirstOrDefault(x => Path.GetExtension(x) == ".dll");
}
private string GetMostCompatibleItem(NuGetFramework framework, IEnumerable<FrameworkSpecificGroup> refs, IEnumerable<FrameworkSpecificGroup> libs,
string mainFile)
{
var result = GetMostCompatibleItem(framework, refs, mainFile);
if (result != null) return result;
result = GetMostCompatibleItem(framework, libs, mainFile);
return result;
}
public string Generate(bool indent)
{
var i = indent ? " " : "";
var sb = new StringBuilder();
sb.Append($"{i}nuget_package(\n");
if (Variable == null)
sb.Append($"{i} name = \"{PackageIdentity.Id.ToLower()}\",\n");
else
sb.Append($"{i} name = {Variable},\n");
sb.Append($"{i} package = \"{PackageIdentity.Id.ToLower()}\",\n");
sb.Append($"{i} version = \"{PackageIdentity.Version}\",\n");
if (!String.IsNullOrEmpty(Sha256))
sb.Append($"{i} sha256 = \"{Sha256}\",\n");
if (NugetSourceCustom)
sb.Append($"{i} source = source,\n");
if (CoreLib != null && CoreLib.Any())
{
sb.Append($"{i} core_lib = {{\n");
foreach (var pair in CoreLib)
sb.Append($"{i} \"{pair.Key}\": \"{pair.Value}\",\n");
sb.Append($"{i} }},\n");
}
if (CoreRef != null && CoreRef.Any())
{
sb.Append($"{i} core_ref = {{\n");
foreach (var pair in CoreRef)
sb.Append($"{i} \"{pair.Key}\": \"{pair.Value}\",\n");
sb.Append($"{i} }},\n");
}
// if (NetLib != null && NetLib.Any())
// {
// sb.Append($"{i} net_lib = {{\n");
// foreach (var pair in NetLib)
// sb.Append($"{i} \"{pair.Key}\": \"{pair.Value}\",\n");
// sb.Append($"{i} }},\n");
// }
// if (NetRef != null && NetRef.Any())
// {
// sb.Append($"{i} net_ref = {{\n");
// foreach (var pair in NetRef)
// sb.Append($"{i} \"{pair.Key}\": \"{pair.Value}\",\n");
// sb.Append($"{i} }},\n");
// }
// if (!String.IsNullOrEmpty(MonoLib))
// sb.Append($"{i} mono_lib = \"{MonoLib}\",\n");
// if (!String.IsNullOrEmpty(MonoRef))
// sb.Append($"{i} mono_ref = \"{MonoRef}\",\n");
if (CoreTool != null && CoreTool.Sum(x => x.Value.Count()) > 0)
{
sb.Append($"{i} core_tool = {{\n");
foreach (var pair in CoreTool)
sb.Append($"{i} \"{pair.Key}\": \"{pair.Value}\",\n");
sb.Append($"{i} }},\n");
}
// if (NetTool != null && NetTool.Sum(x => x.Value.Count()) > 0)
// {
// sb.Append($"{i} net_tool = {{\n");
// foreach (var pair in NetTool)
// sb.Append($"{i} \"{pair.Key}\": \"{pair.Value}\",\n");
// sb.Append($"{i} }},\n");
// }
// if (!String.IsNullOrEmpty(MonoTool))
// sb.Append($"{i} mono_tool = \"{MonoTool}\",\n");
if (Core_Deps != null && Core_Deps.Sum(x => x.Value.Count()) > 0)
{
sb.Append($"{i} core_deps = {{\n");
foreach (var pair in Core_Deps)
{
if (!pair.Value.Any())
continue;
sb.Append($"{i} \"{pair.Key}\": [\n");
foreach (var s in pair.Value)
sb.Append($"{i} \"{s}\",\n");
sb.Append($"{i} ],\n");
}
sb.Append($"{i} }},\n");
}
// if (Net_Deps != null && Net_Deps.Sum(x => x.Value.Count()) > 0)
// {
// sb.Append($"{i} net_deps = {{\n");
// foreach (var pair in Net_Deps)
// {
// if (!pair.Value.Any())
// continue;
// sb.Append($"{i} \"{pair.Key}\": [\n");
// foreach (var s in pair.Value)
// sb.Append($"{i} \"{s}\",\n");
// sb.Append($"{i} ],\n");
// }
// sb.Append($"{i} }},\n");
// }
// if (Mono_Deps != null && Mono_Deps.Any())
// {
// sb.Append($"{i} mono_deps = [\n");
// foreach (var s in Mono_Deps)
// sb.Append($"{i} \"{s}\",\n");
// sb.Append($"{i} ],\n");
// }
if (Core_Files != null && Core_Files.Sum(x => x.Value.Count()) > 0)
{
sb.Append($"{i} core_files = {{\n");
foreach (var pair in Core_Files)
{
if (!pair.Value.Any())
continue;
sb.Append($"{i} \"{pair.Key}\": [\n");
foreach (var s in pair.Value)
sb.Append($"{i} \"{s}\",\n");
sb.Append($"{i} ],\n");
}
sb.Append($"{i} }},\n");
}
// if (Net_Files != null && Net_Files.Sum(x => x.Value.Count()) > 0)
// {
// sb.Append($"{i} net_files = {{\n");
// foreach (var pair in Net_Files)
// {
// if (!pair.Value.Any())
// continue;
// sb.Append($"{i} \"{pair.Key}\": [\n");
// foreach (var s in pair.Value)
// sb.Append($"{i} \"{s}\",\n");
// sb.Append($"{i} ],\n");
// }
// sb.Append($"{i} }},\n");
// }
// if (Mono_Files != null && Mono_Files.Any())
// {
// sb.Append($"{i} mono_files = [\n");
// foreach (var s in Mono_Files)
// sb.Append($"{i} \"{s}\",\n");
// sb.Append($"{i} ],\n");
// }
sb.Append($"{i})\n");
return sb.ToString();
}
private string ToRefCore(string id, NuGetFramework framework)
{
return $"@{id.ToLower()}//:{framework.GetShortFolderName()}_core";
}
private string ToRefMono(string id)
{
return $"@{id.ToLower()}//:mono";
}
private string ToRefNet(string id, NuGetFramework framework)
{
return $"@{id.ToLower()}//:{framework.GetShortFolderName()}_net";
}
public PackageIdentity PackageIdentity { get; set; }
public string Sha256 { get; set; }
public string Variable { get; set; }
public bool NugetSourceCustom { get; set; }
public IDictionary<string, string> CoreLib { get; set; }
public IDictionary<string, string> NetLib { get; set; }
public string MonoLib { get; set; }
public IDictionary<string, string> CoreRef { get; set; }
public IDictionary<string, string> NetRef { get; set; }
public string MonoRef { get; set; }
public IDictionary<string, string> CoreTool { get; set; }
public IDictionary<string, string> NetTool { get; set; }
public string MonoTool { get; set; }
public IDictionary<string, IEnumerable<string>> Core_Deps { get; set; }
public IDictionary<string, IEnumerable<string>> Net_Deps { get; set; }
public IEnumerable<string> Mono_Deps { get; set; }
public IDictionary<string, IEnumerable<string>> Core_Files { get; set; }
public IDictionary<string, IEnumerable<string>> Net_Files { get; set; }
public IEnumerable<string> Mono_Files { get; set; }
}
}
| |
// Author: Dwivedi, Ajay kumar
// Adwiv@Yahoo.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 Mono.System.Xml.Serialization;
using System.ComponentModel;
using Mono.System.Xml;
using Mono.Xml;
using Mono.Xml.Schema;
namespace Mono.System.Xml.Schema
{
/// <summary>
/// Summary description for XmlSchemaXPath.
/// </summary>
public class XmlSchemaXPath : XmlSchemaAnnotated
{
private string xpath;
XmlNamespaceManager nsmgr;
internal bool isSelector;
XsdIdentityPath [] compiledExpression;
XsdIdentityPath currentPath;
public XmlSchemaXPath()
{
}
[DefaultValue("")]
[Mono.System.Xml.Serialization.XmlAttribute("xpath")]
public string XPath
{
get{ return xpath; }
set{ xpath = value; }
}
internal override int Compile(ValidationEventHandler h, XmlSchema schema)
{
// If this is already compiled this time, simply skip.
if (CompilationId == schema.CompilationId)
return 0;
if (nsmgr == null) {
nsmgr = new XmlNamespaceManager (new NameTable ());
if (Namespaces != null)
foreach (XmlQualifiedName qname in Namespaces.ToArray ())
nsmgr.AddNamespace (qname.Name, qname.Namespace);
}
currentPath = new XsdIdentityPath ();
ParseExpression (xpath, h, schema);
XmlSchemaUtil.CompileID(Id, this, schema.IDCollection, h);
this.CompilationId = schema.CompilationId;
return errorCount;
}
internal XsdIdentityPath [] CompiledExpression {
get { return compiledExpression; }
}
private void ParseExpression (string xpath, ValidationEventHandler h, XmlSchema schema)
{
ArrayList paths = new ArrayList ();
ParsePath (xpath, 0, paths, h, schema);
this.compiledExpression = (XsdIdentityPath []) paths.ToArray (typeof (XsdIdentityPath));
}
private void ParsePath (string xpath, int pos, ArrayList paths,
ValidationEventHandler h, XmlSchema schema)
{
pos = SkipWhitespace (xpath, pos);
if (xpath.Length >= pos + 3 && xpath [pos] == '.') {
int tmp = pos;
pos++;
pos = SkipWhitespace (xpath, pos);
if (xpath.Length > pos + 2 && xpath.IndexOf ("//", pos, 2) == pos) {
currentPath.Descendants = true;
pos += 2;
}
else
pos = tmp; // revert
}
ArrayList al = new ArrayList ();
ParseStep (xpath, pos, al, paths, h, schema);
}
private void ParseStep (string xpath, int pos, ArrayList steps,
ArrayList paths, ValidationEventHandler h, XmlSchema schema)
{
pos = SkipWhitespace (xpath, pos);
if (xpath.Length == pos) {
error (h, "Empty xpath expression is specified");
return;
}
XsdIdentityStep step = new XsdIdentityStep ();
switch (xpath [pos]) {
case '@':
if (isSelector) {
error (h, "Selector cannot include attribute axes.");
currentPath = null;
return;
}
pos++;
step.IsAttribute = true;
pos = SkipWhitespace (xpath, pos);
if (xpath.Length > pos && xpath [pos] == '*') {
pos++;
step.IsAnyName = true;
break;
}
goto default;
case '.':
pos++; // do nothing ;-)
step.IsCurrent = true;
break;
case '*':
pos++;
step.IsAnyName = true;
break;
case 'c':
if (xpath.Length > pos + 5 && xpath.IndexOf ("child", pos, 5) == pos) {
int tmp = pos;
pos += 5;
pos = SkipWhitespace (xpath, pos);
if (xpath.Length > pos && xpath [pos] == ':' && xpath [pos+1] == ':') {
pos += 2;
if (xpath.Length > pos && xpath [pos] == '*') {
pos++;
step.IsAnyName = true;
break;
}
pos = SkipWhitespace (xpath, pos);
}
else
pos = tmp;
}
goto default;
case 'a':
if (xpath.Length > pos + 9 && xpath.IndexOf ("attribute", pos, 9) == pos) {
int tmp = pos;
pos += 9;
pos = SkipWhitespace (xpath, pos);
if (xpath.Length > pos && xpath [pos] == ':' && xpath [pos+1] == ':') {
if (isSelector) {
error (h, "Selector cannot include attribute axes.");
currentPath = null;
return;
}
pos += 2;
step.IsAttribute = true;
if (xpath.Length > pos && xpath [pos] == '*') {
pos++;
step.IsAnyName = true;
break;
}
pos = SkipWhitespace (xpath, pos);
}
else
pos = tmp;
}
goto default;
default:
int nameStart = pos;
while (xpath.Length > pos) {
if (!XmlChar.IsNCNameChar (xpath [pos]))
break;
else
pos++;
}
if (pos == nameStart) {
error (h, "Invalid path format for a field.");
this.currentPath = null;
return;
}
if (xpath.Length == pos || xpath [pos] != ':')
step.Name = xpath.Substring (nameStart, pos - nameStart);
else {
string prefix = xpath.Substring (nameStart, pos - nameStart);
pos++;
if (xpath.Length > pos && xpath [pos] == '*') {
string ns = nsmgr.LookupNamespace (prefix, false);
if (ns == null) {
error (h, "Specified prefix '" + prefix + "' is not declared.");
this.currentPath = null;
return;
}
step.NsName = ns;
pos++;
} else {
int localNameStart = pos;
while (xpath.Length > pos) {
if (!XmlChar.IsNCNameChar (xpath [pos]))
break;
else
pos++;
}
step.Name = xpath.Substring (localNameStart, pos - localNameStart);
string ns = nsmgr.LookupNamespace (prefix, false);
if (ns == null) {
error (h, "Specified prefix '" + prefix + "' is not declared.");
this.currentPath = null;
return;
}
step.Namespace = ns;
}
}
break;
}
if (!step.IsCurrent) // Current step is meaningless, other than its representation.
steps.Add (step);
pos = SkipWhitespace (xpath, pos);
if (xpath.Length == pos) {
currentPath.OrderedSteps = (XsdIdentityStep []) steps.ToArray (typeof (XsdIdentityStep));
paths.Add (currentPath);
return;
}
else if (xpath [pos] == '/') {
pos++;
if (step.IsAttribute) {
error (h, "Unexpected xpath token after Attribute NameTest.");
this.currentPath = null;
return;
}
this.ParseStep (xpath, pos, steps, paths, h, schema);
if (currentPath == null) // For ValidationEventHandler
return;
currentPath.OrderedSteps = (XsdIdentityStep []) steps.ToArray (typeof (XsdIdentityStep));
} else if (xpath [pos] == '|') {
pos++;
currentPath.OrderedSteps = (XsdIdentityStep []) steps.ToArray (typeof (XsdIdentityStep));
paths.Add (this.currentPath);
this.currentPath = new XsdIdentityPath ();
this.ParsePath (xpath, pos, paths, h, schema);
} else {
error (h, "Unexpected xpath token after NameTest.");
this.currentPath = null;
return;
}
}
private int SkipWhitespace (string xpath, int pos)
{
bool loop = true;
while (loop && xpath.Length > pos) {
switch (xpath [pos]) {
case ' ':
case '\t':
case '\r':
case '\n':
pos++;
continue;
default:
loop = false;
break;
}
}
return pos;
}
//<selector
// id = ID
// xpath = a subset of XPath expression, see below
// {any attributes with non-schema namespace . . .}>
// Content: (annotation?)
//</selector>
internal static XmlSchemaXPath Read(XmlSchemaReader reader, ValidationEventHandler h,string name)
{
XmlSchemaXPath path = new XmlSchemaXPath();
reader.MoveToElement();
if(reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != name)
{
error(h,"Should not happen :1: XmlSchemaComplexContentRestriction.Read, name="+reader.Name,null);
reader.Skip();
return null;
}
path.LineNumber = reader.LineNumber;
path.LinePosition = reader.LinePosition;
path.SourceUri = reader.BaseURI;
XmlNamespaceManager currentMgr = XmlSchemaUtil.GetParserContext (reader.Reader).NamespaceManager;
if (currentMgr != null) {
path.nsmgr = new XmlNamespaceManager (reader.NameTable);
IEnumerator e = currentMgr.GetEnumerator ();
while (e.MoveNext ()) {
string prefix = e.Current as string;
switch (prefix) {
case "xml":
case "xmlns":
continue;
default:
path.nsmgr.AddNamespace (prefix, currentMgr.LookupNamespace (prefix, false));
break;
}
}
}
while(reader.MoveToNextAttribute())
{
if(reader.Name == "id")
{
path.Id = reader.Value;
}
else if(reader.Name == "xpath")
{
path.xpath = reader.Value;
}
else if((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace)
{
error(h,reader.Name + " is not a valid attribute for "+name,null);
}
else
{
XmlSchemaUtil.ReadUnhandledAttribute(reader,path);
}
}
reader.MoveToElement();
if(reader.IsEmptyElement)
return path;
// Content: (annotation?)
int level = 1;
while(reader.ReadNextElement())
{
if(reader.NodeType == XmlNodeType.EndElement)
{
if(reader.LocalName != name)
error(h,"Should not happen :2: XmlSchemaXPath.Read, name="+reader.Name,null);
break;
}
if(level <= 1 && reader.LocalName == "annotation")
{
level = 2; //Only one annotation
XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader,h);
if(annotation != null)
path.Annotation = annotation;
continue;
}
reader.RaiseInvalidElementError();
}
return path;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web.Security;
using Newtonsoft.Json;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Factories;
using Umbraco.Core.Persistence.Mappers;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Relators;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Security;
namespace Umbraco.Core.Persistence.Repositories
{
/// <summary>
/// Represents the UserRepository for doing CRUD operations for <see cref="IUser"/>
/// </summary>
internal class UserRepository : PetaPocoRepositoryBase<int, IUser>, IUserRepository
{
private readonly IDictionary<string, string> _passwordConfiguration;
/// <summary>
/// Constructor
/// </summary>
/// <param name="work"></param>
/// <param name="cacheHelper"></param>
/// <param name="logger"></param>
/// <param name="sqlSyntax"></param>
/// <param name="passwordConfiguration">
/// A dictionary specifying the configuration for user passwords. If this is null then no password configuration will be persisted or read.
/// </param>
public UserRepository(IScopeUnitOfWork work, CacheHelper cacheHelper, ILogger logger, ISqlSyntaxProvider sqlSyntax,
IDictionary<string, string> passwordConfiguration = null)
: base(work, cacheHelper, logger, sqlSyntax)
{
_passwordConfiguration = passwordConfiguration;
}
#region Overrides of RepositoryBase<int,IUser>
protected override IUser PerformGet(int id)
{
var sql = GetQueryWithGroups();
sql.Where(GetBaseWhereClause(), new { Id = id });
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
var dto = Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql)
.FirstOrDefault();
if (dto == null)
return null;
var user = UserFactory.BuildEntity(dto);
return user;
}
/// <summary>
/// Returns a user by username
/// </summary>
/// <param name="username"></param>
/// <param name="includeSecurityData">
/// Can be used for slightly faster user lookups if the result doesn't require security data (i.e. groups, apps & start nodes).
/// This is really only used for a shim in order to upgrade to 7.6.
/// </param>
/// <returns>
/// A non cached <see cref="IUser"/> instance
/// </returns>
public IUser GetByUsername(string username, bool includeSecurityData)
{
UserDto dto;
if (includeSecurityData)
{
var sql = GetQueryWithGroups();
sql.Where<UserDto>(userDto => userDto.Login == username, SqlSyntax);
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
dto = Database
.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(
new UserGroupRelator().Map, sql)
.FirstOrDefault();
}
else
{
var sql = GetBaseQuery("umbracoUser.*");
sql.Where<UserDto>(userDto => userDto.Login == username, SqlSyntax);
dto = Database.FirstOrDefault<UserDto>(sql);
}
if (dto == null)
return null;
var user = UserFactory.BuildEntity(dto);
return user;
}
/// <summary>
/// Returns a user by id
/// </summary>
/// <param name="id"></param>
/// <param name="includeSecurityData">
/// This is really only used for a shim in order to upgrade to 7.6 but could be used
/// for slightly faster user lookups if the result doesn't require security data (i.e. groups, apps & start nodes)
/// </param>
/// <returns>
/// A non cached <see cref="IUser"/> instance
/// </returns>
public IUser Get(int id, bool includeSecurityData)
{
UserDto dto;
if (includeSecurityData)
{
var sql = GetQueryWithGroups();
sql.Where(GetBaseWhereClause(), new { Id = id });
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
dto = Database
.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(
new UserGroupRelator().Map, sql)
.FirstOrDefault();
}
else
{
var sql = GetBaseQuery("umbracoUser.*");
sql.Where(GetBaseWhereClause(), new { Id = id });
dto = Database.FirstOrDefault<UserDto>(sql);
}
if (dto == null)
return null;
var user = UserFactory.BuildEntity(dto);
return user;
}
public IProfile GetProfile(string username)
{
var sql = GetBaseQuery(false).Where<UserDto>(userDto => userDto.UserName == username, SqlSyntax);
var dto = Database.Fetch<UserDto>(sql)
.FirstOrDefault();
if (dto == null)
return null;
return new UserProfile(dto.Id, dto.UserName);
}
public IProfile GetProfile(int id)
{
var sql = GetBaseQuery(false).Where<UserDto>(userDto => userDto.Id == id, SqlSyntax);
var dto = Database.Fetch<UserDto>(sql)
.FirstOrDefault();
if (dto == null)
return null;
return new UserProfile(dto.Id, dto.UserName);
}
public IDictionary<UserState, int> GetUserStates()
{
var sql = @"SELECT '1CountOfAll' AS colName, COUNT(id) AS num FROM umbracoUser
UNION
SELECT '2CountOfActive' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NOT NULL
UNION
SELECT '3CountOfDisabled' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userDisabled = 1
UNION
SELECT '4CountOfLockedOut' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userNoConsole = 1
UNION
SELECT '5CountOfInvited' AS colName, COUNT(id) AS num FROM umbracoUser WHERE lastLoginDate IS NULL AND userDisabled = 1 AND invitedDate IS NOT NULL
ORDER BY colName";
var result = Database.Fetch<dynamic>(sql);
return new Dictionary<UserState, int>
{
{UserState.All, result[0].num},
{UserState.Active, result[1].num},
{UserState.Disabled, result[2].num},
{UserState.LockedOut, result[3].num},
{UserState.Invited, result[4].num}
};
}
protected override IEnumerable<IUser> PerformGetAll(params int[] ids)
{
var sql = GetQueryWithGroups();
if (ids.Any())
{
sql.Where("umbracoUser.id in (@ids)", new { ids = ids });
}
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
var users = ConvertFromDtos(Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql))
.ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching.
return users;
}
protected override IEnumerable<IUser> PerformGetByQuery(IQuery<IUser> query)
{
var sqlClause = GetQueryWithGroups();
var translator = new SqlTranslator<IUser>(sqlClause, query);
var sql = translator.Translate();
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
var dtos = Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql)
.DistinctBy(x => x.Id);
var users = ConvertFromDtos(dtos)
.ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching.
return users;
}
#endregion
#region Overrides of PetaPocoRepositoryBase<int,IUser>
protected override Sql GetBaseQuery(bool isCount)
{
var sql = new Sql();
if (isCount)
{
sql.Select("COUNT(*)").From<UserDto>();
}
else
{
return GetBaseQuery("*");
}
return sql;
}
/// <summary>
/// A query to return a user with it's groups and with it's groups sections
/// </summary>
/// <returns></returns>
private Sql GetQueryWithGroups()
{
//base query includes user groups
var sql = GetBaseQuery("umbracoUser.*, umbracoUserGroup.*, umbracoUserGroup2App.*, umbracoUserStartNode.*");
AddGroupLeftJoin(sql);
return sql;
}
private void AddGroupLeftJoin(Sql sql)
{
sql.LeftJoin<User2UserGroupDto>(SqlSyntax)
.On<User2UserGroupDto, UserDto>(SqlSyntax, dto => dto.UserId, dto => dto.Id)
.LeftJoin<UserGroupDto>(SqlSyntax)
.On<UserGroupDto, User2UserGroupDto>(SqlSyntax, dto => dto.Id, dto => dto.UserGroupId)
.LeftJoin<UserGroup2AppDto>(SqlSyntax)
.On<UserGroup2AppDto, UserGroupDto>(SqlSyntax, dto => dto.UserGroupId, dto => dto.Id)
.LeftJoin<UserStartNodeDto>(SqlSyntax)
.On<UserStartNodeDto, UserDto>(SqlSyntax, dto => dto.UserId, dto => dto.Id);
}
private Sql GetBaseQuery(string columns)
{
var sql = new Sql();
sql.Select(columns)
.From<UserDto>();
return sql;
}
protected override string GetBaseWhereClause()
{
return "umbracoUser.id = @Id";
}
protected override IEnumerable<string> GetDeleteClauses()
{
var list = new List<string>
{
"DELETE FROM cmsTask WHERE userId = @Id",
"DELETE FROM cmsTask WHERE parentUserId = @Id",
"DELETE FROM umbracoUser2UserGroup WHERE userId = @Id",
"DELETE FROM umbracoUser2NodeNotify WHERE userId = @Id",
"DELETE FROM umbracoUser WHERE id = @Id",
"DELETE FROM umbracoExternalLogin WHERE id = @Id"
};
return list;
}
protected override Guid NodeObjectTypeId
{
get { throw new NotImplementedException(); }
}
protected override void PersistNewItem(IUser entity)
{
((User)entity).AddingEntity();
//ensure security stamp if non
if (entity.SecurityStamp.IsNullOrWhiteSpace())
{
entity.SecurityStamp = Guid.NewGuid().ToString();
}
var userDto = UserFactory.BuildDto(entity);
//Check if we have a known config, we only want to store config for hashing
//TODO: This logic will need to be updated when we do http://issues.umbraco.org/issue/U4-10089
if (_passwordConfiguration != null && _passwordConfiguration.Count > 0)
{
var json = JsonConvert.SerializeObject(_passwordConfiguration);
userDto.PasswordConfig = json;
}
var id = Convert.ToInt32(Database.Insert(userDto));
entity.Id = id;
if (entity.IsPropertyDirty("StartContentIds") || entity.IsPropertyDirty("StartMediaIds"))
{
if (entity.IsPropertyDirty("StartContentIds"))
{
AddingOrUpdateStartNodes(entity, Enumerable.Empty<UserStartNodeDto>(), UserStartNodeDto.StartNodeTypeValue.Content, entity.StartContentIds);
}
if (entity.IsPropertyDirty("StartMediaIds"))
{
AddingOrUpdateStartNodes(entity, Enumerable.Empty<UserStartNodeDto>(), UserStartNodeDto.StartNodeTypeValue.Media, entity.StartMediaIds);
}
}
if (entity.IsPropertyDirty("Groups"))
{
//lookup all assigned
var assigned = entity.Groups == null || entity.Groups.Any() == false
? new List<UserGroupDto>()
: Database.Fetch<UserGroupDto>("SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", new { aliases = entity.Groups.Select(x => x.Alias) });
foreach (var groupDto in assigned)
{
var dto = new User2UserGroupDto
{
UserGroupId = groupDto.Id,
UserId = entity.Id
};
Database.Insert(dto);
}
}
entity.ResetDirtyProperties();
}
protected override void PersistUpdatedItem(IUser entity)
{
//Updates Modified date
((User)entity).UpdatingEntity();
//ensure security stamp if non
if (entity.SecurityStamp.IsNullOrWhiteSpace())
{
entity.SecurityStamp = Guid.NewGuid().ToString();
}
var userDto = UserFactory.BuildDto(entity);
//build list of columns to check for saving - we don't want to save the password if it hasn't changed!
//List the columns to save, NOTE: would be nice to not have hard coded strings here but no real good way around that
var colsToSave = new Dictionary<string, string>()
{
{"userDisabled", "IsApproved"},
{"userNoConsole", "IsLockedOut"},
{"startStructureID", "StartContentId"},
{"startMediaID", "StartMediaId"},
{"userName", "Name"},
{"userLogin", "Username"},
{"userEmail", "Email"},
{"userLanguage", "Language"},
{"securityStampToken", "SecurityStamp"},
{"lastLockoutDate", "LastLockoutDate"},
{"lastPasswordChangeDate", "LastPasswordChangeDate"},
{"lastLoginDate", "LastLoginDate"},
{"failedLoginAttempts", "FailedPasswordAttempts"},
{"createDate", "CreateDate"},
{"updateDate", "UpdateDate"},
{"avatar", "Avatar"},
{"emailConfirmedDate", "EmailConfirmedDate"},
{"invitedDate", "InvitedDate"}
};
//create list of properties that have changed
var changedCols = colsToSave
.Where(col => entity.IsPropertyDirty(col.Value))
.Select(col => col.Key)
.ToList();
// DO NOT update the password if it has not changed or if it is null or empty
if (entity.IsPropertyDirty("RawPasswordValue") && entity.RawPasswordValue.IsNullOrWhiteSpace() == false)
{
changedCols.Add("userPassword");
//special case - when using ASP.Net identity the user manager will take care of updating the security stamp, however
// when not using ASP.Net identity (i.e. old membership providers), we'll need to take care of updating this manually
// so we can just detect if that property is dirty, if it's not we'll set it manually
if (entity.IsPropertyDirty("SecurityStamp") == false)
{
userDto.SecurityStampToken = entity.SecurityStamp = Guid.NewGuid().ToString();
changedCols.Add("securityStampToken");
}
//Check if we have a known config, we only want to store config for hashing
//TODO: This logic will need to be updated when we do http://issues.umbraco.org/issue/U4-10089
if (_passwordConfiguration != null && _passwordConfiguration.Count > 0)
{
var json = JsonConvert.SerializeObject(_passwordConfiguration);
userDto.PasswordConfig = json;
changedCols.Add("passwordConfig");
}
}
//only update the changed cols
if (changedCols.Count > 0)
{
Database.Update(userDto, changedCols);
}
if (entity.IsPropertyDirty("StartContentIds") || entity.IsPropertyDirty("StartMediaIds"))
{
var assignedStartNodes = Database.Fetch<UserStartNodeDto>("SELECT * FROM umbracoUserStartNode WHERE userId = @userId", new { userId = entity.Id });
if (entity.IsPropertyDirty("StartContentIds"))
{
AddingOrUpdateStartNodes(entity, assignedStartNodes, UserStartNodeDto.StartNodeTypeValue.Content, entity.StartContentIds);
}
if (entity.IsPropertyDirty("StartMediaIds"))
{
AddingOrUpdateStartNodes(entity, assignedStartNodes, UserStartNodeDto.StartNodeTypeValue.Media, entity.StartMediaIds);
}
}
if (entity.IsPropertyDirty("Groups"))
{
//lookup all assigned
var assigned = entity.Groups == null || entity.Groups.Any() == false
? new List<UserGroupDto>()
: Database.Fetch<UserGroupDto>("SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", new { aliases = entity.Groups.Select(x => x.Alias) });
//first delete all
//TODO: We could do this a nicer way instead of "Nuke and Pave"
Database.Delete<User2UserGroupDto>("WHERE UserId = @UserId", new { UserId = entity.Id });
foreach (var groupDto in assigned)
{
var dto = new User2UserGroupDto
{
UserGroupId = groupDto.Id,
UserId = entity.Id
};
Database.Insert(dto);
}
}
entity.ResetDirtyProperties();
}
private void AddingOrUpdateStartNodes(IEntity entity, IEnumerable<UserStartNodeDto> current, UserStartNodeDto.StartNodeTypeValue startNodeType, int[] entityStartIds)
{
var assignedIds = current.Where(x => x.StartNodeType == (int)startNodeType).Select(x => x.StartNode).ToArray();
//remove the ones not assigned to the entity
var toDelete = assignedIds.Except(entityStartIds).ToArray();
if (toDelete.Length > 0)
Database.Delete<UserStartNodeDto>("WHERE UserId = @UserId AND startNode IN (@startNodes)", new { UserId = entity.Id, startNodes = toDelete });
//add the ones not currently in the db
var toAdd = entityStartIds.Except(assignedIds).ToArray();
foreach (var i in toAdd)
{
var dto = new UserStartNodeDto
{
StartNode = i,
StartNodeType = (int)startNodeType,
UserId = entity.Id
};
Database.Insert(dto);
}
}
#endregion
#region Implementation of IUserRepository
public int GetCountByQuery(IQuery<IUser> query)
{
var sqlClause = GetBaseQuery("umbracoUser.id");
var translator = new SqlTranslator<IUser>(sqlClause, query);
var subquery = translator.Translate();
//get the COUNT base query
var sql = GetBaseQuery(true)
.Append(new Sql("WHERE umbracoUser.id IN (" + subquery.SQL + ")", subquery.Arguments));
return Database.ExecuteScalar<int>(sql);
}
public bool Exists(string username)
{
var sql = new Sql();
sql.Select("COUNT(*)")
.From<UserDto>()
.Where<UserDto>(x => x.UserName == username);
return Database.ExecuteScalar<int>(sql) > 0;
}
/// <summary>
/// Gets a list of <see cref="IUser"/> objects associated with a given group
/// </summary>
/// <param name="groupId">Id of group</param>
public IEnumerable<IUser> GetAllInGroup(int groupId)
{
return GetAllInOrNotInGroup(groupId, true);
}
/// <summary>
/// Gets a list of <see cref="IUser"/> objects not associated with a given group
/// </summary>
/// <param name="groupId">Id of group</param>
public IEnumerable<IUser> GetAllNotInGroup(int groupId)
{
return GetAllInOrNotInGroup(groupId, false);
}
private IEnumerable<IUser> GetAllInOrNotInGroup(int groupId, bool include)
{
var sql = new Sql();
sql.Select("*")
.From<UserDto>();
var innerSql = new Sql();
innerSql.Select("umbracoUser.id")
.From<UserDto>()
.LeftJoin<User2UserGroupDto>()
.On<UserDto, User2UserGroupDto>(left => left.Id, right => right.UserId)
.Where("umbracoUser2UserGroup.userGroupId = " + groupId);
sql.Where(string.Format("umbracoUser.id {0} ({1})",
include ? "IN" : "NOT IN",
innerSql.SQL));
return ConvertFromDtos(Database.Fetch<UserDto>(sql));
}
[Obsolete("Use the overload with long operators instead")]
[EditorBrowsable(EditorBrowsableState.Never)]
public IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, int pageIndex, int pageSize, out int totalRecords, Expression<Func<IUser, string>> orderBy)
{
if (orderBy == null) throw new ArgumentNullException("orderBy");
// get the referenced column name and find the corresp mapped column name
var expressionMember = ExpressionHelper.GetMemberInfo(orderBy);
var mapper = MappingResolver.Current.ResolveMapperByType(typeof(IUser));
var mappedField = mapper.Map(expressionMember.Name);
if (mappedField.IsNullOrWhiteSpace())
throw new ArgumentException("Could not find a mapping for the column specified in the orderBy clause");
long tr;
var results = GetPagedResultsByQuery(query, Convert.ToInt64(pageIndex), pageSize, out tr, mappedField, Direction.Ascending);
totalRecords = Convert.ToInt32(tr);
return results;
}
/// <summary>
/// Gets paged user results
/// </summary>
/// <param name="query"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecords"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="includeUserGroups">
/// A filter to only include user that belong to these user groups
/// </param>
/// <param name="excludeUserGroups">
/// A filter to only include users that do not belong to these user groups
/// </param>
/// <param name="userState">Optional parameter to filter by specfied user state</param>
/// <param name="filter"></param>
/// <returns></returns>
/// <remarks>
/// The query supplied will ONLY work with data specifically on the umbracoUser table because we are using PetaPoco paging (SQL paging)
/// </remarks>
public IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, long pageIndex, int pageSize, out long totalRecords,
Expression<Func<IUser, object>> orderBy, Direction orderDirection,
string[] includeUserGroups = null,
string[] excludeUserGroups = null,
UserState[] userState = null,
IQuery<IUser> filter = null)
{
if (orderBy == null) throw new ArgumentNullException("orderBy");
// get the referenced column name and find the corresp mapped column name
var expressionMember = ExpressionHelper.GetMemberInfo(orderBy);
var mapper = MappingResolver.Current.ResolveMapperByType(typeof(IUser));
var mappedField = mapper.Map(expressionMember.Name);
if (mappedField.IsNullOrWhiteSpace())
throw new ArgumentException("Could not find a mapping for the column specified in the orderBy clause");
return GetPagedResultsByQuery(query, pageIndex, pageSize, out totalRecords, mappedField, orderDirection, includeUserGroups, excludeUserGroups, userState, filter);
}
private IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, long pageIndex, int pageSize, out long totalRecords, string orderBy, Direction orderDirection,
string[] includeUserGroups = null,
string[] excludeUserGroups = null,
UserState[] userState = null,
IQuery<IUser> customFilter = null)
{
if (string.IsNullOrWhiteSpace(orderBy)) throw new ArgumentException("Value cannot be null or whitespace.", "orderBy");
Sql filterSql = null;
var customFilterWheres = customFilter != null ? customFilter.GetWhereClauses().ToArray() : null;
var hasCustomFilter = customFilterWheres != null && customFilterWheres.Length > 0;
if (hasCustomFilter
|| (includeUserGroups != null && includeUserGroups.Length > 0) || (excludeUserGroups != null && excludeUserGroups.Length > 0)
|| (userState != null && userState.Length > 0 && userState.Contains(UserState.All) == false))
filterSql = new Sql();
if (hasCustomFilter)
{
foreach (var filterClause in customFilterWheres)
{
filterSql.Append(string.Format("AND ({0})", filterClause.Item1), filterClause.Item2);
}
}
if (includeUserGroups != null && includeUserGroups.Length > 0)
{
var subQuery = @"AND (umbracoUser.id IN (SELECT DISTINCT umbracoUser.id
FROM umbracoUser
INNER JOIN umbracoUser2UserGroup ON umbracoUser2UserGroup.userId = umbracoUser.id
INNER JOIN umbracoUserGroup ON umbracoUserGroup.id = umbracoUser2UserGroup.userGroupId
WHERE umbracoUserGroup.userGroupAlias IN (@userGroups)))";
filterSql.Append(subQuery, new { userGroups = includeUserGroups });
}
if (excludeUserGroups != null && excludeUserGroups.Length > 0)
{
var subQuery = @"AND (umbracoUser.id NOT IN (SELECT DISTINCT umbracoUser.id
FROM umbracoUser
INNER JOIN umbracoUser2UserGroup ON umbracoUser2UserGroup.userId = umbracoUser.id
INNER JOIN umbracoUserGroup ON umbracoUserGroup.id = umbracoUser2UserGroup.userGroupId
WHERE umbracoUserGroup.userGroupAlias IN (@userGroups)))";
filterSql.Append(subQuery, new { userGroups = excludeUserGroups });
}
if (userState != null && userState.Length > 0)
{
//the "ALL" state doesn't require any filtering so we ignore that, if it exists in the list we don't do any filtering
if (userState.Contains(UserState.All) == false)
{
var sb = new StringBuilder("(");
var appended = false;
if (userState.Contains(UserState.Active))
{
sb.Append("(userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NOT NULL)");
appended = true;
}
if (userState.Contains(UserState.Disabled))
{
if (appended) sb.Append(" OR ");
sb.Append("(userDisabled = 1)");
appended = true;
}
if (userState.Contains(UserState.LockedOut))
{
if (appended) sb.Append(" OR ");
sb.Append("(userNoConsole = 1)");
appended = true;
}
if (userState.Contains(UserState.Invited))
{
if (appended) sb.Append(" OR ");
sb.Append("(lastLoginDate IS NULL AND userDisabled = 1 AND invitedDate IS NOT NULL)");
appended = true;
}
sb.Append(")");
filterSql.Append("AND " + sb);
}
}
// Get base query for returning IDs
var sqlBaseIds = GetBaseQuery("id");
if (query == null) query = new Query<IUser>();
var translatorIds = new SqlTranslator<IUser>(sqlBaseIds, query);
var sqlQueryIds = translatorIds.Translate();
//get sorted and filtered sql
var sqlNodeIdsWithSort = GetSortedSqlForPagedResults(
GetFilteredSqlForPagedResults(sqlQueryIds, filterSql),
orderDirection, orderBy);
// Get page of results and total count
var pagedResult = Database.Page<UserDto>(pageIndex + 1, pageSize, sqlNodeIdsWithSort);
totalRecords = Convert.ToInt32(pagedResult.TotalItems);
//NOTE: We need to check the actual items returned, not the 'totalRecords', that is because if you request a page number
// that doesn't actually have any data on it, the totalRecords will still indicate there are records but there are none in
// the pageResult.
if (pagedResult.Items.Any())
{
//Create the inner paged query that was used above to get the paged result, we'll use that as the inner sub query
var args = sqlNodeIdsWithSort.Arguments;
string sqlStringCount, sqlStringPage;
Database.BuildPageQueries<UserDto>(pageIndex * pageSize, pageSize, sqlNodeIdsWithSort.SQL, ref args, out sqlStringCount, out sqlStringPage);
var sqlQueryFull = GetBaseQuery("umbracoUser.*, umbracoUserGroup.*, umbracoUserGroup2App.*, umbracoUserStartNode.*");
var fullQueryWithPagedInnerJoin = sqlQueryFull
.Append("INNER JOIN (")
//join the paged query with the paged query arguments
.Append(sqlStringPage, args)
.Append(") temp ")
.Append("ON umbracoUser.id = temp.id");
AddGroupLeftJoin(fullQueryWithPagedInnerJoin);
//get sorted and filtered sql
var fullQuery = GetSortedSqlForPagedResults(
GetFilteredSqlForPagedResults(fullQueryWithPagedInnerJoin, filterSql),
orderDirection, orderBy);
var users = ConvertFromDtos(Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, fullQuery))
.ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching.
return users;
}
return Enumerable.Empty<IUser>();
}
private Sql GetFilteredSqlForPagedResults(Sql sql, Sql filterSql)
{
Sql filteredSql;
// Apply filter
if (filterSql != null)
{
var sqlFilter = " WHERE " + filterSql.SQL.TrimStart("AND ");
//NOTE: this is certainly strange - NPoco handles this much better but we need to re-create the sql
// instance a couple of times to get the parameter order correct, for some reason the first
// time the arguments don't show up correctly but the SQL argument parameter names are actually updated
// accordingly - so we re-create it again. In v8 we don't need to do this and it's already taken care of.
filteredSql = new Sql(sql.SQL, sql.Arguments);
var args = filteredSql.Arguments.Concat(filterSql.Arguments).ToArray();
filteredSql = new Sql(
string.Format("{0} {1}", filteredSql.SQL, sqlFilter),
args);
filteredSql = new Sql(filteredSql.SQL, args);
}
else
{
//copy to var so that the original isn't changed
filteredSql = new Sql(sql.SQL, sql.Arguments);
}
return filteredSql;
}
private Sql GetSortedSqlForPagedResults(Sql sql, Direction orderDirection, string orderBy)
{
//copy to var so that the original isn't changed
var sortedSql = new Sql(sql.SQL, sql.Arguments);
// Apply order according to parameters
if (string.IsNullOrEmpty(orderBy) == false)
{
//each order by param needs to be in a bracket! see: https://github.com/toptensoftware/PetaPoco/issues/177
var orderByParams = new[] { string.Format("({0})", orderBy) };
if (orderDirection == Direction.Ascending)
{
sortedSql.OrderBy(orderByParams);
}
else
{
sortedSql.OrderByDescending(orderByParams);
}
}
return sortedSql;
}
internal IEnumerable<IUser> GetNextUsers(int id, int count)
{
var idsQuery = new Sql()
.Select("umbracoUser.id")
.From<UserDto>(SqlSyntax)
.Where<UserDto>(x => x.Id >= id)
.OrderBy<UserDto>(x => x.Id, SqlSyntax);
// first page is index 1, not zero
var ids = Database.Page<int>(1, count, idsQuery).Items.ToArray();
// now get the actual users and ensure they are ordered properly (same clause)
return ids.Length == 0 ? Enumerable.Empty<IUser>() : GetAll(ids).OrderBy(x => x.Id);
}
#endregion
private IEnumerable<IUser> ConvertFromDtos(IEnumerable<UserDto> dtos)
{
return dtos.Select(UserFactory.BuildEntity);
}
//private IEnumerable<IUserGroup> ConvertFromDtos(IEnumerable<UserGroupDto> dtos)
//{
// return dtos.Select(dto =>
// {
// var userGroupFactory = new UserGroupFactory();
// return userGroupFactory.BuildEntity(dto);
// });
//}
}
}
| |
// 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 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Authorization.Version2015_07_01
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Authorization;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for RoleDefinitionsOperations.
/// </summary>
public static partial class RoleDefinitionsOperationsExtensions
{
/// <summary>
/// Deletes a role definition.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role definition.
/// </param>
/// <param name='roleDefinitionId'>
/// The ID of the role definition to delete.
/// </param>
public static RoleDefinition Delete(this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId)
{
return operations.DeleteAsync(scope, roleDefinitionId).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a role definition.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role definition.
/// </param>
/// <param name='roleDefinitionId'>
/// The ID of the role definition to delete.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleDefinition> DeleteAsync(this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(scope, roleDefinitionId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get role definition by name (GUID).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role definition.
/// </param>
/// <param name='roleDefinitionId'>
/// The ID of the role definition.
/// </param>
public static RoleDefinition Get(this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId)
{
return operations.GetAsync(scope, roleDefinitionId).GetAwaiter().GetResult();
}
/// <summary>
/// Get role definition by name (GUID).
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role definition.
/// </param>
/// <param name='roleDefinitionId'>
/// The ID of the role definition.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleDefinition> GetAsync(this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(scope, roleDefinitionId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a role definition.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role definition.
/// </param>
/// <param name='roleDefinitionId'>
/// The ID of the role definition.
/// </param>
/// <param name='roleDefinition'>
/// The values for the role definition.
/// </param>
public static RoleDefinition CreateOrUpdate(this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId, RoleDefinition roleDefinition)
{
return operations.CreateOrUpdateAsync(scope, roleDefinitionId, roleDefinition).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a role definition.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role definition.
/// </param>
/// <param name='roleDefinitionId'>
/// The ID of the role definition.
/// </param>
/// <param name='roleDefinition'>
/// The values for the role definition.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleDefinition> CreateOrUpdateAsync(this IRoleDefinitionsOperations operations, string scope, string roleDefinitionId, RoleDefinition roleDefinition, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(scope, roleDefinitionId, roleDefinition, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a role definition by ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleDefinitionId'>
/// The fully qualified role definition ID to get.
/// </param>
public static RoleDefinition GetById(this IRoleDefinitionsOperations operations, string roleDefinitionId)
{
return operations.GetByIdAsync(roleDefinitionId).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a role definition by ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleDefinitionId'>
/// The fully qualified role definition ID to get.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleDefinition> GetByIdAsync(this IRoleDefinitionsOperations operations, string roleDefinitionId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetByIdWithHttpMessagesAsync(roleDefinitionId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get all role definitions that are applicable at scope and above.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role definition.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<RoleDefinition> List(this IRoleDefinitionsOperations operations, string scope, ODataQuery<RoleDefinitionFilter> odataQuery = default(ODataQuery<RoleDefinitionFilter>))
{
return ((IRoleDefinitionsOperations)operations).ListAsync(scope, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Get all role definitions that are applicable at scope and above.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// The scope of the role definition.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleDefinition>> ListAsync(this IRoleDefinitionsOperations operations, string scope, ODataQuery<RoleDefinitionFilter> odataQuery = default(ODataQuery<RoleDefinitionFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(scope, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get all role definitions that are applicable at scope and above.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RoleDefinition> ListNext(this IRoleDefinitionsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Get all role definitions that are applicable at scope and above.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleDefinition>> ListNextAsync(this IRoleDefinitionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Xml.Serialization;
namespace Aardvark.Base
{
// AUTOGENERATED CODE - DO NOT CHANGE!
#region QuaternionF
/// <summary>
/// Struct for general quaternions, for rotations in 3-dimensional space use <see cref="Rot3f"/>.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential)]
public struct QuaternionF : IEquatable<QuaternionF>
{
/// <summary>
/// Scalar (real) part of the quaternion.
/// </summary>
[DataMember]
public float W;
/// <summary>
/// First component of vector (imaginary) part of the quaternion.
/// </summary>
[DataMember]
public float X;
/// <summary>
/// Second component of vector (imaginary) part of the quaternion.
/// </summary>
[DataMember]
public float Y;
/// <summary>
/// Third component of vector (imaginary) part of the quaternion.
/// </summary>
[DataMember]
public float Z;
#region Constructors
/// <summary>
/// Creates a <see cref="QuaternionF"/> (a, (a, a, a)).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionF(float a)
{
W = a;
X = a; Y = a; Z = a;
}
/// <summary>
/// Creates a <see cref="QuaternionF"/> (w, (x, y, z)).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionF(float w, float x, float y, float z)
{
W = w;
X = x; Y = y; Z = z;
}
/// <summary>
/// Creates a <see cref="QuaternionF"/> (v.x, (v.y, v.z, v.w)).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionF(V4f v)
{
W = v.X;
X = v.Y; Y = v.Z; Z = v.W;
}
/// <summary>
/// Creates a <see cref="QuaternionF"/> (w, (v.x, v.y, v.z)).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionF(float w, V3f v)
{
W = w;
X = v.X; Y = v.Y; Z = v.Z;
}
/// <summary>
/// Creates a copy of the given <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionF(QuaternionF q)
{
W = q.W; X = q.X; Y = q.Y; Z = q.Z;
}
/// <summary>
/// Creates a <see cref="QuaternionF"/> from the given <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionF(QuaternionD q)
{
W = (float)q.W; X = (float)q.X; Y = (float)q.Y; Z = (float)q.Z;
}
/// <summary>
/// Creates a <see cref="QuaternionF"/> from the given <see cref="Rot3f"/> transformation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionF(Rot3f r)
{
W = r.W; X = r.X; Y = r.Y; Z = r.Z;
}
/// <summary>
/// Creates a <see cref="QuaternionF"/> from the given <see cref="Rot3d"/> transformation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionF(Rot3d r)
{
W = (float)r.W; X = (float)r.X; Y = (float)r.Y; Z = (float)r.Z;
}
/// <summary>
/// Creates a <see cref="QuaternionF"/> from an array.
/// (w = a[0], (x = a[1], y = a[2], z = a[3])).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionF(float[] a)
{
W = a[0];
X = a[1]; Y = a[2]; Z = a[3];
}
/// <summary>
/// Creates a <see cref="QuaternionF"/> from an array starting at specified index.
/// (w = a[start], (x = a[start+1], y = a[start+2], z = a[start+3])).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionF(float[] a, int start)
{
W = a[start];
X = a[start + 1]; Y = a[start + 2]; Z = a[start + 3];
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the vector part (x, y, z) of this <see cref="QuaternionF"/>.
/// </summary>
[XmlIgnore]
public V3f V
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return new V3f(X, Y, Z); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set { X = value.X; Y = value.Y; Z = value.Z; }
}
/// <summary>
/// Gets the squared norm (or squared length) of this <see cref="QuaternionF"/>.
/// </summary>
public float NormSquared
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => W * W + X * X + Y * Y + Z * Z;
}
/// <summary>
/// Gets the norm (or length) of this <see cref="QuaternionF"/>.
/// </summary>
public float Norm
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => NormSquared.Sqrt();
}
/// <summary>
/// Gets normalized (unit) quaternion from this <see cref="QuaternionF"/>
/// </summary>
public QuaternionF Normalized
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
var rs = new QuaternionF(this);
rs.Normalize();
return rs;
}
}
/// <summary>
/// Gets the (multiplicative) inverse of this <see cref="QuaternionF"/>.
/// The zero quaternion is returned, if this quaternion is zero.
/// </summary>
public QuaternionF Inverse
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
var rs = new QuaternionF(this);
rs.Invert();
return rs;
}
}
/// <summary>
/// Gets the conjugate of this <see cref="QuaternionF"/>.
/// For unit quaternions this is the same as its inverse.
/// </summary>
public QuaternionF Conjugated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionF(W, -V);
}
/// <summary>
/// Gets if this <see cref="QuaternionF"/> is zero.
/// </summary>
public bool IsZero
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (W == 0) && (X == 0) && (Y == 0) && (Z == 0);
}
#endregion
#region Constants
/// <summary>
/// Gets a <see cref="QuaternionF"/> with (0, (0, 0, 0)).
/// </summary>
public static QuaternionF Zero
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionF(0);
}
/// <summary>
/// Gets a <see cref="QuaternionF"/> with (1, (0, 0, 0)).
/// </summary>
public static QuaternionF One
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionF(1, 0, 0, 0);
}
/// <summary>
/// Gets the identity <see cref="QuaternionF"/> with (1, (0, 0, 0)).
/// </summary>
public static QuaternionF Identity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionF(1, 0, 0, 0);
}
/// <summary>
/// Gets a <see cref="QuaternionF"/> with (0, (1, 0, 0)).
/// </summary>
public static QuaternionF I
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionF(0, 1, 0, 0);
}
/// <summary>
/// Gets a <see cref="QuaternionF"/> with (0, (0, 1, 0)).
/// </summary>
public static QuaternionF J
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionF(0, 0, 1, 0);
}
/// <summary>
/// Gets a <see cref="QuaternionF"/> with (0, (0, 0, 1)).
/// </summary>
public static QuaternionF K
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionF(0, 0, 0, 1);
}
#endregion
#region Arithmetic Operators
/// <summary>
/// Returns the component-wise negation of a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator -(QuaternionF q)
=> new QuaternionF(-q.W, -q.X, -q.Y, -q.Z);
/// <summary>
/// Returns the sum of two <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator +(QuaternionF a, QuaternionF b)
=> new QuaternionF(a.W + b.W, a.X + b.X, a.Y + b.Y, a.Z + b.Z);
/// <summary>
/// Returns the sum of a <see cref="QuaternionF"/> and a real scalar.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator +(QuaternionF q, float s)
=> new QuaternionF(q.W + s, q.X, q.Y, q.Z);
/// <summary>
/// Returns the sum of a real scalar and a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator +(float s, QuaternionF q)
=> new QuaternionF(q.W + s, q.X, q.Y, q.Z);
/// <summary>
/// Returns the difference between two <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator -(QuaternionF a, QuaternionF b)
=> new QuaternionF(a.W - b.W, a.X - b.X, a.Y - b.Y, a.Z - b.Z);
/// <summary>
/// Returns the difference between a <see cref="QuaternionF"/> and a real scalar.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator -(QuaternionF q, float s)
=> new QuaternionF(q.W - s, q.X, q.Y, q.Z);
/// <summary>
/// Returns the difference between a real scalar and a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator -(float s, QuaternionF q)
=> new QuaternionF(s - q.W, -q.X, -q.Y, -q.Z);
/// <summary>
/// Returns the product of a <see cref="QuaternionF"/> and a scalar.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator *(QuaternionF q, float s)
=> new QuaternionF(q.W * s, q.X * s, q.Y * s, q.Z * s);
/// <summary>
/// Returns the product of a scalar and a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator *(float s, QuaternionF q)
=> new QuaternionF(q.W * s, q.X * s, q.Y * s, q.Z * s);
/// <summary>
/// Multiplies two <see cref="QuaternionF"/>.
/// Attention: Multiplication is NOT commutative!
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator *(QuaternionF a, QuaternionF b)
{
return new QuaternionF(
a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z,
a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y,
a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z,
a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X);
}
/// <summary>
/// Divides two <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator /(QuaternionF a, QuaternionF b)
=> a * b.Inverse;
/// <summary>
/// Divides a <see cref="QuaternionF"/> by a scalar.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator /(QuaternionF q, float s)
=> new QuaternionF(q.W / s, q.X / s, q.Y / s, q.Z / s);
/// <summary>
/// Divides a scalar by a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF operator /(float s, QuaternionF q)
=> new QuaternionF(s / q.W, s / q.X, s / q.Y, s / q.Z);
#endregion
#region Comparison Operators
/// <summary>
/// Checks whether two <see cref="QuaternionF"/> are equal.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(QuaternionF q0, QuaternionF q1)
=> q0.W == q1.W && q0.X == q1.X && q0.Y == q1.Y && q0.Z == q1.Z;
/// <summary>
/// Checks whether two <see cref="QuaternionF"/> are different.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(QuaternionF q0, QuaternionF q1)
=> q0.W != q1.W || q0.X != q1.X || q0.Y != q1.Y || q0.Z != q1.Z;
#endregion
#region Conversions
/// <summary>
/// Conversion from a <see cref="QuaternionF"/> to a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator QuaternionD(QuaternionF q)
=> new QuaternionD(q);
/// <summary>
/// Returns this <see cref="QuaternionF"/> as a 4x4 matrix. Quaternions are represented as matrices in such
/// a way that quaternion multiplication and addition is equivalent to matrix multiplication and addition.
/// Note that there are 48 distinct such matrix representations for a single quaternion.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator M44f(QuaternionF q)
{
return new M44f(
q.W, -q.X, -q.Y, -q.Z,
q.X, q.W, -q.Z, q.Y,
q.Y, q.Z, q.W, -q.X,
q.Z, -q.Y, q.X, q.W);
}
/// <summary>
/// Returns this <see cref="QuaternionF"/> as a <see cref="V4f"/> vector.
/// Note that the components are ordered (w, x, y, z).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator V4f(QuaternionF q)
=> new V4f(q.W, q.X, q.Y, q.Z);
/// <summary>
/// Returns all values of a <see cref="QuaternionF"/> instance
/// in a float[] array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator float[](QuaternionF q)
{
float[] array = new float[4];
array[0] = q.W;
array[1] = q.X;
array[2] = q.Y;
array[3] = q.Z;
return array;
}
#endregion
#region Indexing
/// <summary>
/// Gets or sets the <paramref name="i"/>-th component of the <see cref="QuaternionF"/> with components (w, (x, y, z)).
/// </summary>
public unsafe float this[int i]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (float* ptr = &W) { return ptr[i]; }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
fixed (float* ptr = &W) { ptr[i] = value; }
}
}
#endregion
#region Overrides
public override int GetHashCode()
{
return HashCode.GetCombined(W, X, Y, Z);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(QuaternionF other)
=> W.Equals(other.W) && X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z);
public override bool Equals(object other)
=> (other is QuaternionF o) ? Equals(o) : false;
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "[{0}, {1}, {2}, {3}]", W, X, Y, Z);
}
public static QuaternionF Parse(string s)
{
var x = s.NestedBracketSplitLevelOne().ToArray();
return new QuaternionF(float.Parse(x[0], CultureInfo.InvariantCulture), float.Parse(x[1], CultureInfo.InvariantCulture), float.Parse(x[2], CultureInfo.InvariantCulture), float.Parse(x[3], CultureInfo.InvariantCulture));
}
#endregion
}
public static partial class Quaternion
{
#region Invert, Normalize, Conjugate, Dot
/// <summary>
/// Returns the inverse of a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF Inverse(QuaternionF q)
=> q.Inverse;
/// <summary>
/// Inverts a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Invert(this ref QuaternionF q)
{
var norm = q.NormSquared;
if (norm > 0)
{
var scale = 1 / norm;
q.W *= scale;
q.X *= -scale;
q.Y *= -scale;
q.Z *= -scale;
}
}
/// <summary>
/// Returns a normalized copy of a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF Normalized(QuaternionF q)
=> q.Normalized;
/// <summary>
/// Normalizes a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Normalize(this ref QuaternionF q)
{
var norm = q.Norm;
if (norm > 0)
{
var scale = 1 / norm;
q.W *= scale;
q.X *= scale;
q.Y *= scale;
q.Z *= scale;
}
}
/// <summary>
/// Returns the conjugate of a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionF Conjugated(QuaternionF q)
=> q.Conjugated;
/// <summary>
/// Conjugates a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Conjugate(this ref QuaternionF q)
{
q.X = -q.X;
q.Y = -q.Y;
q.Z = -q.Z;
}
/// <summary>
/// Returns the dot product of two <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(this QuaternionF a, QuaternionF b)
{
return a.W * b.W + a.X * b.X + a.Y * b.Y + a.Z * b.Z;
}
#endregion
#region Norm
/// <summary>
/// Gets the squared norm (or length) of a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float NormSquared(QuaternionF q)
=> q.NormSquared;
/// <summary>
/// Gets the norm (or length) of a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Norm(QuaternionF q)
=> q.Norm;
#endregion
#region Spherical Linear Interpolation
/// <summary>
/// Spherical linear interpolation.
///
/// Assumes q1 and q2 are normalized and that t in [0,1].
///
/// This method interpolates along the shortest arc between q1 and q2.
/// </summary>
public static QuaternionF SlerpShortest(this QuaternionF q1, QuaternionF q2, float t)
{
QuaternionF q3 = q2;
float cosomega = Dot(q1, q3);
if (cosomega < 0)
{
cosomega = -cosomega;
q3 = -q3;
}
if (cosomega >= 1)
{
// Special case: q1 and q2 are the same, so just return one of them.
// This also catches the case where cosomega is very slightly > 1.0
return q1;
}
float sinomega = Fun.Sqrt(1 - cosomega * cosomega);
QuaternionF result;
if (sinomega * float.MaxValue > 1)
{
float omega = Fun.Acos(cosomega);
float s1 = Fun.Sin((1 - t) * omega) / sinomega;
float s2 = Fun.Sin(t * omega) / sinomega;
result = new QuaternionF(s1 * q1 + s2 * q3);
}
else if (cosomega > 0)
{
// omega == 0
float s1 = 1 - t;
float s2 = t;
result = new QuaternionF(s1 * q1 + s2 * q3);
}
else
{
// omega == -pi
result = new QuaternionF(q1.Z, -q1.Y, q1.X, -q1.W);
float s1 = Fun.Sin((0.5f - t) * ConstantF.Pi);
float s2 = Fun.Sin(t * ConstantF.Pi);
result = new QuaternionF(s1 * q1 + s2 * result);
}
return result;
}
#endregion
}
public static partial class Fun
{
#region ApproximateEquals
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool ApproximateEquals(this QuaternionF q0, QuaternionF q1)
{
return ApproximateEquals(q0, q1, Constant<float>.PositiveTinyValue);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool ApproximateEquals(this QuaternionF q0, QuaternionF q1, float tolerance)
{
return ApproximateEquals(q0.W, q1.W, tolerance) && ApproximateEquals(q0.X, q1.X, tolerance) && ApproximateEquals(q0.Y, q1.Y, tolerance) && ApproximateEquals(q0.Z, q1.Z, tolerance);
}
#endregion
}
#endregion
#region QuaternionD
/// <summary>
/// Struct for general quaternions, for rotations in 3-dimensional space use <see cref="Rot3d"/>.
/// </summary>
[DataContract]
[StructLayout(LayoutKind.Sequential)]
public struct QuaternionD : IEquatable<QuaternionD>
{
/// <summary>
/// Scalar (real) part of the quaternion.
/// </summary>
[DataMember]
public double W;
/// <summary>
/// First component of vector (imaginary) part of the quaternion.
/// </summary>
[DataMember]
public double X;
/// <summary>
/// Second component of vector (imaginary) part of the quaternion.
/// </summary>
[DataMember]
public double Y;
/// <summary>
/// Third component of vector (imaginary) part of the quaternion.
/// </summary>
[DataMember]
public double Z;
#region Constructors
/// <summary>
/// Creates a <see cref="QuaternionD"/> (a, (a, a, a)).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionD(double a)
{
W = a;
X = a; Y = a; Z = a;
}
/// <summary>
/// Creates a <see cref="QuaternionD"/> (w, (x, y, z)).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionD(double w, double x, double y, double z)
{
W = w;
X = x; Y = y; Z = z;
}
/// <summary>
/// Creates a <see cref="QuaternionD"/> (v.x, (v.y, v.z, v.w)).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionD(V4d v)
{
W = v.X;
X = v.Y; Y = v.Z; Z = v.W;
}
/// <summary>
/// Creates a <see cref="QuaternionD"/> (w, (v.x, v.y, v.z)).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionD(double w, V3d v)
{
W = w;
X = v.X; Y = v.Y; Z = v.Z;
}
/// <summary>
/// Creates a copy of the given <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionD(QuaternionD q)
{
W = q.W; X = q.X; Y = q.Y; Z = q.Z;
}
/// <summary>
/// Creates a <see cref="QuaternionD"/> from the given <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionD(QuaternionF q)
{
W = (double)q.W; X = (double)q.X; Y = (double)q.Y; Z = (double)q.Z;
}
/// <summary>
/// Creates a <see cref="QuaternionD"/> from the given <see cref="Rot3d"/> transformation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionD(Rot3d r)
{
W = r.W; X = r.X; Y = r.Y; Z = r.Z;
}
/// <summary>
/// Creates a <see cref="QuaternionD"/> from the given <see cref="Rot3f"/> transformation.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionD(Rot3f r)
{
W = (double)r.W; X = (double)r.X; Y = (double)r.Y; Z = (double)r.Z;
}
/// <summary>
/// Creates a <see cref="QuaternionD"/> from an array.
/// (w = a[0], (x = a[1], y = a[2], z = a[3])).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionD(double[] a)
{
W = a[0];
X = a[1]; Y = a[2]; Z = a[3];
}
/// <summary>
/// Creates a <see cref="QuaternionD"/> from an array starting at specified index.
/// (w = a[start], (x = a[start+1], y = a[start+2], z = a[start+3])).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public QuaternionD(double[] a, int start)
{
W = a[start];
X = a[start + 1]; Y = a[start + 2]; Z = a[start + 3];
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the vector part (x, y, z) of this <see cref="QuaternionD"/>.
/// </summary>
[XmlIgnore]
public V3d V
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return new V3d(X, Y, Z); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set { X = value.X; Y = value.Y; Z = value.Z; }
}
/// <summary>
/// Gets the squared norm (or squared length) of this <see cref="QuaternionD"/>.
/// </summary>
public double NormSquared
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => W * W + X * X + Y * Y + Z * Z;
}
/// <summary>
/// Gets the norm (or length) of this <see cref="QuaternionD"/>.
/// </summary>
public double Norm
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => NormSquared.Sqrt();
}
/// <summary>
/// Gets normalized (unit) quaternion from this <see cref="QuaternionD"/>
/// </summary>
public QuaternionD Normalized
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
var rs = new QuaternionD(this);
rs.Normalize();
return rs;
}
}
/// <summary>
/// Gets the (multiplicative) inverse of this <see cref="QuaternionD"/>.
/// The zero quaternion is returned, if this quaternion is zero.
/// </summary>
public QuaternionD Inverse
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
var rs = new QuaternionD(this);
rs.Invert();
return rs;
}
}
/// <summary>
/// Gets the conjugate of this <see cref="QuaternionD"/>.
/// For unit quaternions this is the same as its inverse.
/// </summary>
public QuaternionD Conjugated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionD(W, -V);
}
/// <summary>
/// Gets if this <see cref="QuaternionD"/> is zero.
/// </summary>
public bool IsZero
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => (W == 0) && (X == 0) && (Y == 0) && (Z == 0);
}
#endregion
#region Constants
/// <summary>
/// Gets a <see cref="QuaternionD"/> with (0, (0, 0, 0)).
/// </summary>
public static QuaternionD Zero
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionD(0);
}
/// <summary>
/// Gets a <see cref="QuaternionD"/> with (1, (0, 0, 0)).
/// </summary>
public static QuaternionD One
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionD(1, 0, 0, 0);
}
/// <summary>
/// Gets the identity <see cref="QuaternionD"/> with (1, (0, 0, 0)).
/// </summary>
public static QuaternionD Identity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionD(1, 0, 0, 0);
}
/// <summary>
/// Gets a <see cref="QuaternionD"/> with (0, (1, 0, 0)).
/// </summary>
public static QuaternionD I
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionD(0, 1, 0, 0);
}
/// <summary>
/// Gets a <see cref="QuaternionD"/> with (0, (0, 1, 0)).
/// </summary>
public static QuaternionD J
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionD(0, 0, 1, 0);
}
/// <summary>
/// Gets a <see cref="QuaternionD"/> with (0, (0, 0, 1)).
/// </summary>
public static QuaternionD K
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => new QuaternionD(0, 0, 0, 1);
}
#endregion
#region Arithmetic Operators
/// <summary>
/// Returns the component-wise negation of a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator -(QuaternionD q)
=> new QuaternionD(-q.W, -q.X, -q.Y, -q.Z);
/// <summary>
/// Returns the sum of two <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator +(QuaternionD a, QuaternionD b)
=> new QuaternionD(a.W + b.W, a.X + b.X, a.Y + b.Y, a.Z + b.Z);
/// <summary>
/// Returns the sum of a <see cref="QuaternionD"/> and a real scalar.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator +(QuaternionD q, double s)
=> new QuaternionD(q.W + s, q.X, q.Y, q.Z);
/// <summary>
/// Returns the sum of a real scalar and a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator +(double s, QuaternionD q)
=> new QuaternionD(q.W + s, q.X, q.Y, q.Z);
/// <summary>
/// Returns the difference between two <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator -(QuaternionD a, QuaternionD b)
=> new QuaternionD(a.W - b.W, a.X - b.X, a.Y - b.Y, a.Z - b.Z);
/// <summary>
/// Returns the difference between a <see cref="QuaternionD"/> and a real scalar.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator -(QuaternionD q, double s)
=> new QuaternionD(q.W - s, q.X, q.Y, q.Z);
/// <summary>
/// Returns the difference between a real scalar and a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator -(double s, QuaternionD q)
=> new QuaternionD(s - q.W, -q.X, -q.Y, -q.Z);
/// <summary>
/// Returns the product of a <see cref="QuaternionD"/> and a scalar.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator *(QuaternionD q, double s)
=> new QuaternionD(q.W * s, q.X * s, q.Y * s, q.Z * s);
/// <summary>
/// Returns the product of a scalar and a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator *(double s, QuaternionD q)
=> new QuaternionD(q.W * s, q.X * s, q.Y * s, q.Z * s);
/// <summary>
/// Multiplies two <see cref="QuaternionD"/>.
/// Attention: Multiplication is NOT commutative!
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator *(QuaternionD a, QuaternionD b)
{
return new QuaternionD(
a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z,
a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y,
a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z,
a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X);
}
/// <summary>
/// Divides two <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator /(QuaternionD a, QuaternionD b)
=> a * b.Inverse;
/// <summary>
/// Divides a <see cref="QuaternionD"/> by a scalar.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator /(QuaternionD q, double s)
=> new QuaternionD(q.W / s, q.X / s, q.Y / s, q.Z / s);
/// <summary>
/// Divides a scalar by a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD operator /(double s, QuaternionD q)
=> new QuaternionD(s / q.W, s / q.X, s / q.Y, s / q.Z);
#endregion
#region Comparison Operators
/// <summary>
/// Checks whether two <see cref="QuaternionD"/> are equal.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(QuaternionD q0, QuaternionD q1)
=> q0.W == q1.W && q0.X == q1.X && q0.Y == q1.Y && q0.Z == q1.Z;
/// <summary>
/// Checks whether two <see cref="QuaternionD"/> are different.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(QuaternionD q0, QuaternionD q1)
=> q0.W != q1.W || q0.X != q1.X || q0.Y != q1.Y || q0.Z != q1.Z;
#endregion
#region Conversions
/// <summary>
/// Conversion from a <see cref="QuaternionD"/> to a <see cref="QuaternionF"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator QuaternionF(QuaternionD q)
=> new QuaternionF(q);
/// <summary>
/// Returns this <see cref="QuaternionD"/> as a 4x4 matrix. Quaternions are represented as matrices in such
/// a way that quaternion multiplication and addition is equivalent to matrix multiplication and addition.
/// Note that there are 48 distinct such matrix representations for a single quaternion.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator M44d(QuaternionD q)
{
return new M44d(
q.W, -q.X, -q.Y, -q.Z,
q.X, q.W, -q.Z, q.Y,
q.Y, q.Z, q.W, -q.X,
q.Z, -q.Y, q.X, q.W);
}
/// <summary>
/// Returns this <see cref="QuaternionD"/> as a <see cref="V4d"/> vector.
/// Note that the components are ordered (w, x, y, z).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator V4d(QuaternionD q)
=> new V4d(q.W, q.X, q.Y, q.Z);
/// <summary>
/// Returns all values of a <see cref="QuaternionD"/> instance
/// in a double[] array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static explicit operator double[](QuaternionD q)
{
double[] array = new double[4];
array[0] = q.W;
array[1] = q.X;
array[2] = q.Y;
array[3] = q.Z;
return array;
}
#endregion
#region Indexing
/// <summary>
/// Gets or sets the <paramref name="i"/>-th component of the <see cref="QuaternionD"/> with components (w, (x, y, z)).
/// </summary>
public unsafe double this[int i]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (double* ptr = &W) { return ptr[i]; }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
fixed (double* ptr = &W) { ptr[i] = value; }
}
}
#endregion
#region Overrides
public override int GetHashCode()
{
return HashCode.GetCombined(W, X, Y, Z);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(QuaternionD other)
=> W.Equals(other.W) && X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z);
public override bool Equals(object other)
=> (other is QuaternionD o) ? Equals(o) : false;
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "[{0}, {1}, {2}, {3}]", W, X, Y, Z);
}
public static QuaternionD Parse(string s)
{
var x = s.NestedBracketSplitLevelOne().ToArray();
return new QuaternionD(double.Parse(x[0], CultureInfo.InvariantCulture), double.Parse(x[1], CultureInfo.InvariantCulture), double.Parse(x[2], CultureInfo.InvariantCulture), double.Parse(x[3], CultureInfo.InvariantCulture));
}
#endregion
}
public static partial class Quaternion
{
#region Invert, Normalize, Conjugate, Dot
/// <summary>
/// Returns the inverse of a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD Inverse(QuaternionD q)
=> q.Inverse;
/// <summary>
/// Inverts a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Invert(this ref QuaternionD q)
{
var norm = q.NormSquared;
if (norm > 0)
{
var scale = 1 / norm;
q.W *= scale;
q.X *= -scale;
q.Y *= -scale;
q.Z *= -scale;
}
}
/// <summary>
/// Returns a normalized copy of a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD Normalized(QuaternionD q)
=> q.Normalized;
/// <summary>
/// Normalizes a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Normalize(this ref QuaternionD q)
{
var norm = q.Norm;
if (norm > 0)
{
var scale = 1 / norm;
q.W *= scale;
q.X *= scale;
q.Y *= scale;
q.Z *= scale;
}
}
/// <summary>
/// Returns the conjugate of a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static QuaternionD Conjugated(QuaternionD q)
=> q.Conjugated;
/// <summary>
/// Conjugates a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Conjugate(this ref QuaternionD q)
{
q.X = -q.X;
q.Y = -q.Y;
q.Z = -q.Z;
}
/// <summary>
/// Returns the dot product of two <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Dot(this QuaternionD a, QuaternionD b)
{
return a.W * b.W + a.X * b.X + a.Y * b.Y + a.Z * b.Z;
}
#endregion
#region Norm
/// <summary>
/// Gets the squared norm (or length) of a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double NormSquared(QuaternionD q)
=> q.NormSquared;
/// <summary>
/// Gets the norm (or length) of a <see cref="QuaternionD"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Norm(QuaternionD q)
=> q.Norm;
#endregion
#region Spherical Linear Interpolation
/// <summary>
/// Spherical linear interpolation.
///
/// Assumes q1 and q2 are normalized and that t in [0,1].
///
/// This method interpolates along the shortest arc between q1 and q2.
/// </summary>
public static QuaternionD SlerpShortest(this QuaternionD q1, QuaternionD q2, double t)
{
QuaternionD q3 = q2;
double cosomega = Dot(q1, q3);
if (cosomega < 0)
{
cosomega = -cosomega;
q3 = -q3;
}
if (cosomega >= 1)
{
// Special case: q1 and q2 are the same, so just return one of them.
// This also catches the case where cosomega is very slightly > 1.0
return q1;
}
double sinomega = Fun.Sqrt(1 - cosomega * cosomega);
QuaternionD result;
if (sinomega * double.MaxValue > 1)
{
double omega = Fun.Acos(cosomega);
double s1 = Fun.Sin((1 - t) * omega) / sinomega;
double s2 = Fun.Sin(t * omega) / sinomega;
result = new QuaternionD(s1 * q1 + s2 * q3);
}
else if (cosomega > 0)
{
// omega == 0
double s1 = 1 - t;
double s2 = t;
result = new QuaternionD(s1 * q1 + s2 * q3);
}
else
{
// omega == -pi
result = new QuaternionD(q1.Z, -q1.Y, q1.X, -q1.W);
double s1 = Fun.Sin((0.5 - t) * Constant.Pi);
double s2 = Fun.Sin(t * Constant.Pi);
result = new QuaternionD(s1 * q1 + s2 * result);
}
return result;
}
#endregion
}
public static partial class Fun
{
#region ApproximateEquals
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool ApproximateEquals(this QuaternionD q0, QuaternionD q1)
{
return ApproximateEquals(q0, q1, Constant<double>.PositiveTinyValue);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool ApproximateEquals(this QuaternionD q0, QuaternionD q1, double tolerance)
{
return ApproximateEquals(q0.W, q1.W, tolerance) && ApproximateEquals(q0.X, q1.X, tolerance) && ApproximateEquals(q0.Y, q1.Y, tolerance) && ApproximateEquals(q0.Z, q1.Z, tolerance);
}
#endregion
}
#endregion
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using NPOI.OpenXmlFormats.Spreadsheet;
using System;
using System.Xml;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel.Extensions;
using NPOI.XSSF.Model;
namespace NPOI.XSSF.UserModel
{
/**
*
* High level representation of the the possible formatting information for the contents of the cells on a sheet in a
* SpreadsheetML document.
*
* @see NPOI.xssf.usermodel.XSSFWorkbook#CreateCellStyle()
* @see NPOI.xssf.usermodel.XSSFWorkbook#getCellStyleAt(short)
* @see NPOI.xssf.usermodel.XSSFCell#setCellStyle(NPOI.ss.usermodel.CellStyle)
*/
public class XSSFCellStyle : ICellStyle
{
private int _cellXfId;
private StylesTable _stylesSource;
private CT_Xf _cellXf;
private CT_Xf _cellStyleXf;
private XSSFFont _font;
private XSSFCellAlignment _cellAlignment;
private ThemesTable _theme;
/**
* Creates a Cell Style from the supplied parts
* @param cellXfId The main XF for the cell. Must be a valid 0-based index into the XF table
* @param cellStyleXfId Optional, style xf. A value of <code>-1</code> means no xf.
* @param stylesSource Styles Source to work off
*/
public XSSFCellStyle(int cellXfId, int cellStyleXfId, StylesTable stylesSource, ThemesTable theme)
{
_cellXfId = cellXfId;
_stylesSource = stylesSource;
_cellXf = stylesSource.GetCellXfAt(this._cellXfId);
_cellStyleXf = cellStyleXfId == -1 ? null : stylesSource.GetCellStyleXfAt(cellStyleXfId);
_theme = theme;
}
/**
* Used so that StylesSource can figure out our location
*/
public CT_Xf GetCoreXf()
{
return _cellXf;
}
/**
* Used so that StylesSource can figure out our location
*/
public CT_Xf GetStyleXf()
{
return _cellStyleXf;
}
/// <summary>
/// Creates an empty Cell Style
/// </summary>
/// <param name="stylesSource"></param>
public XSSFCellStyle(StylesTable stylesSource)
{
_stylesSource = stylesSource;
// We need a new CT_Xf for the main styles
// TODO decide on a style ctxf
_cellXf = new CT_Xf();
_cellStyleXf = null;
}
/**
* Verifies that this style belongs to the supplied Workbook
* Styles Source.
* Will throw an exception if it belongs to a different one.
* This is normally called when trying to assign a style to a
* cell, to ensure the cell and the style are from the same
* workbook (if they're not, it won't work)
* @throws ArgumentException if there's a workbook mis-match
*/
public void VerifyBelongsToStylesSource(StylesTable src)
{
if (this._stylesSource != src)
{
throw new ArgumentException("This Style does not belong to the supplied Workbook Stlyes Source. Are you trying to assign a style from one workbook to the cell of a differnt workbook?");
}
}
/**
* Clones all the style information from another
* XSSFCellStyle, onto this one. This
* XSSFCellStyle will then have all the same
* properties as the source, but the two may
* be edited independently.
* Any stylings on this XSSFCellStyle will be lost!
*
* The source XSSFCellStyle could be from another
* XSSFWorkbook if you like. This allows you to
* copy styles from one XSSFWorkbook to another.
*/
public void CloneStyleFrom(ICellStyle source)
{
if (source is XSSFCellStyle)
{
XSSFCellStyle src = (XSSFCellStyle)source;
// Is it on our Workbook?
if (src._stylesSource == _stylesSource)
{
// Nice and easy
_cellXf = src.GetCoreXf().Copy();
_cellStyleXf = src.GetStyleXf().Copy();
}
else
{
// Copy the style
try
{
// Remove any children off the current style, to
// avoid orphaned nodes
if (_cellXf.IsSetAlignment())
_cellXf.UnsetAlignment();
if (_cellXf.IsSetExtLst())
_cellXf.UnsetExtLst();
// Create a new Xf with the same contents
_cellXf =
src.GetCoreXf().Copy();
// Swap it over
_stylesSource.ReplaceCellXfAt(_cellXfId, _cellXf);
}
catch (XmlException e)
{
throw new POIXMLException(e);
}
// Copy the format
String fmt = src.GetDataFormatString();
DataFormat = (
(new XSSFDataFormat(_stylesSource)).GetFormat(fmt)
);
// Copy the font
try
{
CT_Font ctFont =
src.GetFont().GetCTFont().Clone();
XSSFFont font = new XSSFFont(ctFont);
font.RegisterTo(_stylesSource);
SetFont(font);
}
catch (XmlException e)
{
throw new POIXMLException(e);
}
}
// Clear out cached details
_font = null;
_cellAlignment = null;
}
else
{
throw new ArgumentException("Can only clone from one XSSFCellStyle to another, not between HSSFCellStyle and XSSFCellStyle");
}
}
public HorizontalAlignment Alignment
{
get
{
return GetAlignmentEnum();
}
set
{
GetCellAlignment().Horizontal = value;
}
}
/// <summary>
/// Get the type of horizontal alignment for the cell
/// </summary>
/// <returns>the type of alignment</returns>
internal HorizontalAlignment GetAlignmentEnum()
{
CT_CellAlignment align = _cellXf.alignment;
if (align != null && align.IsSetHorizontal())
{
return (HorizontalAlignment)align.horizontal;
}
return HorizontalAlignment.General;
}
public BorderStyle BorderBottom
{
get
{
if (!_cellXf.applyBorder) return BorderStyle.None;
int idx = (int)_cellXf.borderId;
CT_Border ct = _stylesSource.GetBorderAt(idx).GetCTBorder();
if (!ct.IsSetBottom())
{
return BorderStyle.None;
}
else
{
return (BorderStyle)ct.bottom.style;
}
}
set
{
CT_Border ct = GetCTBorder();
CT_BorderPr pr = ct.IsSetBottom() ? ct.bottom : ct.AddNewBottom();
if (value == BorderStyle.None) ct.unsetBottom();
else pr.style = (ST_BorderStyle)value;
int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme));
_cellXf.borderId = (uint)idx;
_cellXf.applyBorder = (true);
}
}
public BorderStyle BorderLeft
{
get
{
if (!_cellXf.applyBorder) return BorderStyle.None;
int idx = (int)_cellXf.borderId;
CT_Border ct = _stylesSource.GetBorderAt(idx).GetCTBorder();
if (!ct.IsSetLeft())
{
return BorderStyle.None;
}
else
{
return (BorderStyle)ct.left.style;
}
}
set
{
CT_Border ct = GetCTBorder();
CT_BorderPr pr = ct.IsSetLeft() ? ct.left : ct.AddNewLeft();
if (value == BorderStyle.None) ct.unsetLeft();
else pr.style = (ST_BorderStyle)value;
int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme));
_cellXf.borderId = (uint)idx;
_cellXf.applyBorder = (true);
}
}
/// <summary>
/// Get the type of border to use for the right border of the cell
/// </summary>
public BorderStyle BorderRight
{
get
{
if (!_cellXf.applyBorder) return BorderStyle.None;
int idx = (int)_cellXf.borderId;
CT_Border ct = _stylesSource.GetBorderAt(idx).GetCTBorder();
if (!ct.IsSetRight())
{
return BorderStyle.None;
}
else
{
return (BorderStyle)ct.right.style;
}
}
set
{
CT_Border ct = GetCTBorder();
CT_BorderPr pr = ct.IsSetRight() ? ct.right : ct.AddNewRight();
if (value == BorderStyle.None) ct.unsetRight();
else pr.style = (ST_BorderStyle)value;
int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme));
_cellXf.borderId = (uint)idx;
_cellXf.applyBorder = (true);
}
}
public BorderStyle BorderTop
{
get
{
if (!_cellXf.applyBorder) return BorderStyle.None;
int idx = (int)_cellXf.borderId;
CT_Border ct = _stylesSource.GetBorderAt(idx).GetCTBorder();
if (!ct.IsSetTop())
{
return BorderStyle.None;
}
else
{
return (BorderStyle)ct.top.style;
}
}
set
{
CT_Border ct = GetCTBorder();
CT_BorderPr pr = ct.IsSetTop() ? ct.top : ct.AddNewTop();
if (value == BorderStyle.None) ct.unsetTop();
else pr.style = (ST_BorderStyle)value;
int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme));
_cellXf.borderId = (uint)idx;
_cellXf.applyBorder = (true);
}
}
/**
* Get the color to use for the bottom border
* Color is optional. When missing, IndexedColors.Automatic is implied.
* @return the index of the color defInition, default value is {@link NPOI.ss.usermodel.IndexedColors#AUTOMATIC}
* @see NPOI.ss.usermodel.IndexedColors
*/
public short BottomBorderColor
{
get
{
XSSFColor clr = BottomBorderXSSFColor;
return clr == null ? IndexedColors.Black.Index : clr.Indexed;
}
set
{
XSSFColor clr = new XSSFColor();
clr.Indexed = value;
SetBottomBorderColor(clr);
}
}
/**
* Get the color to use for the bottom border as a {@link XSSFColor}
*
* @return the used color or <code>null</code> if not Set
*/
public XSSFColor BottomBorderXSSFColor
{
get
{
if (!_cellXf.applyBorder) return null;
int idx = (int)_cellXf.borderId;
XSSFCellBorder border = _stylesSource.GetBorderAt(idx);
return border.GetBorderColor(BorderSide.BOTTOM);
}
}
/**
* Get the index of the number format (numFmt) record used by this cell format.
*
* @return the index of the number format
*/
public short DataFormat
{
get
{
return (short)_cellXf.numFmtId;
}
set
{
_cellXf.applyNumberFormat = (true);
_cellXf.numFmtId = (uint)value;
}
}
/**
* Get the contents of the format string, by looking up
* the StylesSource
*
* @return the number format string
*/
public String GetDataFormatString()
{
int idx = DataFormat;
return new XSSFDataFormat(_stylesSource).GetFormat((short)idx);
}
/// <summary>
/// Get the background fill color.
/// Note - many cells are actually filled with a foreground fill, not a background fill
/// </summary>
public short FillBackgroundColor
{
get
{
XSSFColor clr = (XSSFColor)this.FillBackgroundColorColor;
return clr == null ? IndexedColors.Automatic.Index : clr.Indexed;
}
set
{
XSSFColor clr = new XSSFColor();
clr.Indexed = (value);
SetFillBackgroundColor(clr);
}
}
/**
* Get the background fill color.
* <p>
* Note - many cells are actually Filled with a foreground
* Fill, not a background fill - see {@link #getFillForegroundColor()}
* </p>
* @see NPOI.xssf.usermodel.XSSFColor#getRgb()
* @return XSSFColor - fill color or <code>null</code> if not Set
*/
public IColor FillBackgroundColorColor
{
get
{
return this.FillBackgroundXSSFColor;
}
set
{
this.FillBackgroundXSSFColor = (XSSFColor)value;
}
}
public XSSFColor FillBackgroundXSSFColor
{
get
{
if (!_cellXf.applyFill) return null;
int fillIndex = (int)_cellXf.fillId;
XSSFCellFill fg = _stylesSource.GetFillAt(fillIndex);
XSSFColor fillBackgroundColor = fg.GetFillBackgroundColor();
if (fillBackgroundColor != null && _theme != null)
{
_theme.InheritFromThemeAsRequired(fillBackgroundColor);
}
return fillBackgroundColor;
}
set
{
CT_Fill ct = GetCTFill();
CT_PatternFill ptrn = ct.patternFill;
if (value == null)
{
if (ptrn != null) ptrn.UnsetBgColor();
}
else
{
if (ptrn == null) ptrn = ct.AddNewPatternFill();
ptrn.bgColor = (value.GetCTColor());
}
int idx = _stylesSource.PutFill(new XSSFCellFill(ct));
_cellXf.fillId = (uint)(idx);
_cellXf.applyFill = (true);
}
}
/**
* Get the foreground fill color.
* <p>
* Many cells are Filled with this, instead of a
* background color ({@link #getFillBackgroundColor()})
* </p>
* @see IndexedColors
* @return fill color, default value is {@link NPOI.ss.usermodel.IndexedColors#AUTOMATIC}
*/
public short FillForegroundColor
{
get
{
XSSFColor clr = (XSSFColor)this.FillForegroundColorColor;
return clr == null ? IndexedColors.Automatic.Index : clr.Indexed;
}
set
{
XSSFColor clr = new XSSFColor();
clr.Indexed = (value);
SetFillForegroundColor(clr);
}
}
/// <summary>
/// Get the foreground fill color.
/// </summary>
public IColor FillForegroundColorColor
{
get
{
return this.FillForegroundXSSFColor;
}
set
{
this.FillForegroundXSSFColor = (XSSFColor)value;
}
}
/// <summary>
/// Get the foreground fill color.
/// </summary>
public XSSFColor FillForegroundXSSFColor
{
get
{
if (!_cellXf.applyFill) return null;
int fillIndex = (int)_cellXf.fillId;
XSSFCellFill fg = _stylesSource.GetFillAt(fillIndex);
XSSFColor fillForegroundColor = fg.GetFillForegroundColor();
if (fillForegroundColor != null && _theme != null)
{
_theme.InheritFromThemeAsRequired(fillForegroundColor);
}
return fillForegroundColor;
}
set
{
CT_Fill ct = GetCTFill();
CT_PatternFill ptrn = ct.patternFill;
if (value == null)
{
if (ptrn != null) ptrn.UnsetFgColor();
}
else
{
if (ptrn == null) ptrn = ct.AddNewPatternFill();
ptrn.fgColor = (value.GetCTColor());
}
int idx = _stylesSource.PutFill(new XSSFCellFill(ct));
_cellXf.fillId = (uint)(idx);
_cellXf.applyFill = (true);
}
}
public FillPattern FillPattern
{
get
{
if (!_cellXf.applyFill) return 0;
int FillIndex = (int)_cellXf.fillId;
XSSFCellFill fill = _stylesSource.GetFillAt(FillIndex);
ST_PatternType ptrn = fill.GetPatternType();
return (FillPattern)ptrn;
}
set
{
CT_Fill ct = GetCTFill();
CT_PatternFill ptrn = ct.IsSetPatternFill() ? ct.GetPatternFill() : ct.AddNewPatternFill();
if (value == FillPattern.NoFill && ptrn.IsSetPatternType())
ptrn.UnsetPatternType();
else ptrn.patternType = (ST_PatternType)value;
int idx = _stylesSource.PutFill(new XSSFCellFill(ct));
_cellXf.fillId = (uint)idx;
_cellXf.applyFill = (true);
}
}
/**
* Gets the font for this style
* @return Font - font
*/
public XSSFFont GetFont()
{
if (_font == null)
{
_font = _stylesSource.GetFontAt(FontId);
}
return _font;
}
/**
* Gets the index of the font for this style
*
* @return short - font index
* @see NPOI.xssf.usermodel.XSSFWorkbook#getFontAt(short)
*/
public short FontIndex
{
get
{
return (short)FontId;
}
}
/**
* Get whether the cell's using this style are to be hidden
*
* @return bool - whether the cell using this style is hidden
*/
public bool IsHidden
{
get
{
if (!_cellXf.IsSetProtection() || !_cellXf.protection.IsSetHidden())
{
return false;
}
return _cellXf.protection.hidden;
}
set
{
if (!_cellXf.IsSetProtection())
{
_cellXf.AddNewProtection();
}
_cellXf.protection.hidden = (value);
}
}
/**
* Get the number of spaces to indent the text in the cell
*
* @return indent - number of spaces
*/
public short Indention
{
get
{
CT_CellAlignment align = _cellXf.alignment;
return (short)(align == null ? 0 : align.indent);
}
set
{
GetCellAlignment().Indent = value;
}
}
/**
* Get the index within the StylesTable (sequence within the collection of CT_Xf elements)
*
* @return unique index number of the underlying record this style represents
*/
public short Index
{
get
{
return (short)this._cellXfId;
}
}
/**
* Get the color to use for the left border
*
* @return the index of the color defInition, default value is {@link NPOI.ss.usermodel.IndexedColors#BLACK}
* @see NPOI.ss.usermodel.IndexedColors
*/
public short LeftBorderColor
{
get
{
XSSFColor clr = LeftBorderXSSFColor;
return clr == null ? IndexedColors.Black.Index : clr.Indexed;
}
set
{
XSSFColor clr = new XSSFColor();
clr.Indexed = (value);
SetLeftBorderColor(clr);
}
}
public XSSFColor DiagonalBorderXSSFColor
{
get
{
if (!_cellXf.applyBorder) return null;
int idx = (int)_cellXf.borderId;
XSSFCellBorder border = _stylesSource.GetBorderAt(idx);
return border.GetBorderColor(BorderSide.DIAGONAL);
}
}
/**
* Get the color to use for the left border
*
* @return the index of the color defInition or <code>null</code> if not Set
* @see NPOI.ss.usermodel.IndexedColors
*/
public XSSFColor LeftBorderXSSFColor
{
get
{
if (!_cellXf.applyBorder) return null;
int idx = (int)_cellXf.borderId;
XSSFCellBorder border = _stylesSource.GetBorderAt(idx);
return border.GetBorderColor(BorderSide.LEFT);
}
}
/// <summary>
/// Get whether the cell's using this style are locked
/// </summary>
public bool IsLocked
{
get
{
if (!_cellXf.IsSetProtection())
{
return true;
}
return _cellXf.protection.locked;
}
set
{
if (!_cellXf.IsSetProtection())
{
_cellXf.AddNewProtection();
}
_cellXf.protection.locked = value;
}
}
/// <summary>
/// Get the color to use for the right border
/// </summary>
public short RightBorderColor
{
get
{
XSSFColor clr = RightBorderXSSFColor;
return clr == null ? IndexedColors.Black.Index : clr.Indexed;
}
set
{
XSSFColor clr = new XSSFColor();
clr.Indexed = (value);
SetRightBorderColor(clr);
}
}
/// <summary>
/// Get the color to use for the right border
/// </summary>
/// <returns></returns>
public XSSFColor RightBorderXSSFColor
{
get
{
if (!_cellXf.applyBorder) return null;
int idx = (int)_cellXf.borderId;
XSSFCellBorder border = _stylesSource.GetBorderAt(idx);
return border.GetBorderColor(BorderSide.RIGHT);
}
}
/// <summary>
/// Get the degree of rotation (between 0 and 180 degrees) for the text in the cell
/// </summary>
/// <example>
/// Expressed in degrees. Values range from 0 to 180. The first letter of
/// the text is considered the center-point of the arc.
/// For 0 - 90, the value represents degrees above horizon. For 91-180 the degrees below the horizon is calculated as:
/// <code>[degrees below horizon] = 90 - textRotation.</code>
/// </example>
public short Rotation
{
get
{
CT_CellAlignment align = _cellXf.alignment;
return (short)(align == null ? 0 : align.textRotation);
}
set
{
GetCellAlignment().TextRotation = value;
}
}
/**
* Get the color to use for the top border
*
* @return the index of the color defInition, default value is {@link NPOI.ss.usermodel.IndexedColors#BLACK}
* @see NPOI.ss.usermodel.IndexedColors
*/
public short TopBorderColor
{
get
{
XSSFColor clr = TopBorderXSSFColor;
return clr == null ? IndexedColors.Black.Index : clr.Indexed;
}
set
{
XSSFColor clr = new XSSFColor();
clr.Indexed = (value);
SetTopBorderColor(clr);
}
}
/// <summary>
/// Get the color to use for the top border
/// </summary>
/// <returns></returns>
public XSSFColor TopBorderXSSFColor
{
get
{
if (!_cellXf.applyBorder) return null;
int idx = (int)_cellXf.borderId;
XSSFCellBorder border = _stylesSource.GetBorderAt(idx);
return border.GetBorderColor(BorderSide.TOP);
}
}
/// <summary>
/// Get the type of vertical alignment for the cell
/// </summary>
public VerticalAlignment VerticalAlignment
{
get
{
return GetVerticalAlignmentEnum();
}
set
{
GetCellAlignment().Vertical = value;
}
}
/// <summary>
/// Get the type of vertical alignment for the cell
/// </summary>
/// <returns></returns>
internal VerticalAlignment GetVerticalAlignmentEnum()
{
CT_CellAlignment align = _cellXf.alignment;
if (align != null && align.IsSetVertical())
{
return (VerticalAlignment)align.vertical;
}
return VerticalAlignment.Bottom;
}
/// <summary>
/// Whether the text in a cell should be line-wrapped within the cell.
/// </summary>
public bool WrapText
{
get
{
CT_CellAlignment align = _cellXf.alignment;
return align != null && align.wrapText;
}
set
{
GetCellAlignment().WrapText = value;
}
}
/**
* Set the color to use for the bottom border
*
* @param color the color to use, null means no color
*/
public void SetBottomBorderColor(XSSFColor color)
{
CT_Border ct = GetCTBorder();
if (color == null && !ct.IsSetBottom()) return;
CT_BorderPr pr = ct.IsSetBottom() ? ct.bottom : ct.AddNewBottom();
if (color != null) pr.SetColor(color.GetCTColor());
else pr.UnsetColor();
int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme));
_cellXf.borderId = (uint)idx;
_cellXf.applyBorder = (true);
}
/**
* Set the background fill color represented as a {@link XSSFColor} value.
* <p>
* For example:
* <pre>
* cs.SetFillPattern(XSSFCellStyle.FINE_DOTS );
* cs.SetFillBackgroundXSSFColor(new XSSFColor(java.awt.Color.RED));
* </pre>
* optionally a Foreground and background fill can be applied:
* <i>Note: Ensure Foreground color is set prior to background</i>
* <pre>
* cs.SetFillPattern(XSSFCellStyle.FINE_DOTS );
* cs.SetFillForegroundColor(new XSSFColor(java.awt.Color.BLUE));
* cs.SetFillBackgroundColor(new XSSFColor(java.awt.Color.GREEN));
* </pre>
* or, for the special case of SOLID_FILL:
* <pre>
* cs.SetFillPattern(XSSFCellStyle.SOLID_FOREGROUND );
* cs.SetFillForegroundColor(new XSSFColor(java.awt.Color.GREEN));
* </pre>
* It is necessary to set the fill style in order
* for the color to be shown in the cell.
*
* @param color - the color to use
*/
public void SetFillBackgroundColor(XSSFColor color)
{
CT_Fill ct = GetCTFill();
CT_PatternFill ptrn = ct.GetPatternFill();
if (color == null)
{
if (ptrn != null) ptrn.UnsetBgColor();
}
else
{
if (ptrn == null) ptrn = ct.AddNewPatternFill();
ptrn.bgColor = color.GetCTColor();
}
int idx = _stylesSource.PutFill(new XSSFCellFill(ct));
_cellXf.fillId = (uint)idx;
_cellXf.applyFill = (true);
}
/**
* Set the foreground fill color represented as a {@link XSSFColor} value.
* <br/>
* <i>Note: Ensure Foreground color is Set prior to background color.</i>
* @param color the color to use
* @see #setFillBackgroundColor(NPOI.xssf.usermodel.XSSFColor) )
*/
public void SetFillForegroundColor(XSSFColor color)
{
CT_Fill ct = GetCTFill();
CT_PatternFill ptrn = ct.GetPatternFill();
if (color == null)
{
if (ptrn != null) ptrn.UnsetFgColor();
}
else
{
if (ptrn == null) ptrn = ct.AddNewPatternFill();
ptrn.fgColor = (color.GetCTColor());
}
int idx = _stylesSource.PutFill(new XSSFCellFill(ct));
_cellXf.fillId = (uint)idx;
_cellXf.applyFill = (true);
}
/**
* Get a <b>copy</b> of the currently used CT_Fill, if none is used, return a new instance.
*/
public CT_Fill GetCTFill()
{
CT_Fill ct;
if (_cellXf.applyFill)
{
int FillIndex = (int)_cellXf.fillId;
XSSFCellFill cf = _stylesSource.GetFillAt(FillIndex);
ct = (CT_Fill)cf.GetCTFill().Copy();
}
else
{
ct = new CT_Fill();
}
return ct;
}
/**
* Get a <b>copy</b> of the currently used CT_Border, if none is used, return a new instance.
*/
public CT_Border GetCTBorder()
{
CT_Border ctBorder;
if (_cellXf.applyBorder)
{
int idx = (int)_cellXf.borderId;
XSSFCellBorder cf = _stylesSource.GetBorderAt(idx);
ctBorder = (CT_Border)cf.GetCTBorder();
}
else
{
ctBorder = new CT_Border();
ctBorder.AddNewLeft();
ctBorder.AddNewRight();
ctBorder.AddNewTop();
ctBorder.AddNewBottom();
ctBorder.AddNewDiagonal();
}
return ctBorder;
}
/**
* Set the font for this style
*
* @param font a font object Created or retreived from the XSSFWorkbook object
* @see NPOI.xssf.usermodel.XSSFWorkbook#CreateFont()
* @see NPOI.xssf.usermodel.XSSFWorkbook#getFontAt(short)
*/
public void SetFont(IFont font)
{
if (font != null)
{
long index = font.Index;
this._cellXf.fontId = (uint)index;
this._cellXf.fontIdSpecified = true;
this._cellXf.applyFont = (true);
}
else
{
this._cellXf.applyFont = (false);
}
}
public void SetDiagonalBorderColor(XSSFColor color)
{
CT_Border ct = GetCTBorder();
if (color == null && !ct.IsSetDiagonal()) return;
CT_BorderPr pr = ct.IsSetDiagonal() ? ct.diagonal : ct.AddNewDiagonal();
if (color != null) pr.color = (color.GetCTColor());
else pr.UnsetColor();
int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme));
_cellXf.borderId = (uint)idx;
_cellXf.applyBorder = (true);
}
/**
* Set the color to use for the left border as a {@link XSSFColor} value
*
* @param color the color to use
*/
public void SetLeftBorderColor(XSSFColor color)
{
CT_Border ct = GetCTBorder();
if (color == null && !ct.IsSetLeft()) return;
CT_BorderPr pr = ct.IsSetLeft() ? ct.left : ct.AddNewLeft();
if (color != null) pr.color = (color.GetCTColor());
else pr.UnsetColor();
int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme));
_cellXf.borderId = (uint)idx;
_cellXf.applyBorder = (true);
}
/**
* Set the color to use for the right border as a {@link XSSFColor} value
*
* @param color the color to use
*/
public void SetRightBorderColor(XSSFColor color)
{
CT_Border ct = GetCTBorder();
if (color == null && !ct.IsSetRight()) return;
CT_BorderPr pr = ct.IsSetRight() ? ct.right : ct.AddNewRight();
if (color != null) pr.color = (color.GetCTColor());
else pr.UnsetColor();
int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme));
_cellXf.borderId = (uint)(idx);
_cellXf.applyBorder = (true);
}
/**
* Set the color to use for the top border as a {@link XSSFColor} value
*
* @param color the color to use
*/
public void SetTopBorderColor(XSSFColor color)
{
CT_Border ct = GetCTBorder();
if (color == null && !ct.IsSetTop()) return;
CT_BorderPr pr = ct.IsSetTop() ? ct.top : ct.AddNewTop();
if (color != null) pr.color = color.GetCTColor();
else pr.UnsetColor();
int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme));
_cellXf.borderId = (uint)idx;
_cellXf.applyBorder = (true);
}
/**
* Set the type of vertical alignment for the cell
*
* @param align - align the type of alignment
* @see NPOI.ss.usermodel.CellStyle#VERTICAL_TOP
* @see NPOI.ss.usermodel.CellStyle#VERTICAL_CENTER
* @see NPOI.ss.usermodel.CellStyle#VERTICAL_BOTTOM
* @see NPOI.ss.usermodel.CellStyle#VERTICAL_JUSTIFY
* @see NPOI.ss.usermodel.VerticalAlignment
*/
public void SetVerticalAlignment(short align)
{
GetCellAlignment().Vertical = (VerticalAlignment)align;
}
/**
* Gets border color
*
* @param side the border side
* @return the used color
*/
public XSSFColor GetBorderColor(BorderSide side)
{
switch (side)
{
case BorderSide.BOTTOM:
return BottomBorderXSSFColor;
case BorderSide.RIGHT:
return RightBorderXSSFColor;
case BorderSide.TOP:
return TopBorderXSSFColor;
case BorderSide.LEFT:
return LeftBorderXSSFColor;
default:
throw new ArgumentException("Unknown border: " + side);
}
}
/**
* Set the color to use for the selected border
*
* @param side - where to apply the color defInition
* @param color - the color to use
*/
public void SetBorderColor(BorderSide side, XSSFColor color)
{
switch (side)
{
case BorderSide.BOTTOM:
SetBottomBorderColor(color);
break;
case BorderSide.RIGHT:
SetRightBorderColor(color);
break;
case BorderSide.TOP:
SetTopBorderColor(color);
break;
case BorderSide.LEFT:
SetLeftBorderColor(color);
break;
}
}
private int FontId
{
get
{
if (_cellXf.IsSetFontId())
{
return (int)_cellXf.fontId;
}
return (int)_cellStyleXf.fontId;
}
}
/**
* Get the cellAlignment object to use for manage alignment
* @return XSSFCellAlignment - cell alignment
*/
internal XSSFCellAlignment GetCellAlignment()
{
if (this._cellAlignment == null)
{
this._cellAlignment = new XSSFCellAlignment(GetCTCellAlignment());
}
return this._cellAlignment;
}
/**
* Return the CT_CellAlignment instance for alignment
*
* @return CT_CellAlignment
*/
internal CT_CellAlignment GetCTCellAlignment()
{
if (_cellXf.alignment == null)
{
_cellXf.alignment = new CT_CellAlignment();
}
return _cellXf.alignment;
}
/**
* Returns a hash code value for the object. The hash is derived from the underlying CT_Xf bean.
*
* @return the hash code value for this style
*/
public override int GetHashCode()
{
return _cellXf.ToString().GetHashCode();
}
/**
* Checks is the supplied style is equal to this style
*
* @param o the style to check
* @return true if the supplied style is equal to this style
*/
public override bool Equals(Object o)
{
if (o == null || !(o is XSSFCellStyle)) return false;
XSSFCellStyle cf = (XSSFCellStyle)o;
return _cellXf.ToString().Equals(cf.GetCoreXf().ToString());
}
/**
* Make a copy of this style. The underlying CT_Xf bean is Cloned,
* the references to Fills and borders remain.
*
* @return a copy of this style
*/
public Object Clone()
{
CT_Xf xf = (CT_Xf)_cellXf.Copy();
int xfSize = _stylesSource.StyleXfsSize;
int indexXf = _stylesSource.PutCellXf(xf);
return new XSSFCellStyle(indexXf - 1, xfSize - 1, _stylesSource, _theme);
}
#region ICellStyle Members
public IFont GetFont(IWorkbook parentWorkbook)
{
return this.GetFont();
}
public bool ShrinkToFit
{
get
{
CT_CellAlignment align = _cellXf.alignment;
return align != null && align.shrinkToFit;
}
set
{
GetCTCellAlignment().shrinkToFit = value;
}
}
public short BorderDiagonalColor
{
get
{
XSSFColor clr = DiagonalBorderXSSFColor;
return clr == null ? IndexedColors.Black.Index : clr.Indexed;
}
set
{
XSSFColor clr = new XSSFColor();
clr.Indexed = (value);
SetDiagonalBorderColor(clr);
}
}
public BorderStyle BorderDiagonalLineStyle
{
get
{
if (!_cellXf.applyBorder) return BorderStyle.None;
int idx = (int)_cellXf.borderId;
CT_Border ct = _stylesSource.GetBorderAt(idx).GetCTBorder();
if (!ct.IsSetDiagonal())
{
return BorderStyle.None;
}
else
{
return (BorderStyle)ct.diagonal.style;
}
}
set
{
CT_Border ct = GetCTBorder();
CT_BorderPr pr = ct.IsSetDiagonal() ? ct.diagonal : ct.AddNewDiagonal();
if (value == BorderStyle.None)
ct.unsetDiagonal();
else
pr.style = (ST_BorderStyle)value;
int idx = _stylesSource.PutBorder(new XSSFCellBorder(ct, _theme));
_cellXf.borderId = (uint)idx;
_cellXf.applyBorder = (true);
}
}
public BorderDiagonal BorderDiagonal
{
get
{
CT_Border ct = GetCTBorder();
if (ct.diagonalDown == true && ct.diagonalUp == true)
return BorderDiagonal.Both;
else if (ct.diagonalDown == true)
return BorderDiagonal.Backward;
else if (ct.diagonalUp == true)
return BorderDiagonal.Forward;
else
return BorderDiagonal.None;
}
set
{
CT_Border ct = GetCTBorder();
if (value == BorderDiagonal.Both)
{
ct.diagonalDown = true;
ct.diagonalDownSpecified = true;
ct.diagonalUp = true;
ct.diagonalUpSpecified = true;
}
else if (value == BorderDiagonal.Forward)
{
ct.diagonalDown = false;
ct.diagonalDownSpecified = false;
ct.diagonalUp = true;
ct.diagonalUpSpecified = true;
}
else if (value == BorderDiagonal.Backward)
{
ct.diagonalDown = true;
ct.diagonalDownSpecified = true;
ct.diagonalUp = false;
ct.diagonalUpSpecified = false;
}
else
{
ct.unsetDiagonal();
ct.diagonalDown = false;
ct.diagonalDownSpecified = false;
ct.diagonalUp = false;
ct.diagonalUpSpecified = false;
}
}
}
#endregion
}
}
| |
//
// EndPointListener.cs
// Copied from System.Net.EndPointListener.cs
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2012-2013 sta.blockhead
//
// 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.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace WebSocketSharp.Net
{
internal sealed class EndPointListener
{
#region Private Fields
List<ListenerPrefix> _all; // host = '+'
X509Certificate2 _cert;
IPEndPoint _endpoint;
Dictionary<ListenerPrefix, HttpListener> _prefixes;
bool _secure;
Socket _socket;
List<ListenerPrefix> _unhandled; // host = '*'
Dictionary<HttpConnection, HttpConnection> _unregistered;
#endregion
#region Public Constructors
public EndPointListener (
IPAddress address,
int port,
bool secure,
string certFolderPath,
X509Certificate2 defaultCert
)
{
if (secure) {
_secure = secure;
_cert = getCertificate (port, certFolderPath, defaultCert);
if (_cert == null)
throw new ArgumentException ("Server certificate not found.");
}
_endpoint = new IPEndPoint (address, port);
_socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind (_endpoint);
_socket.Listen (500);
var args = new SocketAsyncEventArgs ();
args.UserToken = this;
args.Completed += onAccept;
_socket.AcceptAsync (args);
_prefixes = new Dictionary<ListenerPrefix, HttpListener> ();
_unregistered = new Dictionary<HttpConnection, HttpConnection> ();
}
#endregion
#region Private Methods
private static void addSpecial (List<ListenerPrefix> prefixes, ListenerPrefix prefix)
{
if (prefixes == null)
return;
foreach (var p in prefixes)
if (p.Path == prefix.Path) // TODO: code
throw new HttpListenerException (400, "Prefix already in use.");
prefixes.Add (prefix);
}
private void checkIfRemove ()
{
if (_prefixes.Count > 0)
return;
if (_unhandled != null && _unhandled.Count > 0)
return;
if (_all != null && _all.Count > 0)
return;
EndPointManager.RemoveEndPoint (this, _endpoint);
}
private static RSACryptoServiceProvider createRSAFromFile (string filename)
{
var rsa = new RSACryptoServiceProvider ();
byte[] pvk = null;
using (var fs = File.Open (filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
pvk = new byte [fs.Length];
fs.Read (pvk, 0, pvk.Length);
}
rsa.ImportCspBlob (pvk);
return rsa;
}
private static X509Certificate2 getCertificate (
int port, string certFolderPath, X509Certificate2 defaultCert)
{
try {
var cer = Path.Combine (certFolderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (certFolderPath, String.Format ("{0}.key", port));
if (File.Exists (cer) && File.Exists (key))
{
var cert = new X509Certificate2 (cer);
cert.PrivateKey = createRSAFromFile (key);
return cert;
}
}
catch {
}
return defaultCert;
}
private static HttpListener matchFromList (
string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
{
prefix = null;
if (list == null)
return null;
HttpListener best_match = null;
var best_length = -1;
foreach (var p in list)
{
var ppath = p.Path;
if (ppath.Length < best_length)
continue;
if (path.StartsWith (ppath))
{
best_length = ppath.Length;
best_match = p.Listener;
prefix = p;
}
}
return best_match;
}
private static void onAccept (object sender, EventArgs e)
{
var args = (SocketAsyncEventArgs) e;
var epListener = (EndPointListener) args.UserToken;
Socket accepted = null;
if (args.SocketError == SocketError.Success)
{
accepted = args.AcceptSocket;
args.AcceptSocket = null;
}
try {
epListener._socket.AcceptAsync (args);
}
catch {
if (accepted != null)
accepted.Close ();
return;
}
if (accepted == null)
return;
HttpConnection conn = null;
try {
conn = new HttpConnection (accepted, epListener, epListener._secure, epListener._cert);
lock (((ICollection) epListener._unregistered).SyncRoot)
{
epListener._unregistered [conn] = conn;
}
conn.BeginReadRequest ();
}
catch {
if (conn != null)
{
conn.Close (true);
return;
}
accepted.Close ();
}
}
private static bool removeSpecial (List<ListenerPrefix> prefixes, ListenerPrefix prefix)
{
if (prefixes == null)
return false;
var count = prefixes.Count;
for (int i = 0; i < count; i++)
{
if (prefixes [i].Path == prefix.Path)
{
prefixes.RemoveAt (i);
return true;
}
}
return false;
}
private HttpListener searchListener (Uri uri, out ListenerPrefix prefix)
{
prefix = null;
if (uri == null)
return null;
var host = uri.Host;
var port = uri.Port;
var path = HttpUtility.UrlDecode (uri.AbsolutePath);
var path_slash = path [path.Length - 1] == '/' ? path : path + "/";
HttpListener best_match = null;
var best_length = -1;
if (host != null && host.Length > 0)
{
foreach (var p in _prefixes.Keys)
{
var ppath = p.Path;
if (ppath.Length < best_length)
continue;
if (p.Host != host || p.Port != port)
continue;
if (path.StartsWith (ppath) || path_slash.StartsWith (ppath))
{
best_length = ppath.Length;
best_match = _prefixes [p];
prefix = p;
}
}
if (best_length != -1)
return best_match;
}
var list = _unhandled;
best_match = matchFromList (host, path, list, out prefix);
if (path != path_slash && best_match == null)
best_match = matchFromList (host, path_slash, list, out prefix);
if (best_match != null)
return best_match;
list = _all;
best_match = matchFromList (host, path, list, out prefix);
if (path != path_slash && best_match == null)
best_match = matchFromList (host, path_slash, list, out prefix);
if (best_match != null)
return best_match;
return null;
}
#endregion
#region Internal Methods
internal static bool CertificateExists (int port, string certFolderPath)
{
var cer = Path.Combine (certFolderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (certFolderPath, String.Format ("{0}.key", port));
return File.Exists (cer) && File.Exists (key);
}
internal void RemoveConnection (HttpConnection connection)
{
lock (((ICollection) _unregistered).SyncRoot)
{
_unregistered.Remove (connection);
}
}
#endregion
#region Public Methods
public void AddPrefix (ListenerPrefix prefix, HttpListener listener)
{
List<ListenerPrefix> current, future;
if (prefix.Host == "*")
{
do {
current = _unhandled;
future = current != null
? new List<ListenerPrefix> (current)
: new List<ListenerPrefix> ();
prefix.Listener = listener;
addSpecial (future, prefix);
} while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);
return;
}
if (prefix.Host == "+")
{
do {
current = _all;
future = current != null
? new List<ListenerPrefix> (current)
: new List<ListenerPrefix> ();
prefix.Listener = listener;
addSpecial (future, prefix);
} while (Interlocked.CompareExchange (ref _all, future, current) != current);
return;
}
Dictionary<ListenerPrefix, HttpListener> prefs, p2;
do {
prefs = _prefixes;
if (prefs.ContainsKey (prefix))
{
HttpListener other = prefs [prefix];
if (other != listener) // TODO: code.
throw new HttpListenerException (400, "There's another listener for " + prefix);
return;
}
p2 = new Dictionary<ListenerPrefix, HttpListener> (prefs);
p2 [prefix] = listener;
} while (Interlocked.CompareExchange (ref _prefixes, p2, prefs) != prefs);
}
public bool BindContext (HttpListenerContext context)
{
var req = context.Request;
ListenerPrefix prefix;
var listener = searchListener (req.Url, out prefix);
if (listener == null)
return false;
context.Listener = listener;
context.Connection.Prefix = prefix;
return true;
}
public void Close ()
{
_socket.Close ();
lock (((ICollection) _unregistered).SyncRoot)
{
var copy = new Dictionary<HttpConnection, HttpConnection> (_unregistered);
foreach (var conn in copy.Keys)
conn.Close (true);
copy.Clear ();
_unregistered.Clear ();
}
}
public void RemovePrefix (ListenerPrefix prefix, HttpListener listener)
{
List<ListenerPrefix> current, future;
if (prefix.Host == "*")
{
do {
current = _unhandled;
future = current != null
? new List<ListenerPrefix> (current)
: new List<ListenerPrefix> ();
if (!removeSpecial (future, prefix))
break; // Prefix not found.
} while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);
checkIfRemove ();
return;
}
if (prefix.Host == "+")
{
do {
current = _all;
future = current != null
? new List<ListenerPrefix> (current)
: new List<ListenerPrefix> ();
if (!removeSpecial (future, prefix))
break; // Prefix not found.
} while (Interlocked.CompareExchange (ref _all, future, current) != current);
checkIfRemove ();
return;
}
Dictionary<ListenerPrefix, HttpListener> prefs, p2;
do {
prefs = _prefixes;
if (!prefs.ContainsKey (prefix))
break;
p2 = new Dictionary<ListenerPrefix, HttpListener> (prefs);
p2.Remove (prefix);
} while (Interlocked.CompareExchange (ref _prefixes, p2, prefs) != prefs);
checkIfRemove ();
}
public void UnbindContext (HttpListenerContext context)
{
if (context == null || context.Request == null)
return;
context.Listener.UnregisterContext (context);
}
#endregion
}
}
| |
// 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
// Do not warn about missing documentation.
#pragma warning disable 1591
namespace FalkenTests
{
public sealed class EnemyExampleEntity : Falken.EntityBase
{
[Falken.Range(-1f, 1f)]
public float lookUpAngle = 0.5f;
public bool shoot = true;
[Falken.Range(2, 5)]
public int energy = 3;
public FalkenWeaponEnum weapon = FalkenWeaponEnum.Shotgun;
public Falken.Number numberAttribute = new Falken.Number(0, 1);
public Falken.Category categoryAttribute = new Falken.Category(
new List<string>(){"yes", "no", "yes, and"});
public Falken.Boolean booleanAttribute = new Falken.Boolean();
}
public sealed class SimpleExampleEntity : Falken.EntityBase
{
public bool friend = true;
}
public sealed class SimpleExampleEntityWithFeelers : Falken.EntityBase
{
public Falken.Feelers feeler =
new Falken.Feelers(4.0f, 1.0f, 180.0f, 14,
new List<string>() { "Nothing", "Enemy", "Wall" });
}
public class EnemyEntityTestContainer : Falken.EntityContainer
{
public EnemyExampleEntity enemy = new EnemyExampleEntity();
}
public sealed class TwoEntitiesTestContainer : EnemyEntityTestContainer
{
public SimpleExampleEntity simpleEnemy = new SimpleExampleEntity();
}
public sealed class UnsupportedTypesTestEntity : Falken.EntityBase
{
[Falken.Range(2, 5)]
public int energy = 3;
public double unsupportedType = 1.0;
}
public sealed class UnsupportedTypesEntityContainerTest :
Falken.EntityContainer
{
public UnsupportedTypesTestEntity unsupportedEntity =
new UnsupportedTypesTestEntity();
}
public sealed class UnsupportedFieldsInContainter : Falken.EntityContainer
{
public double unsupportedType = 4.0;
}
public class EntityTest
{
private FalkenInternal.falken.EntityContainer _falkenContainer;
[SetUp]
public void Setup()
{
_falkenContainer = new FalkenInternal.falken.EntityContainer();
}
[Test]
public void CreateDynamicEntity()
{
Falken.EntityBase entity = new Falken.EntityBase("entity");
}
[Test]
public void CreateDynamicEntityNullName()
{
Assert.That(() => new Falken.EntityBase(null),
Throws.TypeOf<ArgumentNullException>());
}
[Test]
public void BindDynamicEntity()
{
Falken.EntityBase entity = new Falken.EntityBase("entity");
Falken.Boolean boolean = new Falken.Boolean("boolean");
entity["boolean"] = boolean;
entity.BindEntity(null, _falkenContainer);
// Position and rotation attributes are included.
Assert.AreEqual(entity.Count, 3);
Assert.IsTrue(entity.ContainsKey("boolean"));
Falken.Boolean entityBoolean = (Falken.Boolean)entity["boolean"];
Assert.IsTrue(entityBoolean.Bound);
Assert.IsFalse(entityBoolean.Value);
entityBoolean.Value = true;
Assert.IsTrue(entityBoolean.Value);
}
[Test]
public void BindEntity()
{
FieldInfo enemyField =
typeof(EnemyEntityTestContainer).GetField("enemy");
EnemyExampleEntity enemy = new EnemyExampleEntity();
enemy.BindEntity(enemyField, _falkenContainer);
Assert.IsNotNull(_falkenContainer.entity("enemy"));
Assert.IsTrue(enemy.ContainsKey("lookUpAngle"));
Assert.IsTrue(enemy["lookUpAngle"] is Falken.Number);
Falken.Number number = (Falken.Number)enemy["lookUpAngle"];
Assert.AreEqual(-1.0f, number.Minimum);
Assert.AreEqual(1.0f, number.Maximum);
Assert.AreEqual(0.5f, number.Value);
Assert.IsTrue(enemy.ContainsKey("shoot"));
Assert.IsTrue(enemy["shoot"] is Falken.Boolean);
Falken.Boolean boolean = (Falken.Boolean)enemy["shoot"];
Assert.AreEqual(true, boolean.Value);
Assert.IsTrue(enemy.ContainsKey("energy"));
Assert.IsTrue(enemy["energy"] is Falken.Number);
Falken.Number energy = (Falken.Number)enemy["energy"];
Assert.AreEqual(2.0f, energy.Minimum);
Assert.AreEqual(5.0f, energy.Maximum);
Assert.AreEqual(3.0f, energy.Value);
Assert.IsTrue(enemy.ContainsKey("weapon"));
Assert.IsTrue(enemy["weapon"] is Falken.Category);
Falken.Category weapon = (Falken.Category)enemy["weapon"];
Assert.AreEqual(1, weapon.Value);
string[] enum_names = typeof(FalkenWeaponEnum).GetEnumNames();
Assert.IsTrue(
Enumerable.SequenceEqual(enum_names,
weapon.CategoryValues));
Assert.IsTrue(enemy.ContainsKey("numberAttribute"));
Assert.IsTrue(enemy["numberAttribute"] == enemy.numberAttribute);
enemy.numberAttribute.Value = 0.5f;
Assert.AreEqual(enemy.numberAttribute.Value, 0.5f);
Assert.IsTrue(enemy.ContainsKey("booleanAttribute"));
Assert.IsTrue(enemy["booleanAttribute"] == enemy.booleanAttribute);
enemy.booleanAttribute.Value = true;
Assert.AreEqual(enemy.booleanAttribute.Value, true);
Assert.IsTrue(enemy.ContainsKey("categoryAttribute"));
Assert.IsTrue(enemy["categoryAttribute"] == enemy.categoryAttribute);
enemy.categoryAttribute.Value = 1;
Assert.AreEqual(enemy.categoryAttribute.Value, 1);
Assert.IsTrue(enemy.ContainsKey("position"));
Assert.IsTrue(enemy["position"] is Falken.Position);
Falken.Position position = (Falken.Position)enemy["position"];
Falken.PositionVector positionVector = position.Value;
Assert.AreEqual(0.0f, positionVector.X);
Assert.AreEqual(0.0f, positionVector.Y);
Assert.AreEqual(0.0f, positionVector.Z);
Assert.IsTrue(enemy.ContainsKey("rotation"));
Assert.IsTrue(enemy["rotation"] is Falken.Rotation);
Falken.Rotation rotation = (Falken.Rotation)enemy["rotation"];
Falken.RotationQuaternion rotationQuaternion = rotation.Value;
Assert.AreEqual(0.0f, rotationQuaternion.X);
Assert.AreEqual(0.0f, rotationQuaternion.Y);
Assert.AreEqual(0.0f, rotationQuaternion.Z);
Assert.AreEqual(1.0f, rotationQuaternion.W);
}
[Test]
public void BindEntityWithUnsupportedTypes()
{
FieldInfo unsupportedTypesEntityField =
typeof(UnsupportedTypesEntityContainerTest).GetField("unsupportedEntity");
UnsupportedTypesTestEntity unsupportedTypesEntity =
new UnsupportedTypesTestEntity();
Assert.That(() => unsupportedTypesEntity.BindEntity(unsupportedTypesEntityField,
_falkenContainer),
Throws.TypeOf<Falken.UnsupportedFalkenTypeException>()
.With.Message.EqualTo($"Field 'unsupportedType' has unsupported " +
$"type '{typeof(double).ToString()}' " +
"or it does not have the necessary " +
"implicit conversions."));
}
[Test]
public void LoadEntity()
{
FalkenInternal.falken.EntityBase entity =
new FalkenInternal.falken.EntityBase(_falkenContainer, "entity");
FalkenInternal.falken.AttributeBase boolean =
new FalkenInternal.falken.AttributeBase(
entity, "boolean",
FalkenInternal.falken.AttributeBase.Type.kTypeBool);
FalkenInternal.falken.AttributeBase number =
new FalkenInternal.falken.AttributeBase(
entity, "number", -1.0f, 1.0f);
FalkenInternal.falken.AttributeBase category =
new FalkenInternal.falken.AttributeBase(
entity, "category",
new FalkenInternal.std.StringVector() { "zero", "one" });
FalkenInternal.falken.AttributeBase feeler =
new FalkenInternal.falken.AttributeBase(
entity, "feeler", 2,
5.0f, 45.0f, 1.0f,
new FalkenInternal.std.StringVector() { "zero", "one" });
Falken.EntityBase falkenEntity = new Falken.EntityBase("entity");
falkenEntity.LoadEntity(entity);
Assert.IsTrue(falkenEntity.ContainsKey("position"));
Assert.IsTrue(falkenEntity["position"] is Falken.Position);
Assert.IsTrue(falkenEntity["position"].Bound);
Falken.Position positionAttribute = (Falken.Position)falkenEntity["position"];
falkenEntity.position = new Falken.PositionVector(3.0f, 2.0f, 1.0f);
Assert.AreEqual(3.0f, positionAttribute.Value.X);
Assert.AreEqual(2.0f, positionAttribute.Value.Y);
Assert.AreEqual(1.0f, positionAttribute.Value.Z);
FieldInfo positionField = typeof(Falken.EntityBase).GetField("position");
Assert.AreEqual(3.0f, positionAttribute.Value.X);
Assert.AreEqual(2.0f, positionAttribute.Value.Y);
Assert.AreEqual(1.0f, positionAttribute.Value.Z);
}
}
public class InheritedEntityContainer : Falken.EntityContainer
{
[Falken.FalkenInheritedAttribute]
public SimpleExampleEntity inheritedEntity =
new SimpleExampleEntity();
}
public class EntityContainerTest
{
private FalkenInternal.falken.EntityContainer _falkenContainer;
[SetUp]
public void Setup()
{
_falkenContainer = new FalkenInternal.falken.EntityContainer();
}
[Test]
public void AddEntity()
{
Falken.EntityContainer container = new Falken.EntityContainer();
Falken.EntityBase random = new Falken.EntityBase("random");
Assert.AreEqual(0, container.Count);
container["random"] = random;
Assert.IsTrue(container.ContainsKey("random"));
Assert.AreEqual(1, container.Count);
container.Add("random2", new Falken.EntityBase("random2"));
Assert.IsTrue(container.ContainsKey("random2"));
Assert.AreEqual(2, container.Count);
container.Add(
new KeyValuePair<string, Falken.EntityBase>(
"random3", new Falken.EntityBase("random3")));
Assert.IsTrue(container.ContainsKey("random3"));
Assert.AreEqual(3, container.Count);
}
[Test]
public void AddEntityBoundContainer()
{
Falken.EntityContainer container = new Falken.EntityContainer();
Falken.EntityBase random = new Falken.EntityBase("random");
random["boolean"] = new Falken.Boolean("boolean");
container["random"] = random;
container.BindEntities(_falkenContainer);
Assert.That(() => container.Add("random2", new Falken.EntityBase("random2")),
Throws.TypeOf<InvalidOperationException>());
Assert.IsFalse(container.ContainsKey("random2"));
Assert.AreEqual(1, container.Count);
}
[Test]
public void ClearContainer()
{
Falken.EntityContainer container = new Falken.EntityContainer();
Falken.EntityBase random = new Falken.EntityBase("random");
container["random"] = random;
Assert.AreEqual(1, container.Count);
container.Clear();
Assert.AreEqual(0, container.Count);
}
[Test]
public void ClearBoundContainer()
{
Falken.EntityContainer container = new Falken.EntityContainer();
Falken.EntityBase random = new Falken.EntityBase("random");
container["random"] = random;
Assert.AreEqual(1, container.Count);
container.BindEntities(_falkenContainer);
Assert.That(() => container.Clear(),
Throws.TypeOf<InvalidOperationException>());
Assert.AreEqual(1, container.Count);
}
[Test]
public void RemoveEntities()
{
Falken.EntityContainer container = new Falken.EntityContainer();
Falken.EntityBase random = new Falken.EntityBase("random");
container["random"] = random;
container["random2"] = new Falken.EntityBase("random2");
Assert.IsTrue(container.ContainsKey("random"));
Assert.IsTrue(container.Remove("random"));
Assert.IsFalse(container.ContainsKey("random"));
Assert.IsFalse(container.Remove("random"));
Assert.IsTrue(container.ContainsKey("random2"));
}
[Test]
public void RemoveEntitiesFromBoundContainer()
{
Falken.EntityContainer container = new Falken.EntityContainer();
Falken.EntityBase random = new Falken.EntityBase("random");
container["random"] = random;
container["random2"] = new Falken.EntityBase("random2");
container.BindEntities(_falkenContainer);
Assert.That(() => container.Remove("random"),
Throws.TypeOf<InvalidOperationException>());
Assert.IsTrue(container.ContainsKey("random"));
}
[Test]
public void TryGetEntityValue()
{
Falken.EntityContainer container = new Falken.EntityContainer();
container["random"] = new Falken.EntityBase("random");
Falken.EntityBase entity = null;
Assert.IsTrue(container.TryGetValue("random", out entity));
Assert.IsNotNull(entity);
Assert.IsFalse(container.TryGetValue("random2", out entity));
Assert.IsNull(entity);
}
[Test]
public void TryGetEntityValueBoundContainer()
{
Falken.EntityContainer container = new Falken.EntityContainer();
container["random"] = new Falken.EntityBase("random");
container.BindEntities(_falkenContainer);
Falken.EntityBase entity = null;
Assert.IsTrue(container.TryGetValue("random", out entity));
Assert.IsNotNull(entity);
Assert.IsFalse(container.TryGetValue("random2", out entity));
Assert.IsNull(entity);
}
[Test]
public void ReadOnly()
{
Falken.EntityContainer container = new Falken.EntityContainer();
Assert.IsFalse(container.IsReadOnly);
container["random"] = new Falken.EntityBase("random");
container.BindEntities(_falkenContainer);
Assert.IsTrue(container.IsReadOnly);
}
[Test]
public void GetKeys()
{
Falken.EntityContainer container = new Falken.EntityContainer();
container["random"] = new Falken.EntityBase("random");
container["random2"] = new Falken.EntityBase("random2");
ICollection<string> keys = container.Keys;
Assert.AreEqual(2, keys.Count);
Assert.IsTrue(keys.Contains("random"));
Assert.IsTrue(keys.Contains("random2"));
}
[Test]
public void GetValues()
{
Falken.EntityContainer container = new Falken.EntityContainer();
container["random"] = new Falken.EntityBase("random");
container["random2"] = new Falken.EntityBase("random2");
ICollection<Falken.EntityBase> values = container.Values;
Assert.AreEqual(2, values.Count);
}
[Test]
public void BindDynamicEntity()
{
Falken.EntityBase entity = new Falken.EntityBase("entity");
Falken.Boolean boolean = new Falken.Boolean("boolean");
entity["boolean"] = boolean;
Falken.EntityContainer container = new Falken.EntityContainer();
container["entity"] = entity;
container.BindEntities(_falkenContainer);
Assert.AreEqual(container.Count, 1);
Assert.IsTrue(container.ContainsKey("entity"));
Assert.IsTrue(container["entity"].ContainsKey("boolean"));
}
[Test]
public void BindSharedDynamicEntity()
{
Falken.EntityBase entity = new Falken.EntityBase("entity");
Falken.Boolean boolean = new Falken.Boolean("boolean");
entity["boolean"] = boolean;
Falken.EntityContainer container = new Falken.EntityContainer();
container["entity"] = entity;
container.BindEntities(_falkenContainer);
Falken.EntityContainer anotherContainer =
new Falken.EntityContainer();
anotherContainer["entity"] = entity;
Assert.That(() => anotherContainer.BindEntities(_falkenContainer),
Throws.TypeOf<Falken.AlreadyBoundException>()
.With.Message.EqualTo($"Can't bind entity container. Entity " +
$"'{entity.Name}' is already bound."));
}
[Test]
public void BindEntityContainer()
{
TwoEntitiesTestContainer container =
new TwoEntitiesTestContainer();
container.BindEntities(_falkenContainer);
Assert.IsTrue(container.ContainsKey("enemy"));
Assert.IsTrue(container.ContainsKey("simpleEnemy"));
Assert.IsTrue(container["simpleEnemy"].ContainsKey("friend"));
}
[Test]
public void BindEntityContainerUnsupportedType()
{
UnsupportedFieldsInContainter container =
new UnsupportedFieldsInContainter();
Assert.That(() => container.BindEntities(_falkenContainer),
Throws.TypeOf<Falken.UnsupportedFalkenTypeException>()
.With.Message.EqualTo("Can't bind entity container because " +
"'unsupportedType' has an unsupported " +
"type 'System.Double'. Make sure that your field " +
"inherits from 'Falken.Entity'. "));
}
[Test]
public void BindInheritedEntityContainer()
{
FalkenInternal.falken.EntityBase inheritedEntity =
new FalkenInternal.falken.EntityBase(
_falkenContainer, "inheritedEntity");
InheritedEntityContainer container =
new InheritedEntityContainer();
container.BindEntities(_falkenContainer);
Assert.IsTrue(container.ContainsKey("inheritedEntity"));
}
[Test]
public void BindInheritedEntityWrongNameContainer()
{
FalkenInternal.falken.EntityBase inheritedEntity =
new FalkenInternal.falken.EntityBase(
_falkenContainer, "anotherName");
InheritedEntityContainer container =
new InheritedEntityContainer();
using (var ignoreErrorMessages = new IgnoreErrorMessages())
{
Assert.That(() => container.BindEntities(_falkenContainer),
Throws.TypeOf<Falken.InheritedAttributeNotFoundException>()
.With.Message.EqualTo("Inherited entity field 'inheritedEntity' " +
"was not found in the entity container."));
}
}
[Test]
public void RebindEntityContainer()
{
EnemyEntityTestContainer enemyContainer = new EnemyEntityTestContainer();
enemyContainer.BindEntities(_falkenContainer);
FalkenInternal.falken.EntityContainer otherContainer =
new FalkenInternal.falken.EntityContainer();
FalkenInternal.falken.EntityBase enemyEntity =
new FalkenInternal.falken.EntityBase(otherContainer, "enemy");
FalkenInternal.falken.AttributeBase lookUpAttribute =
new FalkenInternal.falken.AttributeBase(enemyEntity, "lookUpAngle", -1.0f, 1.0f);
FalkenInternal.falken.AttributeBase shootAttribute =
new FalkenInternal.falken.AttributeBase(enemyEntity, "shoot",
FalkenInternal.falken.AttributeBase.Type.kTypeBool);
FalkenInternal.falken.AttributeBase energyAttribute =
new FalkenInternal.falken.AttributeBase(enemyEntity, "energy", 2.0f, 5.0f);
FalkenInternal.falken.AttributeBase weaponAttribute =
new FalkenInternal.falken.AttributeBase(enemyEntity, "weapon",
new FalkenInternal.std.StringVector(
typeof(FalkenWeaponEnum).GetEnumNames()));
FalkenInternal.falken.AttributeBase falkenNumberAttribute =
new FalkenInternal.falken.AttributeBase(enemyEntity, "numberAttribute", 0.0f, 1.0f);
FalkenInternal.falken.AttributeBase falkenBooleanAttribute =
new FalkenInternal.falken.AttributeBase(enemyEntity, "booleanAttribute",
FalkenInternal.falken.AttributeBase.Type.kTypeBool);
FalkenInternal.falken.AttributeBase falkenCategoryAttribute =
new FalkenInternal.falken.AttributeBase(enemyEntity, "categoryAttribute",
new FalkenInternal.std.StringVector() { "yes", "no", "yes, and" });
Falken.Boolean shootBoolean = (Falken.Boolean)enemyContainer["enemy"]["shoot"];
shootBoolean.Value = true;
Falken.Number lookUp = (Falken.Number)enemyContainer["enemy"]["lookUpAngle"];
Falken.Number numberAttribute =
(Falken.Number)enemyContainer["enemy"]["numberAttribute"];
enemyContainer.Rebind(otherContainer);
lookUp.Value = 0.5f;
numberAttribute.Value = 0.5f;
Assert.IsTrue(shootBoolean.Value);
Assert.AreEqual(0.5f, lookUp.Value);
Assert.AreEqual(0.5f, numberAttribute.Value);
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// A virtual network
/// First published in XenServer 4.0.
/// </summary>
public partial class Network : XenObject<Network>
{
public Network()
{
}
public Network(string uuid,
string name_label,
string name_description,
List<network_operations> allowed_operations,
Dictionary<string, network_operations> current_operations,
List<XenRef<VIF>> VIFs,
List<XenRef<PIF>> PIFs,
long MTU,
Dictionary<string, string> other_config,
string bridge,
bool managed,
Dictionary<string, XenRef<Blob>> blobs,
string[] tags,
network_default_locking_mode default_locking_mode,
Dictionary<XenRef<VIF>, string> assigned_ips,
List<network_purpose> purpose)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.allowed_operations = allowed_operations;
this.current_operations = current_operations;
this.VIFs = VIFs;
this.PIFs = PIFs;
this.MTU = MTU;
this.other_config = other_config;
this.bridge = bridge;
this.managed = managed;
this.blobs = blobs;
this.tags = tags;
this.default_locking_mode = default_locking_mode;
this.assigned_ips = assigned_ips;
this.purpose = purpose;
}
/// <summary>
/// Creates a new Network from a Proxy_Network.
/// </summary>
/// <param name="proxy"></param>
public Network(Proxy_Network proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Network.
/// </summary>
public override void UpdateFrom(Network update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
allowed_operations = update.allowed_operations;
current_operations = update.current_operations;
VIFs = update.VIFs;
PIFs = update.PIFs;
MTU = update.MTU;
other_config = update.other_config;
bridge = update.bridge;
managed = update.managed;
blobs = update.blobs;
tags = update.tags;
default_locking_mode = update.default_locking_mode;
assigned_ips = update.assigned_ips;
purpose = update.purpose;
}
internal void UpdateFromProxy(Proxy_Network proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<network_operations>(proxy.allowed_operations);
current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_network_operations(proxy.current_operations);
VIFs = proxy.VIFs == null ? null : XenRef<VIF>.Create(proxy.VIFs);
PIFs = proxy.PIFs == null ? null : XenRef<PIF>.Create(proxy.PIFs);
MTU = proxy.MTU == null ? 0 : long.Parse((string)proxy.MTU);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
bridge = proxy.bridge == null ? null : (string)proxy.bridge;
managed = (bool)proxy.managed;
blobs = proxy.blobs == null ? null : Maps.convert_from_proxy_string_XenRefBlob(proxy.blobs);
tags = proxy.tags == null ? new string[] {} : (string [])proxy.tags;
default_locking_mode = proxy.default_locking_mode == null ? (network_default_locking_mode) 0 : (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), (string)proxy.default_locking_mode);
assigned_ips = proxy.assigned_ips == null ? null : Maps.convert_from_proxy_XenRefVIF_string(proxy.assigned_ips);
purpose = proxy.purpose == null ? null : Helper.StringArrayToEnumList<network_purpose>(proxy.purpose);
}
public Proxy_Network ToProxy()
{
Proxy_Network result_ = new Proxy_Network();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {};
result_.current_operations = Maps.convert_to_proxy_string_network_operations(current_operations);
result_.VIFs = (VIFs != null) ? Helper.RefListToStringArray(VIFs) : new string[] {};
result_.PIFs = (PIFs != null) ? Helper.RefListToStringArray(PIFs) : new string[] {};
result_.MTU = MTU.ToString();
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.bridge = bridge ?? "";
result_.managed = managed;
result_.blobs = Maps.convert_to_proxy_string_XenRefBlob(blobs);
result_.tags = tags;
result_.default_locking_mode = network_default_locking_mode_helper.ToString(default_locking_mode);
result_.assigned_ips = Maps.convert_to_proxy_XenRefVIF_string(assigned_ips);
result_.purpose = (purpose != null) ? Helper.ObjectListToStringArray(purpose) : new string[] {};
return result_;
}
/// <summary>
/// Creates a new Network from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Network(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Network
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("allowed_operations"))
allowed_operations = Helper.StringArrayToEnumList<network_operations>(Marshalling.ParseStringArray(table, "allowed_operations"));
if (table.ContainsKey("current_operations"))
current_operations = Maps.convert_from_proxy_string_network_operations(Marshalling.ParseHashTable(table, "current_operations"));
if (table.ContainsKey("VIFs"))
VIFs = Marshalling.ParseSetRef<VIF>(table, "VIFs");
if (table.ContainsKey("PIFs"))
PIFs = Marshalling.ParseSetRef<PIF>(table, "PIFs");
if (table.ContainsKey("MTU"))
MTU = Marshalling.ParseLong(table, "MTU");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("bridge"))
bridge = Marshalling.ParseString(table, "bridge");
if (table.ContainsKey("managed"))
managed = Marshalling.ParseBool(table, "managed");
if (table.ContainsKey("blobs"))
blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs"));
if (table.ContainsKey("tags"))
tags = Marshalling.ParseStringArray(table, "tags");
if (table.ContainsKey("default_locking_mode"))
default_locking_mode = (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), Marshalling.ParseString(table, "default_locking_mode"));
if (table.ContainsKey("assigned_ips"))
assigned_ips = Maps.convert_from_proxy_XenRefVIF_string(Marshalling.ParseHashTable(table, "assigned_ips"));
if (table.ContainsKey("purpose"))
purpose = Helper.StringArrayToEnumList<network_purpose>(Marshalling.ParseStringArray(table, "purpose"));
}
public bool DeepEquals(Network other, bool ignoreCurrentOperations)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations))
return false;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._allowed_operations, other._allowed_operations) &&
Helper.AreEqual2(this._VIFs, other._VIFs) &&
Helper.AreEqual2(this._PIFs, other._PIFs) &&
Helper.AreEqual2(this._MTU, other._MTU) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._bridge, other._bridge) &&
Helper.AreEqual2(this._managed, other._managed) &&
Helper.AreEqual2(this._blobs, other._blobs) &&
Helper.AreEqual2(this._tags, other._tags) &&
Helper.AreEqual2(this._default_locking_mode, other._default_locking_mode) &&
Helper.AreEqual2(this._assigned_ips, other._assigned_ips) &&
Helper.AreEqual2(this._purpose, other._purpose);
}
internal static List<Network> ProxyArrayToObjectList(Proxy_Network[] input)
{
var result = new List<Network>();
foreach (var item in input)
result.Add(new Network(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Network server)
{
if (opaqueRef == null)
{
var reference = create(session, this);
return reference == null ? null : reference.opaque_ref;
}
else
{
if (!Helper.AreEqual2(_name_label, server._name_label))
{
Network.set_name_label(session, opaqueRef, _name_label);
}
if (!Helper.AreEqual2(_name_description, server._name_description))
{
Network.set_name_description(session, opaqueRef, _name_description);
}
if (!Helper.AreEqual2(_MTU, server._MTU))
{
Network.set_MTU(session, opaqueRef, _MTU);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Network.set_other_config(session, opaqueRef, _other_config);
}
if (!Helper.AreEqual2(_tags, server._tags))
{
Network.set_tags(session, opaqueRef, _tags);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Network get_record(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_record(session.opaque_ref, _network);
else
return new Network((Proxy_Network)session.proxy.network_get_record(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get a reference to the network instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Network> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Network>.Create(session.proxy.network_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Create a new network instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Network> create(Session session, Network _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_create(session.opaque_ref, _record);
else
return XenRef<Network>.Create(session.proxy.network_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new network instance, and return its handle.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_record">All constructor arguments</param>
public static XenRef<Task> async_create(Session session, Network _record)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_create(session.opaque_ref, _record);
else
return XenRef<Task>.Create(session.proxy.async_network_create(session.opaque_ref, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified network instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static void destroy(Session session, string _network)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_destroy(session.opaque_ref, _network);
else
session.proxy.network_destroy(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Destroy the specified network instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static XenRef<Task> async_destroy(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_destroy(session.opaque_ref, _network);
else
return XenRef<Task>.Create(session.proxy.async_network_destroy(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get all the network instances with the given label.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Network>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Network>.Create(session.proxy.network_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_uuid(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_uuid(session.opaque_ref, _network);
else
return (string)session.proxy.network_get_uuid(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_name_label(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_name_label(session.opaque_ref, _network);
else
return (string)session.proxy.network_get_name_label(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_name_description(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_name_description(session.opaque_ref, _network);
else
return (string)session.proxy.network_get_name_description(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the allowed_operations field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<network_operations> get_allowed_operations(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_allowed_operations(session.opaque_ref, _network);
else
return Helper.StringArrayToEnumList<network_operations>(session.proxy.network_get_allowed_operations(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the current_operations field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<string, network_operations> get_current_operations(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_current_operations(session.opaque_ref, _network);
else
return Maps.convert_from_proxy_string_network_operations(session.proxy.network_get_current_operations(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the VIFs field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<XenRef<VIF>> get_VIFs(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_vifs(session.opaque_ref, _network);
else
return XenRef<VIF>.Create(session.proxy.network_get_vifs(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the PIFs field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<XenRef<PIF>> get_PIFs(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_pifs(session.opaque_ref, _network);
else
return XenRef<PIF>.Create(session.proxy.network_get_pifs(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the MTU field of the given network.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static long get_MTU(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_mtu(session.opaque_ref, _network);
else
return long.Parse((string)session.proxy.network_get_mtu(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<string, string> get_other_config(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_other_config(session.opaque_ref, _network);
else
return Maps.convert_from_proxy_string_string(session.proxy.network_get_other_config(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the bridge field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string get_bridge(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_bridge(session.opaque_ref, _network);
else
return (string)session.proxy.network_get_bridge(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the managed field of the given network.
/// First published in XenServer 7.2.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static bool get_managed(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_managed(session.opaque_ref, _network);
else
return (bool)session.proxy.network_get_managed(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the blobs field of the given network.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<string, XenRef<Blob>> get_blobs(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_blobs(session.opaque_ref, _network);
else
return Maps.convert_from_proxy_string_XenRefBlob(session.proxy.network_get_blobs(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the tags field of the given network.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static string[] get_tags(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_tags(session.opaque_ref, _network);
else
return (string [])session.proxy.network_get_tags(session.opaque_ref, _network ?? "").parse();
}
/// <summary>
/// Get the default_locking_mode field of the given network.
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static network_default_locking_mode get_default_locking_mode(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_default_locking_mode(session.opaque_ref, _network);
else
return (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), (string)session.proxy.network_get_default_locking_mode(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the assigned_ips field of the given network.
/// First published in XenServer 6.5.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static Dictionary<XenRef<VIF>, string> get_assigned_ips(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_assigned_ips(session.opaque_ref, _network);
else
return Maps.convert_from_proxy_XenRefVIF_string(session.proxy.network_get_assigned_ips(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Get the purpose field of the given network.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
public static List<network_purpose> get_purpose(Session session, string _network)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_purpose(session.opaque_ref, _network);
else
return Helper.StringArrayToEnumList<network_purpose>(session.proxy.network_get_purpose(session.opaque_ref, _network ?? "").parse());
}
/// <summary>
/// Set the name/label field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_label">New value to set</param>
public static void set_name_label(Session session, string _network, string _label)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_name_label(session.opaque_ref, _network, _label);
else
session.proxy.network_set_name_label(session.opaque_ref, _network ?? "", _label ?? "").parse();
}
/// <summary>
/// Set the name/description field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_description">New value to set</param>
public static void set_name_description(Session session, string _network, string _description)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_name_description(session.opaque_ref, _network, _description);
else
session.proxy.network_set_name_description(session.opaque_ref, _network ?? "", _description ?? "").parse();
}
/// <summary>
/// Set the MTU field of the given network.
/// First published in XenServer 5.6.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_mtu">New value to set</param>
public static void set_MTU(Session session, string _network, long _mtu)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_mtu(session.opaque_ref, _network, _mtu);
else
session.proxy.network_set_mtu(session.opaque_ref, _network ?? "", _mtu.ToString()).parse();
}
/// <summary>
/// Set the other_config field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _network, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_other_config(session.opaque_ref, _network, _other_config);
else
session.proxy.network_set_other_config(session.opaque_ref, _network ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given network.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _network, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_add_to_other_config(session.opaque_ref, _network, _key, _value);
else
session.proxy.network_add_to_other_config(session.opaque_ref, _network ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given network. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _network, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_remove_from_other_config(session.opaque_ref, _network, _key);
else
session.proxy.network_remove_from_other_config(session.opaque_ref, _network ?? "", _key ?? "").parse();
}
/// <summary>
/// Set the tags field of the given network.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_tags">New value to set</param>
public static void set_tags(Session session, string _network, string[] _tags)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_tags(session.opaque_ref, _network, _tags);
else
session.proxy.network_set_tags(session.opaque_ref, _network ?? "", _tags).parse();
}
/// <summary>
/// Add the given value to the tags field of the given network. If the value is already in that Set, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">New value to add</param>
public static void add_tags(Session session, string _network, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_add_tags(session.opaque_ref, _network, _value);
else
session.proxy.network_add_tags(session.opaque_ref, _network ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given value from the tags field of the given network. If the value is not in that Set, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">Value to remove</param>
public static void remove_tags(Session session, string _network, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_remove_tags(session.opaque_ref, _network, _value);
else
session.proxy.network_remove_tags(session.opaque_ref, _network ?? "", _value ?? "").parse();
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
public static XenRef<Blob> create_new_blob(Session session, string _network, string _name, string _mime_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_create_new_blob(session.opaque_ref, _network, _name, _mime_type);
else
return XenRef<Blob>.Create(session.proxy.network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "").parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
public static XenRef<Task> async_create_new_blob(Session session, string _network, string _name, string _mime_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_create_new_blob(session.opaque_ref, _network, _name, _mime_type);
else
return XenRef<Task>.Create(session.proxy.async_network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "").parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Blob> create_new_blob(Session session, string _network, string _name, string _mime_type, bool _public)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_create_new_blob(session.opaque_ref, _network, _name, _mime_type, _public);
else
return XenRef<Blob>.Create(session.proxy.network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "", _public).parse());
}
/// <summary>
/// Create a placeholder for a named binary blob of data that is associated with this pool
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_name">The name associated with the blob</param>
/// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param>
/// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param>
public static XenRef<Task> async_create_new_blob(Session session, string _network, string _name, string _mime_type, bool _public)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_create_new_blob(session.opaque_ref, _network, _name, _mime_type, _public);
else
return XenRef<Task>.Create(session.proxy.async_network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "", _public).parse());
}
/// <summary>
/// Set the default locking mode for VIFs attached to this network
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The default locking mode for VIFs attached to this network.</param>
public static void set_default_locking_mode(Session session, string _network, network_default_locking_mode _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_set_default_locking_mode(session.opaque_ref, _network, _value);
else
session.proxy.network_set_default_locking_mode(session.opaque_ref, _network ?? "", network_default_locking_mode_helper.ToString(_value)).parse();
}
/// <summary>
/// Set the default locking mode for VIFs attached to this network
/// First published in XenServer 6.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The default locking mode for VIFs attached to this network.</param>
public static XenRef<Task> async_set_default_locking_mode(Session session, string _network, network_default_locking_mode _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_set_default_locking_mode(session.opaque_ref, _network, _value);
else
return XenRef<Task>.Create(session.proxy.async_network_set_default_locking_mode(session.opaque_ref, _network ?? "", network_default_locking_mode_helper.ToString(_value)).parse());
}
/// <summary>
/// Give a network a new purpose (if not present already)
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The purpose to add</param>
public static void add_purpose(Session session, string _network, network_purpose _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_add_purpose(session.opaque_ref, _network, _value);
else
session.proxy.network_add_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse();
}
/// <summary>
/// Give a network a new purpose (if not present already)
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The purpose to add</param>
public static XenRef<Task> async_add_purpose(Session session, string _network, network_purpose _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_add_purpose(session.opaque_ref, _network, _value);
else
return XenRef<Task>.Create(session.proxy.async_network_add_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse());
}
/// <summary>
/// Remove a purpose from a network (if present)
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The purpose to remove</param>
public static void remove_purpose(Session session, string _network, network_purpose _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.network_remove_purpose(session.opaque_ref, _network, _value);
else
session.proxy.network_remove_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse();
}
/// <summary>
/// Remove a purpose from a network (if present)
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_network">The opaque_ref of the given network</param>
/// <param name="_value">The purpose to remove</param>
public static XenRef<Task> async_remove_purpose(Session session, string _network, network_purpose _value)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_network_remove_purpose(session.opaque_ref, _network, _value);
else
return XenRef<Task>.Create(session.proxy.async_network_remove_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse());
}
/// <summary>
/// Return a list of all the networks known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Network>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_all(session.opaque_ref);
else
return XenRef<Network>.Create(session.proxy.network_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the network Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Network>, Network> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.network_get_all_records(session.opaque_ref);
else
return XenRef<Network>.Create<Proxy_Network>(session.proxy.network_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
/// </summary>
public virtual List<network_operations> allowed_operations
{
get { return _allowed_operations; }
set
{
if (!Helper.AreEqual(value, _allowed_operations))
{
_allowed_operations = value;
Changed = true;
NotifyPropertyChanged("allowed_operations");
}
}
}
private List<network_operations> _allowed_operations = new List<network_operations>() {};
/// <summary>
/// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
/// </summary>
public virtual Dictionary<string, network_operations> current_operations
{
get { return _current_operations; }
set
{
if (!Helper.AreEqual(value, _current_operations))
{
_current_operations = value;
Changed = true;
NotifyPropertyChanged("current_operations");
}
}
}
private Dictionary<string, network_operations> _current_operations = new Dictionary<string, network_operations>() {};
/// <summary>
/// list of connected vifs
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VIF>))]
public virtual List<XenRef<VIF>> VIFs
{
get { return _VIFs; }
set
{
if (!Helper.AreEqual(value, _VIFs))
{
_VIFs = value;
Changed = true;
NotifyPropertyChanged("VIFs");
}
}
}
private List<XenRef<VIF>> _VIFs = new List<XenRef<VIF>>() {};
/// <summary>
/// list of connected pifs
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PIF>))]
public virtual List<XenRef<PIF>> PIFs
{
get { return _PIFs; }
set
{
if (!Helper.AreEqual(value, _PIFs))
{
_PIFs = value;
Changed = true;
NotifyPropertyChanged("PIFs");
}
}
}
private List<XenRef<PIF>> _PIFs = new List<XenRef<PIF>>() {};
/// <summary>
/// MTU in octets
/// First published in XenServer 5.6.
/// </summary>
public virtual long MTU
{
get { return _MTU; }
set
{
if (!Helper.AreEqual(value, _MTU))
{
_MTU = value;
Changed = true;
NotifyPropertyChanged("MTU");
}
}
}
private long _MTU = 1500;
/// <summary>
/// additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// name of the bridge corresponding to this network on the local host
/// </summary>
public virtual string bridge
{
get { return _bridge; }
set
{
if (!Helper.AreEqual(value, _bridge))
{
_bridge = value;
Changed = true;
NotifyPropertyChanged("bridge");
}
}
}
private string _bridge = "";
/// <summary>
/// true if the bridge is managed by xapi
/// First published in XenServer 7.2.
/// </summary>
public virtual bool managed
{
get { return _managed; }
set
{
if (!Helper.AreEqual(value, _managed))
{
_managed = value;
Changed = true;
NotifyPropertyChanged("managed");
}
}
}
private bool _managed = true;
/// <summary>
/// Binary blobs associated with this network
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(StringXenRefMapConverter<Blob>))]
public virtual Dictionary<string, XenRef<Blob>> blobs
{
get { return _blobs; }
set
{
if (!Helper.AreEqual(value, _blobs))
{
_blobs = value;
Changed = true;
NotifyPropertyChanged("blobs");
}
}
}
private Dictionary<string, XenRef<Blob>> _blobs = new Dictionary<string, XenRef<Blob>>() {};
/// <summary>
/// user-specified tags for categorization purposes
/// First published in XenServer 5.0.
/// </summary>
public virtual string[] tags
{
get { return _tags; }
set
{
if (!Helper.AreEqual(value, _tags))
{
_tags = value;
Changed = true;
NotifyPropertyChanged("tags");
}
}
}
private string[] _tags = {};
/// <summary>
/// The network will use this value to determine the behaviour of all VIFs where locking_mode = default
/// First published in XenServer 6.1.
/// </summary>
[JsonConverter(typeof(network_default_locking_modeConverter))]
public virtual network_default_locking_mode default_locking_mode
{
get { return _default_locking_mode; }
set
{
if (!Helper.AreEqual(value, _default_locking_mode))
{
_default_locking_mode = value;
Changed = true;
NotifyPropertyChanged("default_locking_mode");
}
}
}
private network_default_locking_mode _default_locking_mode = network_default_locking_mode.unlocked;
/// <summary>
/// The IP addresses assigned to VIFs on networks that have active xapi-managed DHCP
/// First published in XenServer 6.5.
/// </summary>
[JsonConverter(typeof(XenRefStringMapConverter<VIF>))]
public virtual Dictionary<XenRef<VIF>, string> assigned_ips
{
get { return _assigned_ips; }
set
{
if (!Helper.AreEqual(value, _assigned_ips))
{
_assigned_ips = value;
Changed = true;
NotifyPropertyChanged("assigned_ips");
}
}
}
private Dictionary<XenRef<VIF>, string> _assigned_ips = new Dictionary<XenRef<VIF>, string>() {};
/// <summary>
/// Set of purposes for which the server will use this network
/// First published in XenServer 7.3.
/// </summary>
public virtual List<network_purpose> purpose
{
get { return _purpose; }
set
{
if (!Helper.AreEqual(value, _purpose))
{
_purpose = value;
Changed = true;
NotifyPropertyChanged("purpose");
}
}
}
private List<network_purpose> _purpose = new List<network_purpose>() {};
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using Scientia.HtmlRenderer.Adapters.Entities;
using Scientia.HtmlRenderer.Core.Utils;
using Scientia.HtmlRenderer.Adapters;
using Scientia.HtmlRenderer.WinForms.Utilities;
namespace Scientia.HtmlRenderer.WinForms.Adapters
{
/// <summary>
/// Adapter for WinForms Graphics for core.
/// </summary>
internal sealed class GraphicsAdapter : RGraphics
{
#region Fields and Consts
/// <summary>
/// used for <see cref="MeasureString(string,RFont,double,out int,out double)"/> calculation.
/// </summary>
private static readonly int[] CharFit = new int[1];
/// <summary>
/// used for <see cref="MeasureString(string,RFont,double,out int,out double)"/> calculation.
/// </summary>
private static readonly int[] CharFitWidth = new int[1000];
/// <summary>
/// Used for GDI+ measure string.
/// </summary>
private static readonly CharacterRange[] CharacterRanges = new CharacterRange[1];
/// <summary>
/// The string format to use for measuring strings for GDI+ text rendering
/// </summary>
private static readonly StringFormat StringFormat;
/// <summary>
/// The string format to use for rendering strings for GDI+ text rendering
/// </summary>
private static readonly StringFormat StringFormat2;
/// <summary>
/// The wrapped WinForms graphics object
/// </summary>
private readonly Graphics Graphics;
/// <summary>
/// Use GDI+ text rendering to measure/draw text.
/// </summary>
private readonly bool UseGdiPlusTextRendering;
#if !MONO
/// <summary>
/// the initialized HDC used
/// </summary>
private IntPtr Hdc;
#endif
/// <summary>
/// if to release the graphics object on dispose
/// </summary>
private readonly bool ReleaseGraphics;
/// <summary>
/// If text alignment was set to RTL
/// </summary>
private bool SetRtl;
#endregion
/// <summary>
/// Init static resources.
/// </summary>
static GraphicsAdapter()
{
StringFormat = new StringFormat(StringFormat.GenericTypographic);
StringFormat.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.MeasureTrailingSpaces;
StringFormat2 = new StringFormat(StringFormat.GenericTypographic);
}
/// <summary>
/// Init.
/// </summary>
/// <param name="g">the win forms graphics object to use</param>
/// <param name="useGdiPlusTextRendering">Use GDI+ text rendering to measure/draw text</param>
/// <param name="releaseGraphics">optional: if to release the graphics object on dispose (default - false)</param>
public GraphicsAdapter(Graphics g, bool useGdiPlusTextRendering, bool releaseGraphics = false)
: base(WinFormsAdapter.Instance, Utils.Convert(g.ClipBounds))
{
ArgChecker.AssertArgNotNull(g, "g");
this.Graphics = g;
this.ReleaseGraphics = releaseGraphics;
#if MONO
_useGdiPlusTextRendering = true;
#else
this.UseGdiPlusTextRendering = useGdiPlusTextRendering;
#endif
}
public override void PopClip()
{
this.ReleaseHdc();
this.ClipStack.Pop();
this.Graphics.SetClip(Utils.Convert(this.ClipStack.Peek()), CombineMode.Replace);
}
public override void PushClip(RRect rect)
{
this.ReleaseHdc();
this.ClipStack.Push(rect);
this.Graphics.SetClip(Utils.Convert(rect), CombineMode.Replace);
}
public override void PushClipExclude(RRect rect)
{
this.ReleaseHdc();
this.ClipStack.Push(this.ClipStack.Peek());
this.Graphics.SetClip(Utils.Convert(rect), CombineMode.Exclude);
}
public override Object SetAntiAliasSmoothingMode()
{
this.ReleaseHdc();
var prevMode = this.Graphics.SmoothingMode;
this.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
return prevMode;
}
public override void ReturnPreviousSmoothingMode(Object prevMode)
{
if (prevMode != null)
{
this.ReleaseHdc();
this.Graphics.SmoothingMode = (SmoothingMode)prevMode;
}
}
public override RSize MeasureString(string str, RFont font)
{
if (this.UseGdiPlusTextRendering)
{
this.ReleaseHdc();
var fontAdapter = (FontAdapter)font;
var realFont = fontAdapter.Font;
CharacterRanges[0] = new CharacterRange(0, str.Length);
StringFormat.SetMeasurableCharacterRanges(CharacterRanges);
var size = this.Graphics.MeasureCharacterRanges(str, realFont, RectangleF.Empty, StringFormat)[0].GetBounds(this.Graphics).Size;
if (font.Height < 0)
{
var height = realFont.Height;
var descent = realFont.Size * realFont.FontFamily.GetCellDescent(realFont.Style) / realFont.FontFamily.GetEmHeight(realFont.Style);
#if !MONO
fontAdapter.SetMetrics(height, (int)Math.Round(height - descent + .5f));
#else
fontAdapter.SetMetrics(height, (int)Math.Round((height - descent + 1f)));
#endif
}
return Utils.Convert(size);
}
else
{
#if !MONO
this.SetFont(font);
var size = new Size();
Win32Utils.GetTextExtentPoint32(this.Hdc, str, str.Length, ref size);
if (font.Height < 0)
{
TextMetric lptm;
Win32Utils.GetTextMetrics(this.Hdc, out lptm);
((FontAdapter)font).SetMetrics(size.Height, lptm.Height - lptm.Descent + lptm.Underlined + 1);
}
return Utils.Convert(size);
#else
throw new InvalidProgramException("Invalid Mono code");
#endif
}
}
public override void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth)
{
charFit = 0;
charFitWidth = 0;
if (this.UseGdiPlusTextRendering)
{
this.ReleaseHdc();
var size = this.MeasureString(str, font);
for (int i = 1; i <= str.Length; i++)
{
charFit = i - 1;
RSize pSize = this.MeasureString(str.Substring(0, i), font);
if (pSize.Height <= size.Height && pSize.Width < maxWidth)
{
charFitWidth = pSize.Width;
}
else
{
break;
}
}
}
else
{
#if !MONO
this.SetFont(font);
var size = new Size();
Win32Utils.GetTextExtentExPoint(this.Hdc, str, str.Length, (int)Math.Round(maxWidth), CharFit, CharFitWidth, ref size);
charFit = CharFit[0];
charFitWidth = charFit > 0 ? CharFitWidth[charFit - 1] : 0;
#endif
}
}
public override void DrawString(string str, RFont font, RColor color, RPoint point, RSize size, bool rtl)
{
if (this.UseGdiPlusTextRendering)
{
this.ReleaseHdc();
this.SetRtlAlignGdiPlus(rtl);
var brush = ((BrushAdapter)this.Adapter.GetSolidBrush(color)).Brush;
this.Graphics.DrawString(str, ((FontAdapter)font).Font, brush, (int)(Math.Round(point.X) + (rtl ? size.Width : 0)), (int)Math.Round(point.Y), StringFormat2);
}
else
{
#if !MONO
var pointConv = Utils.ConvertRound(point);
var colorConv = Utils.Convert(color);
if (color.A == 255)
{
this.SetFont(font);
this.SetTextColor(colorConv);
this.SetRtlAlignGdi(rtl);
Win32Utils.TextOut(this.Hdc, pointConv.X, pointConv.Y, str, str.Length);
}
else
{
this.InitHdc();
this.SetRtlAlignGdi(rtl);
DrawTransparentText(this.Hdc, str, font, pointConv, Utils.ConvertRound(size), colorConv);
}
#endif
}
}
public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation)
{
var brush = new TextureBrush(((ImageAdapter)image).Image, Utils.Convert(dstRect));
brush.TranslateTransform((float)translateTransformLocation.X, (float)translateTransformLocation.Y);
return new BrushAdapter(brush, true);
}
public override RGraphicsPath GetGraphicsPath()
{
return new GraphicsPathAdapter();
}
public override void Dispose()
{
this.ReleaseHdc();
if (this.ReleaseGraphics)
{
this.Graphics.Dispose();
}
if (this.UseGdiPlusTextRendering && this.SetRtl)
{
StringFormat2.FormatFlags ^= StringFormatFlags.DirectionRightToLeft;
}
}
#region Delegate graphics methods
public override void DrawLine(RPen pen, double x1, double y1, double x2, double y2)
{
this.ReleaseHdc();
this.Graphics.DrawLine(((PenAdapter)pen).Pen, (float)x1, (float)y1, (float)x2, (float)y2);
}
public override void DrawRectangle(RPen pen, double x, double y, double width, double height)
{
this.ReleaseHdc();
this.Graphics.DrawRectangle(((PenAdapter)pen).Pen, (float)x, (float)y, (float)width, (float)height);
}
public override void DrawRectangle(RBrush brush, double x, double y, double width, double height)
{
this.ReleaseHdc();
this.Graphics.FillRectangle(((BrushAdapter)brush).Brush, (float)x, (float)y, (float)width, (float)height);
}
public override void DrawImage(RImage image, RRect destRect, RRect srcRect)
{
this.ReleaseHdc();
this.Graphics.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect), Utils.Convert(srcRect), GraphicsUnit.Pixel);
}
public override void DrawImage(RImage image, RRect destRect)
{
this.ReleaseHdc();
this.Graphics.DrawImage(((ImageAdapter)image).Image, Utils.Convert(destRect));
}
public override void DrawPath(RPen pen, RGraphicsPath path)
{
this.Graphics.DrawPath(((PenAdapter)pen).Pen, ((GraphicsPathAdapter)path).GraphicsPath);
}
public override void DrawPath(RBrush brush, RGraphicsPath path)
{
this.ReleaseHdc();
this.Graphics.FillPath(((BrushAdapter)brush).Brush, ((GraphicsPathAdapter)path).GraphicsPath);
}
public override void DrawPolygon(RBrush brush, RPoint[] points)
{
if (points != null && points.Length > 0)
{
this.ReleaseHdc();
this.Graphics.FillPolygon(((BrushAdapter)brush).Brush, Utils.Convert(points));
}
}
#endregion
#region Private methods
/// <summary>
/// Release current HDC to be able to use <see cref="System.Drawing.Graphics"/> methods.
/// </summary>
private void ReleaseHdc()
{
#if !MONO
if (this.Hdc != IntPtr.Zero)
{
Win32Utils.SelectClipRgn(this.Hdc, IntPtr.Zero);
this.Graphics.ReleaseHdc(this.Hdc);
this.Hdc = IntPtr.Zero;
}
#endif
}
#if !MONO
/// <summary>
/// Init HDC for the current graphics object to be used to call GDI directly.
/// </summary>
private void InitHdc()
{
if (this.Hdc == IntPtr.Zero)
{
var clip = this.Graphics.Clip.GetHrgn(this.Graphics);
this.Hdc = this.Graphics.GetHdc();
this.SetRtl = false;
Win32Utils.SetBkMode(this.Hdc, 1);
Win32Utils.SelectClipRgn(this.Hdc, clip);
Win32Utils.DeleteObject(clip);
}
}
/// <summary>
/// Set a resource (e.g. a font) for the specified device context.
/// WARNING: Calling Font.ToHfont() many times without releasing the font handle crashes the app.
/// </summary>
private void SetFont(RFont font)
{
this.InitHdc();
Win32Utils.SelectObject(this.Hdc, ((FontAdapter)font).HFont);
}
/// <summary>
/// Set the text color of the device context.
/// </summary>
private void SetTextColor(Color color)
{
this.InitHdc();
int rgb = (color.B & 0xFF) << 16 | (color.G & 0xFF) << 8 | color.R;
Win32Utils.SetTextColor(this.Hdc, rgb);
}
/// <summary>
/// Change text align to Left-to-Right or Right-to-Left if required.
/// </summary>
private void SetRtlAlignGdi(bool rtl)
{
if (this.SetRtl)
{
if (!rtl)
{
Win32Utils.SetTextAlign(this.Hdc, Win32Utils.TextAlignDefault);
}
}
else if (rtl)
{
Win32Utils.SetTextAlign(this.Hdc, Win32Utils.TextAlignRtl);
}
this.SetRtl = rtl;
}
/// <summary>
/// Special draw logic to draw transparent text using GDI.<br/>
/// 1. Create in-memory DC<br/>
/// 2. Copy background to in-memory DC<br/>
/// 3. Draw the text to in-memory DC<br/>
/// 4. Copy the in-memory DC to the proper location with alpha blend<br/>
/// </summary>
private static void DrawTransparentText(IntPtr hdc, string str, RFont font, Point point, Size size, Color color)
{
IntPtr dib;
var memoryHdc = Win32Utils.CreateMemoryHdc(hdc, size.Width, size.Height, out dib);
try
{
// copy target background to memory HDC so when copied back it will have the proper background
Win32Utils.BitBlt(memoryHdc, 0, 0, size.Width, size.Height, hdc, point.X, point.Y, Win32Utils.BitBltCopy);
// Create and select font
Win32Utils.SelectObject(memoryHdc, ((FontAdapter)font).HFont);
Win32Utils.SetTextColor(memoryHdc, (color.B & 0xFF) << 16 | (color.G & 0xFF) << 8 | color.R);
// Draw text to memory HDC
Win32Utils.TextOut(memoryHdc, 0, 0, str, str.Length);
// copy from memory HDC to normal HDC with alpha blend so achieve the transparent text
Win32Utils.AlphaBlend(hdc, point.X, point.Y, size.Width, size.Height, memoryHdc, 0, 0, size.Width, size.Height, new BlendFunction(color.A));
}
finally
{
Win32Utils.ReleaseMemoryHdc(memoryHdc, dib);
}
}
#endif
/// <summary>
/// Change text align to Left-to-Right or Right-to-Left if required.
/// </summary>
private void SetRtlAlignGdiPlus(bool rtl)
{
if (this.SetRtl)
{
if (!rtl)
{
StringFormat2.FormatFlags ^= StringFormatFlags.DirectionRightToLeft;
}
}
else if (rtl)
{
StringFormat2.FormatFlags |= StringFormatFlags.DirectionRightToLeft;
}
this.SetRtl = rtl;
}
#endregion
}
}
| |
//! \file ArcNPK.cs
//! \date Sat Feb 06 06:07:52 2016
//! \brief Mware resource archive.
//
// Copyright (C) 2016 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using GameRes.Formats.Strings;
using GameRes.Utility;
namespace GameRes.Formats.NitroPlus
{
internal class NpkEntry : PackedEntry
{
public readonly List<NpkSegment> Segments = new List<NpkSegment>();
}
internal class NpkSegment
{
public long Offset;
public uint AlignedSize;
public uint Size;
public uint UnpackedSize;
public bool IsCompressed { get { return Size < UnpackedSize; } }
}
public class Npk2Options : ResourceOptions
{
public byte[] Key;
}
internal class NpkArchive : ArcFile
{
public readonly Aes Encryption;
public NpkArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, Aes enc)
: base (arc, impl, dir)
{
Encryption = enc;
}
#region IDisposable Members
bool _npk_disposed = false;
protected override void Dispose (bool disposing)
{
if (_npk_disposed)
return;
if (disposing)
Encryption.Dispose();
_npk_disposed = true;
base.Dispose (disposing);
}
#endregion
}
[Export(typeof(ArchiveFormat))]
public class NpkOpener : ArchiveFormat
{
public override string Tag { get { return "NPK"; } }
public override string Description { get { return "Mware engine resource archive"; } }
public override uint Signature { get { return 0x324B504E; } } // 'NPK2'
public override bool IsHierarchic { get { return true; } }
public override bool CanWrite { get { return true; } }
static Npk2Scheme DefaultScheme = new Npk2Scheme { KnownKeys = new Dictionary<string, byte[]>() };
internal Dictionary<string, byte[]> KnownKeys { get { return DefaultScheme.KnownKeys; } }
const uint DefaultSegmentSize = 0x10000;
static readonly Encoding DefaultEncoding = Encoding.UTF8;
public override ResourceScheme Scheme
{
get { return DefaultScheme; }
set { DefaultScheme = (Npk2Scheme)value; }
}
public override ArcFile TryOpen (ArcView file)
{
int count = file.View.ReadInt32 (0x18);
if (!IsSaneCount (count))
return null;
var key = QueryEncryption (file.Name);
if (null == key)
return null;
var aes = Aes.Create();
try
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = key;
aes.IV = file.View.ReadBytes (8, 0x10);
uint index_size = file.View.ReadUInt32 (0x1C);
using (var decryptor = aes.CreateDecryptor())
using (var enc_index = file.CreateStream (0x20, index_size))
using (var dec_index = new CryptoStream (enc_index, decryptor, CryptoStreamMode.Read))
using (var index = new ArcView.Reader (dec_index))
{
var dir = ReadIndex (index, count, file.MaxOffset);
if (null == dir)
return null;
var arc = new NpkArchive (file, this, dir, aes);
aes = null; // object ownership passed to NpkArchive, don't dispose
return arc;
}
}
finally
{
if (aes != null)
aes.Dispose();
}
}
List<Entry> ReadIndex (BinaryReader index, int count, long max_offset)
{
var name_buffer = new byte[0x104];
var dir = new List<Entry> (count);
for (int i = 0; i < count; ++i)
{
index.ReadByte();
int name_length = index.ReadUInt16();
if (0 == name_length || name_length > name_buffer.Length)
return null;
index.Read (name_buffer, 0, name_length);
var name = DefaultEncoding.GetString (name_buffer, 0, name_length);
var entry = FormatCatalog.Instance.Create<NpkEntry> (name);
entry.UnpackedSize = index.ReadUInt32();
index.Read (name_buffer, 0, 0x20); // skip
int segment_count = index.ReadInt32();
if (segment_count < 0)
return null;
if (0 == segment_count)
{
entry.Offset = 0;
dir.Add (entry);
continue;
}
entry.Segments.Capacity = segment_count;
uint packed_size = 0;
bool is_packed = false;
for (int j = 0; j < segment_count; ++j)
{
var segment = new NpkSegment();
segment.Offset = index.ReadInt64();
segment.AlignedSize = index.ReadUInt32();
segment.Size = index.ReadUInt32();
segment.UnpackedSize = index.ReadUInt32();
entry.Segments.Add (segment);
packed_size += segment.AlignedSize;
is_packed = is_packed || segment.IsCompressed;
}
entry.Offset = entry.Segments[0].Offset;
entry.Size = packed_size;
entry.IsPacked = is_packed;
if (!entry.CheckPlacement (max_offset))
return null;
dir.Add (entry);
}
return dir;
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
if (0 == entry.Size)
return Stream.Null;
var narc = arc as NpkArchive;
var nent = entry as NpkEntry;
if (null == narc || null == nent)
return base.OpenEntry (arc, entry);
if (1 == nent.Segments.Count && !nent.IsPacked)
{
var input = narc.File.CreateStream (nent.Segments[0].Offset, nent.Segments[0].AlignedSize);
var decryptor = narc.Encryption.CreateDecryptor();
return new InputCryptoStream (input, decryptor);
}
return new NpkStream (narc, nent);
}
public override ResourceOptions GetDefaultOptions ()
{
return new Npk2Options { Key = GetKey (Properties.Settings.Default.NPKScheme) };
}
public override object GetAccessWidget ()
{
return new GUI.WidgetNPK (KnownKeys.Keys);
}
public override object GetCreationWidget ()
{
return new GUI.WidgetNPK (KnownKeys.Keys);
}
byte[] QueryEncryption (string arc_name)
{
byte[] key = null;
var title = FormatCatalog.Instance.LookupGame (arc_name);
if (!string.IsNullOrEmpty (title))
key = GetKey (title);
if (null == key)
{
var options = Query<Npk2Options> (arcStrings.ArcEncryptedNotice);
key = options.Key;
}
return key;
}
byte[] GetKey (string title)
{
byte[] key;
KnownKeys.TryGetValue (title, out key);
return key;
}
public override void Create (Stream output, IEnumerable<Entry> list, ResourceOptions options,
EntryCallback callback)
{
var npk_options = GetOptions<Npk2Options> (options);
if (null == npk_options.Key)
throw new InvalidEncryptionScheme();
var enc = DefaultEncoding.WithFatalFallback();
int index_length = 0;
var dir = new List<NpkStoredEntry>();
foreach (var entry in list)
{
var ext = Path.GetExtension (entry.Name).ToLowerInvariant();
var npk_entry = new NpkStoredEntry
{
Name = entry.Name,
RawName = enc.GetBytes (entry.Name.Replace ('\\', '/')),
IsSolid = SolidFiles.Contains (ext),
IsPacked = !DisableCompression.Contains (ext),
};
int segment_count = 1;
if (!npk_entry.IsSolid)
segment_count = (int)(((long)entry.Size + DefaultSegmentSize-1) / DefaultSegmentSize);
index_length += 3 + npk_entry.RawName.Length + 0x28 + segment_count * 0x14;
dir.Add (npk_entry);
}
index_length = (index_length + 0xF) & ~0xF;
int callback_count = 0;
using (var aes = Aes.Create())
{
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = npk_options.Key;
aes.IV = GenerateAesIV();
output.Position = 0x20 + index_length;
foreach (var entry in dir)
{
if (null != callback)
callback (callback_count++, entry, arcStrings.MsgAddingFile);
using (var writer = new NpkWriter (entry, output, aes))
writer.Write (DefaultSegmentSize);
}
output.Position = 0;
var buffer = new byte[] { (byte)'N', (byte)'P', (byte)'K', (byte)'2', 1, 0, 0, 0 };
output.Write (buffer, 0, 8);
output.Write (aes.IV, 0, 0x10);
LittleEndian.Pack (dir.Count, buffer, 0);
LittleEndian.Pack (index_length, buffer, 4);
output.Write (buffer, 0, 8);
using (var encryptor = aes.CreateEncryptor())
using (var proxy = new ProxyStream (output, true))
using (var index_stream = new CryptoStream (proxy, encryptor, CryptoStreamMode.Write))
using (var index = new BinaryWriter (index_stream))
{
if (null != callback)
callback (callback_count++, null, arcStrings.MsgWritingIndex);
foreach (var entry in dir)
{
index.Write (entry.IsSolid); // 0 -> segmentation enabled, 1 -> no segmentation
index.Write ((short)entry.RawName.Length);
index.Write (entry.RawName);
index.Write (entry.UnpackedSize);
index.Write (entry.CheckSum);
index.Write (entry.Segments.Count);
foreach (var segment in entry.Segments)
{
index.Write (segment.Offset);
index.Write (segment.AlignedSize);
index.Write (segment.Size);
index.Write (segment.UnpackedSize);
}
}
}
}
}
byte[] GenerateAesIV ()
{
using (var rng = new RNGCryptoServiceProvider())
{
var iv = new byte[0x10];
rng.GetBytes (iv);
return iv;
}
}
static readonly HashSet<string> SolidFiles = new HashSet<string> { ".png", ".jpg" };
static readonly HashSet<string> DisableCompression = new HashSet<string> { ".png", ".jpg", ".ogg" };
}
internal class NpkStoredEntry : NpkEntry
{
public byte[] RawName;
public byte[] CheckSum;
public bool IsSolid;
}
internal sealed class NpkWriter : IDisposable
{
NpkStoredEntry m_entry;
FileStream m_input;
Stream m_archive;
CryptoStream m_checksum_stream;
Aes m_aes;
long m_remaining;
byte[] m_buffer;
public NpkWriter (NpkStoredEntry entry, Stream archive, Aes aes)
{
m_input = File.OpenRead (entry.Name);
m_archive = archive;
m_entry = entry;
m_aes = aes;
m_buffer = null;
}
static readonly byte[] EmptyFileHash = GetDefaultHash();
public void Write (uint segment_size)
{
long input_size = m_input.Length;
if (input_size > uint.MaxValue)
throw new FileSizeException();
m_entry.Offset = m_archive.Position;
m_entry.Size = m_entry.UnpackedSize = (uint)input_size;
if (0 == m_entry.Size)
{
m_entry.CheckSum = EmptyFileHash;
return;
}
if (!m_entry.IsSolid)
m_buffer = new byte[segment_size];
else if (input_size > segment_size)
segment_size = (uint)input_size;
using (var sha256 = SHA256.Create())
using (m_checksum_stream = new CryptoStream (Stream.Null, sha256, CryptoStreamMode.Write))
{
m_remaining = input_size;
int segment_count = (int)((input_size + segment_size - 1) / segment_size);
m_entry.Segments.Clear();
m_entry.Segments.Capacity = segment_count;
for (int i = 0; i < segment_count; ++i)
{
int chunk_size = (int)Math.Min (m_remaining, segment_size);
bool should_compress = m_entry.IsPacked && chunk_size > 2;
var file_pos = m_input.Position;
var segment = WriteSegment (chunk_size, should_compress);
if (should_compress && !segment.IsCompressed)
{
// compressed segment is larger than uncompressed, rewrite
m_input.Position = file_pos;
m_archive.Position = segment.Offset;
RewriteSegment (segment, chunk_size);
m_archive.SetLength (m_archive.Position);
}
m_entry.Segments.Add (segment);
m_remaining -= segment.UnpackedSize;
}
m_checksum_stream.FlushFinalBlock();
m_entry.CheckSum = sha256.Hash;
}
}
NpkSegment WriteSegment (int chunk_size, bool compress)
{
var segment = new NpkSegment { Offset = m_archive.Position };
using (var proxy = new ProxyStream (m_archive, true))
using (var encryptor = m_aes.CreateEncryptor())
{
Stream output = new CryptoStream (proxy, encryptor, CryptoStreamMode.Write);
var measure = new CountedStream (output);
output = measure;
if (compress)
output = new DeflateStream (output, CompressionLevel.Optimal);
using (output)
{
if (m_remaining == chunk_size)
{
var file_pos = m_input.Position;
m_input.CopyTo (output);
m_input.Position = file_pos;
m_input.CopyTo (m_checksum_stream);
}
else
{
chunk_size = m_input.Read (m_buffer, 0, chunk_size);
output.Write (m_buffer, 0, chunk_size);
m_checksum_stream.Write (m_buffer, 0, chunk_size);
}
}
segment.UnpackedSize = (uint)chunk_size;
segment.Size = (uint)measure.Count;
segment.AlignedSize = (uint)(m_archive.Position - segment.Offset);
return segment;
}
}
void RewriteSegment (NpkSegment segment, int chunk_size)
{
using (var proxy = new ProxyStream (m_archive, true))
using (var encryptor = m_aes.CreateEncryptor())
using (var output = new CryptoStream (proxy, encryptor, CryptoStreamMode.Write))
{
if (m_remaining == chunk_size)
{
m_input.CopyTo (output);
}
else
{
chunk_size = m_input.Read (m_buffer, 0, chunk_size);
output.Write (m_buffer, 0, chunk_size);
}
}
segment.UnpackedSize = segment.Size = (uint)chunk_size;
segment.AlignedSize = (uint)(m_archive.Position - segment.Offset);
}
static byte[] GetDefaultHash ()
{
using (var sha256 = SHA256.Create())
return sha256.ComputeHash (new byte[0]);
}
bool _disposed = false;
public void Dispose ()
{
if (!_disposed)
{
m_input.Dispose();
_disposed = true;
}
GC.SuppressFinalize (this);
}
}
internal class NpkStream : Stream
{
ArcView m_file;
Aes m_encryption;
IEnumerator<NpkSegment> m_segment;
Stream m_stream;
bool m_eof = false;
public override bool CanRead { get { return m_stream != null && m_stream.CanRead; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public NpkStream (NpkArchive arc, NpkEntry entry)
{
m_file = arc.File;
m_encryption = arc.Encryption;
m_segment = entry.Segments.GetEnumerator();
NextSegment();
}
private void NextSegment ()
{
if (!m_segment.MoveNext())
{
m_eof = true;
return;
}
if (null != m_stream)
m_stream.Dispose();
var segment = m_segment.Current;
m_stream = m_file.CreateStream (segment.Offset, segment.AlignedSize);
var decryptor = m_encryption.CreateDecryptor();
m_stream = new InputCryptoStream (m_stream, decryptor);
if (segment.IsCompressed)
m_stream = new DeflateStream (m_stream, CompressionMode.Decompress);
}
public override int Read (byte[] buffer, int offset, int count)
{
int total = 0;
while (!m_eof && count > 0)
{
int read = m_stream.Read (buffer, offset, count);
if (0 != read)
{
total += read;
offset += read;
count -= read;
}
if (0 != count)
NextSegment();
}
return total;
}
public override int ReadByte ()
{
int b = -1;
while (!m_eof)
{
b = m_stream.ReadByte();
if (-1 != b)
break;
NextSegment();
}
return b;
}
#region IO.Stream members
public override long Length
{
get { throw new NotSupportedException ("NpkStream.Length not supported"); }
}
public override long Position
{
get { throw new NotSupportedException ("NpkStream.Position not supported."); }
set { throw new NotSupportedException ("NpkStream.Position not supported."); }
}
public override void Flush ()
{
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ("NpkStream.Seek method is not supported");
}
public override void SetLength (long length)
{
throw new NotSupportedException ("NpkStream.SetLength method is not supported");
}
public override void Write (byte[] buffer, int offset, int count)
{
throw new NotSupportedException ("NpkStream.Write method is not supported");
}
public override void WriteByte (byte value)
{
throw new NotSupportedException("NpkStream.WriteByte method is not supported");
}
#endregion
#region IDisposable Members
bool _disposed = false;
protected override void Dispose (bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (null != m_stream)
m_stream.Dispose();
m_segment.Dispose();
}
_disposed = true;
base.Dispose (disposing);
}
}
#endregion
}
[Serializable]
public class Npk2Scheme : ResourceScheme
{
public Dictionary<string, byte[]> KnownKeys;
}
/// <summary>
/// Filter stream that counts total bytes read/written.
/// </summary>
public class CountedStream : ProxyStream
{
long m_count;
public long Count { get { return m_count; } }
public CountedStream (Stream source, bool leave_open = false) : base (source, leave_open)
{
m_count = 0;
}
public override int Read (byte[] buffer, int offset, int count)
{
int read = BaseStream.Read (buffer, offset, count);
m_count += read;
return read;
}
public override int ReadByte ()
{
int b = BaseStream.ReadByte();
if (b != -1)
++m_count;
return b;
}
public override void Write (byte[] buffer, int offset, int count)
{
BaseStream.Write (buffer, offset, count);
m_count += count;
}
public override void WriteByte (byte b)
{
BaseStream.WriteByte (b);
++m_count;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Humanizer;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Mods;
using osu.Game.Utils;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
#nullable enable
namespace osu.Game.Overlays.Mods
{
public class ModColumn : CompositeDrawable
{
private Func<Mod, bool>? filter;
/// <summary>
/// Function determining whether each mod in the column should be displayed.
/// A return value of <see langword="true"/> means that the mod is not filtered and therefore its corresponding panel should be displayed.
/// A return value of <see langword="false"/> means that the mod is filtered out and therefore its corresponding panel should be hidden.
/// </summary>
public Func<Mod, bool>? Filter
{
get => filter;
set
{
filter = value;
updateFilter();
}
}
private readonly ModType modType;
private readonly Key[]? toggleKeys;
private readonly Bindable<Dictionary<ModType, IReadOnlyList<Mod>>> availableMods = new Bindable<Dictionary<ModType, IReadOnlyList<Mod>>>();
private readonly TextFlowContainer headerText;
private readonly Box headerBackground;
private readonly Container contentContainer;
private readonly Box contentBackground;
private readonly FillFlowContainer<ModPanel> panelFlow;
private readonly ToggleAllCheckbox? toggleAllCheckbox;
private Colour4 accentColour;
private Task? latestLoadTask;
internal bool ItemsLoaded => latestLoadTask == null;
private const float header_height = 42;
public ModColumn(ModType modType, bool allowBulkSelection, Key[]? toggleKeys = null)
{
this.modType = modType;
this.toggleKeys = toggleKeys;
Width = 320;
RelativeSizeAxes = Axes.Y;
Shear = new Vector2(ModPanel.SHEAR_X, 0);
CornerRadius = ModPanel.CORNER_RADIUS;
Masking = true;
Container controlContainer;
InternalChildren = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.X,
Height = header_height + ModPanel.CORNER_RADIUS,
Children = new Drawable[]
{
headerBackground = new Box
{
RelativeSizeAxes = Axes.X,
Height = header_height + ModPanel.CORNER_RADIUS
},
headerText = new OsuTextFlowContainer(t =>
{
t.Font = OsuFont.TorusAlternate.With(size: 17);
t.Shadow = false;
t.Colour = Colour4.Black;
})
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Shear = new Vector2(-ModPanel.SHEAR_X, 0),
Padding = new MarginPadding
{
Horizontal = 17,
Bottom = ModPanel.CORNER_RADIUS
}
}
}
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = header_height },
Child = contentContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
CornerRadius = ModPanel.CORNER_RADIUS,
BorderThickness = 3,
Children = new Drawable[]
{
contentBackground = new Box
{
RelativeSizeAxes = Axes.Both
},
new GridContainer
{
RelativeSizeAxes = Axes.Both,
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
new Dimension()
},
Content = new[]
{
new Drawable[]
{
controlContainer = new Container
{
RelativeSizeAxes = Axes.X,
Padding = new MarginPadding { Horizontal = 14 }
}
},
new Drawable[]
{
new OsuScrollContainer
{
RelativeSizeAxes = Axes.Both,
ScrollbarOverlapsContent = false,
Child = panelFlow = new FillFlowContainer<ModPanel>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Spacing = new Vector2(0, 7),
Padding = new MarginPadding(7)
}
}
}
}
}
}
}
}
};
createHeaderText();
if (allowBulkSelection)
{
controlContainer.Height = 35;
controlContainer.Add(toggleAllCheckbox = new ToggleAllCheckbox(this)
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Scale = new Vector2(0.8f),
RelativeSizeAxes = Axes.X,
LabelText = "Enable All",
Shear = new Vector2(-ModPanel.SHEAR_X, 0)
});
panelFlow.Padding = new MarginPadding
{
Top = 0,
Bottom = 7,
Horizontal = 7
};
}
}
private void createHeaderText()
{
IEnumerable<string> headerTextWords = modType.Humanize(LetterCasing.Title).Split(' ');
if (headerTextWords.Count() > 1)
{
headerText.AddText($"{headerTextWords.First()} ", t => t.Font = t.Font.With(weight: FontWeight.SemiBold));
headerTextWords = headerTextWords.Skip(1);
}
headerText.AddText(string.Join(' ', headerTextWords));
}
[BackgroundDependencyLoader]
private void load(OsuGameBase game, OverlayColourProvider colourProvider, OsuColour colours)
{
availableMods.BindTo(game.AvailableMods);
headerBackground.Colour = accentColour = colours.ForModType(modType);
if (toggleAllCheckbox != null)
{
toggleAllCheckbox.AccentColour = accentColour;
toggleAllCheckbox.AccentHoverColour = accentColour.Lighten(0.3f);
}
contentContainer.BorderColour = ColourInfo.GradientVertical(colourProvider.Background4, colourProvider.Background3);
contentBackground.Colour = colourProvider.Background4;
}
protected override void LoadComplete()
{
base.LoadComplete();
availableMods.BindValueChanged(_ => Scheduler.AddOnce(updateMods));
updateMods();
}
private CancellationTokenSource? cancellationTokenSource;
private void updateMods()
{
var newMods = ModUtils.FlattenMods(availableMods.Value.GetValueOrDefault(modType) ?? Array.Empty<Mod>()).ToList();
if (newMods.SequenceEqual(panelFlow.Children.Select(p => p.Mod)))
return;
cancellationTokenSource?.Cancel();
var panels = newMods.Select(mod => new ModPanel(mod)
{
Shear = new Vector2(-ModPanel.SHEAR_X, 0)
});
Task? loadTask;
latestLoadTask = loadTask = LoadComponentsAsync(panels, loaded =>
{
panelFlow.ChildrenEnumerable = loaded;
foreach (var panel in panelFlow)
panel.Active.BindValueChanged(_ => updateToggleState());
updateToggleState();
updateFilter();
}, (cancellationTokenSource = new CancellationTokenSource()).Token);
loadTask.ContinueWith(_ =>
{
if (loadTask == latestLoadTask)
latestLoadTask = null;
});
}
#region Bulk select / deselect
private const double initial_multiple_selection_delay = 120;
private double selectionDelay = initial_multiple_selection_delay;
private double lastSelection;
private readonly Queue<Action> pendingSelectionOperations = new Queue<Action>();
protected bool SelectionAnimationRunning => pendingSelectionOperations.Count > 0;
protected override void Update()
{
base.Update();
if (selectionDelay == initial_multiple_selection_delay || Time.Current - lastSelection >= selectionDelay)
{
if (pendingSelectionOperations.TryDequeue(out var dequeuedAction))
{
dequeuedAction();
// each time we play an animation, we decrease the time until the next animation (to ramp the visual and audible elements).
selectionDelay = Math.Max(30, selectionDelay * 0.8f);
lastSelection = Time.Current;
}
else
{
// reset the selection delay after all animations have been completed.
// this will cause the next action to be immediately performed.
selectionDelay = initial_multiple_selection_delay;
}
}
}
private void updateToggleState()
{
if (toggleAllCheckbox != null && !SelectionAnimationRunning)
{
toggleAllCheckbox.Alpha = panelFlow.Any(panel => !panel.Filtered.Value) ? 1 : 0;
toggleAllCheckbox.Current.Value = panelFlow.Where(panel => !panel.Filtered.Value).All(panel => panel.Active.Value);
}
}
/// <summary>
/// Selects all mods.
/// </summary>
public void SelectAll()
{
pendingSelectionOperations.Clear();
foreach (var button in panelFlow.Where(b => !b.Active.Value && !b.Filtered.Value))
pendingSelectionOperations.Enqueue(() => button.Active.Value = true);
}
/// <summary>
/// Deselects all mods.
/// </summary>
public void DeselectAll()
{
pendingSelectionOperations.Clear();
foreach (var button in panelFlow.Where(b => b.Active.Value && !b.Filtered.Value))
pendingSelectionOperations.Enqueue(() => button.Active.Value = false);
}
private class ToggleAllCheckbox : OsuCheckbox
{
private Color4 accentColour;
public Color4 AccentColour
{
get => accentColour;
set
{
accentColour = value;
updateState();
}
}
private Color4 accentHoverColour;
public Color4 AccentHoverColour
{
get => accentHoverColour;
set
{
accentHoverColour = value;
updateState();
}
}
private readonly ModColumn column;
public ToggleAllCheckbox(ModColumn column)
: base(false)
{
this.column = column;
}
protected override void ApplyLabelParameters(SpriteText text)
{
base.ApplyLabelParameters(text);
text.Font = text.Font.With(weight: FontWeight.SemiBold);
}
[BackgroundDependencyLoader]
private void load()
{
updateState();
}
private void updateState()
{
Nub.AccentColour = AccentColour;
Nub.GlowingAccentColour = AccentHoverColour;
Nub.GlowColour = AccentHoverColour.Opacity(0.2f);
}
protected override void OnUserChange(bool value)
{
if (value)
column.SelectAll();
else
column.DeselectAll();
}
}
#endregion
#region Filtering support
private void updateFilter()
{
foreach (var modPanel in panelFlow)
modPanel.ApplyFilter(Filter);
updateToggleState();
}
#endregion
#region Keyboard selection support
protected override bool OnKeyDown(KeyDownEvent e)
{
if (e.ControlPressed || e.AltPressed) return false;
if (toggleKeys == null) return false;
int index = Array.IndexOf(toggleKeys, e.Key);
if (index < 0) return false;
var panel = panelFlow.ElementAtOrDefault(index);
if (panel == null || panel.Filtered.Value) return false;
panel.Active.Toggle();
return true;
}
#endregion
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleFix.SampleFixPublic
File: MainWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleFix
{
using System;
using System.ComponentModel;
using System.IO;
using System.Security;
using System.Windows;
using Ecng.Common;
using Ecng.Serialization;
using Ecng.Xaml;
using StockSharp.Messages;
using StockSharp.BusinessEntities;
using StockSharp.Fix;
using StockSharp.Logging;
using StockSharp.Localization;
public partial class MainWindow
{
private bool _isInitialized;
public readonly FixTrader Trader = new FixTrader();
private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow();
private readonly TradesWindow _tradesWindow = new TradesWindow();
private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow();
private readonly OrdersWindow _ordersWindow = new OrdersWindow();
private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow();
private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow();
private readonly NewsWindow _newsWindow = new NewsWindow();
private readonly LogManager _logManager = new LogManager();
private const string _settingsFile = "fix_settings.xml";
public MainWindow()
{
InitializeComponent();
Title = Title.Put("FIX");
_ordersWindow.MakeHideable();
_myTradesWindow.MakeHideable();
_tradesWindow.MakeHideable();
_securitiesWindow.MakeHideable();
_stopOrdersWindow.MakeHideable();
_portfoliosWindow.MakeHideable();
_newsWindow.MakeHideable();
if (File.Exists(_settingsFile))
{
Trader.Load(new XmlSerializer<SettingsStorage>().Deserialize(_settingsFile));
}
MarketDataSessionSettings.SelectedObject = Trader.MarketDataAdapter;
TransactionSessionSettings.SelectedObject = Trader.TransactionAdapter;
MarketDataSupportedMessages.Adapter = Trader.MarketDataAdapter;
TransactionSupportedMessages.Adapter = Trader.TransactionAdapter;
Instance = this;
Trader.LogLevel = LogLevels.Debug;
_logManager.Sources.Add(Trader);
_logManager.Listeners.Add(new FileLogListener { LogDirectory = "StockSharp_Fix" });
}
protected override void OnClosing(CancelEventArgs e)
{
_ordersWindow.DeleteHideable();
_myTradesWindow.DeleteHideable();
_tradesWindow.DeleteHideable();
_securitiesWindow.DeleteHideable();
_stopOrdersWindow.DeleteHideable();
_portfoliosWindow.DeleteHideable();
_newsWindow.DeleteHideable();
_securitiesWindow.Close();
_tradesWindow.Close();
_myTradesWindow.Close();
_stopOrdersWindow.Close();
_ordersWindow.Close();
_portfoliosWindow.Close();
_newsWindow.Close();
if (Trader != null)
Trader.Dispose();
base.OnClosing(e);
}
public static MainWindow Instance { get; private set; }
private void ConnectClick(object sender, RoutedEventArgs e)
{
if (!_isInitialized)
{
_isInitialized = true;
Trader.Restored += () => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(true);
MessageBox.Show(this, LocalizedStrings.Str2958);
});
// subscribe on connection successfully event
Trader.Connected += () =>
{
this.GuiAsync(() => ChangeConnectStatus(true));
};
Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));
// subscribe on connection error event
Trader.ConnectionError += error => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(false);
MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
});
// subscribe on error event
Trader.Error += error =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
// subscribe on error of market data subscription event
Trader.MarketDataSubscriptionFailed += (security, msg, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));
Trader.NewSecurity += security => _securitiesWindow.SecurityPicker.Securities.Add(security);
Trader.NewMyTrade += trade => _myTradesWindow.TradeGrid.Trades.Add(trade);
Trader.NewTrade += trade => _tradesWindow.TradeGrid.Trades.Add(trade);
Trader.NewOrder += order => _ordersWindow.OrderGrid.Orders.Add(order);
Trader.NewStopOrder += order => _stopOrdersWindow.OrderGrid.Orders.Add(order);
Trader.NewPortfolio += portfolio =>
{
// subscribe on portfolio updates
//portfolios.ForEach(Trader.RegisterPortfolio);
_portfoliosWindow.PortfolioGrid.Portfolios.Add(portfolio);
};
Trader.NewPosition += position => _portfoliosWindow.PortfolioGrid.Positions.Add(position);
// subscribe on error of order registration event
Trader.OrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail;
// subscribe on error of order cancelling event
Trader.OrderCancelFailed += OrderFailed;
// subscribe on error of stop-order registration event
Trader.StopOrderRegisterFailed += _stopOrdersWindow.OrderGrid.AddRegistrationFail;
// subscribe on error of stop-order cancelling event
Trader.StopOrderCancelFailed += OrderFailed;
Trader.MassOrderCancelFailed += (transId, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716));
Trader.NewNews += news => _newsWindow.NewsPanel.NewsGrid.News.Add(news);
// set market data provider
_securitiesWindow.SecurityPicker.MarketDataProvider = Trader;
// set news provider
_newsWindow.NewsPanel.NewsProvider = Trader;
ShowSecurities.IsEnabled = ShowTrades.IsEnabled = ShowNews.IsEnabled =
ShowMyTrades.IsEnabled = ShowOrders.IsEnabled =
ShowPortfolios.IsEnabled = ShowStopOrders.IsEnabled = true;
}
if (Trader.ConnectionState == ConnectionStates.Failed || Trader.ConnectionState == ConnectionStates.Disconnected)
{
new XmlSerializer<SettingsStorage>().Serialize(Trader.Save(), _settingsFile);
if (!NewPassword.Password.IsEmpty())
Trader.SendInMessage(new ChangePasswordMessage { NewPassword = NewPassword.Password.To<SecureString>() });
else
Trader.Connect();
}
else if (Trader.ConnectionState == ConnectionStates.Connected)
{
Trader.Disconnect();
}
}
private void OrderFailed(OrderFail fail)
{
this.GuiAsync(() =>
{
MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153);
});
}
private void ChangeConnectStatus(bool isConnected)
{
ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect;
}
private void ShowSecuritiesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_securitiesWindow);
}
private void ShowTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_tradesWindow);
}
private void ShowMyTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_myTradesWindow);
}
private void ShowOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_ordersWindow);
}
private void ShowPortfoliosClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_portfoliosWindow);
}
private void ShowStopOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_stopOrdersWindow);
}
private void ShowNewsClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_newsWindow);
}
private static void ShowOrHide(Window window)
{
if (window == null)
throw new ArgumentNullException(nameof(window));
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
}
}
| |
using System;
using System.Configuration;
using System.Text.RegularExpressions;
namespace SecuritySwitch.Configuration {
/// <summary>
/// The possible ways to ignore HTTP handlers.
/// </summary>
public enum IgnoreHandlers {
/// <summary>
/// Indicates that the module should ignore the built-in HTTP handlers.
/// <list type="bullet">
/// <item>Trace.axd</item>
/// <item>WebResource.axd</item>
/// </list>
/// </summary>
BuiltIn,
/// <summary>
/// Indicates that the module should ignore all files with extensions corresponding
/// to the standard for HTTP handlers. Currently, that is .axd files.
/// </summary>
WithStandardExtensions,
/// <summary>
/// Indicates that the module will not ignore handlers unless specifically
/// specified in the files or directories entries.
/// </summary>
/// <remarks>
/// This was the default behavior prior to version 3.1.
/// </remarks>
None
}
/// <summary>
/// The different modes supported for the <securitySwitch> configuration section.
/// </summary>
public enum Mode {
/// <summary>
/// Indicates that web page security is on and all requests should be monitored.
/// </summary>
On,
/// <summary>
/// Only remote requests are to be monitored.
/// </summary>
RemoteOnly,
/// <summary>
/// Only local requests are to be monitored.
/// </summary>
LocalOnly,
/// <summary>
/// Web page security is off and no monitoring should occur.
/// </summary>
Off
}
/// <summary>
/// The different modes for bypassing security warnings.
/// </summary>
public enum SecurityWarningBypassMode {
/// <summary>
/// Always bypass security warnings when switching to an unencrypted page.
/// </summary>
AlwaysBypass,
/// <summary>
/// Only bypass security warnings when switching to an unencrypted page if the proper query parameter is present.
/// </summary>
BypassWithQueryParam,
/// <summary>
/// Never bypass security warnings when switching to an unencrypted page.
/// </summary>
NeverBypass
}
/// <summary>
/// Contains the settings of a <securitySwitch> configuration section.
/// </summary>
public class Settings : ConfigurationSection {
/// <summary>
/// Creates an instance of Settings.
/// </summary>
public Settings()
: base() {
}
#region Properties
/// <summary>
/// Gets or sets the name of the query parameter that will indicate to the module to bypass
/// any security warning if WarningBypassMode = BypassWithQueryParam.
/// </summary>
[ConfigurationProperty("bypassQueryParamName")]
public string BypassQueryParamName {
get { return (string)this["bypassQueryParamName"]; }
set { this["bypassQueryParamName"] = value; }
}
/// <summary>
/// Gets or sets the path to a URI for encrypted redirections, if any.
/// </summary>
[ConfigurationProperty("encryptedUri"), RegexStringValidator(@"^(?:|(?:https://)?[\w\-][\w\.\-,]*(?:\:\d+)?(?:/[\w\.\-]+)*/?)$")]
public string EncryptedUri {
get { return (string)this["encryptedUri"]; }
set {
if (!string.IsNullOrEmpty(value))
this["encryptedUri"] = value;
else
this["encryptedUri"] = null;
}
}
/// <summary>
/// Gets or sets a flag indicating how to ignore HTTP handlers, if at all.
/// </summary>
[ConfigurationProperty("ignoreHandlers", DefaultValue = IgnoreHandlers.BuiltIn)]
public IgnoreHandlers IgnoreHandlers {
get { return (IgnoreHandlers)this["ignoreHandlers"]; }
set { this["ignoreHandlers"] = value; }
}
/// <summary>
/// Gets or sets a flag indicating whether or not to maintain the current path when redirecting
/// to a different host.
/// </summary>
[ConfigurationProperty("maintainPath", DefaultValue = true)]
public bool MaintainPath {
get { return (bool)this["maintainPath"]; }
set { this["maintainPath"] = value; }
}
/// <summary>
/// Gets or sets the mode indicating how the secure switch settings are handled.
/// </summary>
[ConfigurationProperty("mode", DefaultValue = Mode.On)]
public Mode Mode {
get { return (Mode)this["mode"]; }
set { this["mode"] = value; }
}
/// <summary>
/// Gets the collection of directory settings read from the configuration section.
/// </summary>
[ConfigurationProperty("directories")]
public DirectorySettingCollection Directories {
get { return (DirectorySettingCollection)this["directories"]; }
}
/// <summary>
/// Gets the collection of file settings read from the configuration section.
/// </summary>
[ConfigurationProperty("files")]
public FileSettingCollection Files {
get { return (FileSettingCollection)this["files"]; }
}
/// <summary>
/// Gets or sets the path to a URI for unencrypted redirections, if any.
/// </summary>
[ConfigurationProperty("unencryptedUri"), RegexStringValidator(@"^(?:|(?:http://)?[\w\-][\w\.\-,]*(?:\:\d+)?(?:/[\w\.\-]+)*/?)$")]
public string UnencryptedUri {
get { return (string)this["unencryptedUri"]; }
set {
if (!string.IsNullOrEmpty(value))
this["unencryptedUri"] = value;
else
this["unencryptedUri"] = null;
}
}
/// <summary>
/// Gets or sets the bypass mode indicating whether or not to bypass security warnings
/// when switching to a unencrypted page.
/// </summary>
[ConfigurationProperty("warningBypassMode", DefaultValue = SecurityWarningBypassMode.BypassWithQueryParam)]
public SecurityWarningBypassMode WarningBypassMode {
get { return (SecurityWarningBypassMode)this["warningBypassMode"]; }
set { this["warningBypassMode"] = value; }
}
/// <summary>
/// This property is for internal use and is not meant to be set.
/// </summary>
[ConfigurationProperty("xmlns")]
public string XmlNamespace {
get { return (string)this["xmlns"]; }
set { this["xmlns"] = value; }
}
#endregion
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
*****************************************************************************/
#pragma warning disable 0219
/*****************************************************************************
* Spine Editor Utilities created by Mitch Thompson
* Full irrevocable rights and permissions granted to Esoteric Software
*****************************************************************************/
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using System.Reflection;
using Spine;
[InitializeOnLoad]
public class SpineEditorUtilities : AssetPostprocessor {
public static class Icons {
public static Texture2D skeleton;
public static Texture2D nullBone;
public static Texture2D bone;
public static Texture2D poseBones;
public static Texture2D boneNib;
public static Texture2D slot;
public static Texture2D slotRoot;
public static Texture2D skinPlaceholder;
public static Texture2D image;
public static Texture2D boundingBox;
public static Texture2D mesh;
public static Texture2D weights;
public static Texture2D skin;
public static Texture2D skinsRoot;
public static Texture2D animation;
public static Texture2D animationRoot;
public static Texture2D spine;
public static Texture2D _event;
public static Texture2D constraintNib;
public static Texture2D warning;
public static Texture2D skeletonUtility;
public static Texture2D hingeChain;
public static Texture2D subMeshRenderer;
public static Texture2D unityIcon;
public static Texture2D controllerIcon;
public static Mesh boneMesh {
get {
if (_boneMesh == null) {
_boneMesh = new Mesh();
_boneMesh.vertices = new Vector3[4] {
Vector3.zero,
new Vector3(-0.1f, 0.1f, 0),
Vector3.up,
new Vector3(0.1f, 0.1f, 0)
};
_boneMesh.uv = new Vector2[4];
_boneMesh.triangles = new int[6] { 0, 1, 2, 2, 3, 0 };
_boneMesh.RecalculateBounds();
_boneMesh.RecalculateNormals();
}
return _boneMesh;
}
}
internal static Mesh _boneMesh;
public static Material boneMaterial {
get {
if (_boneMaterial == null) {
#if UNITY_4_3
_boneMaterial = new Material(Shader.Find("Particles/Alpha Blended"));
_boneMaterial.SetColor("_TintColor", new Color(0.4f, 0.4f, 0.4f, 0.25f));
#else
_boneMaterial = new Material(Shader.Find("Spine/Bones"));
_boneMaterial.SetColor("_Color", new Color(0.4f, 0.4f, 0.4f, 0.25f));
#endif
}
return _boneMaterial;
}
}
internal static Material _boneMaterial;
public static void Initialize () {
skeleton = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-skeleton.png");
nullBone = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-null.png");
bone = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-bone.png");
poseBones = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-poseBones.png");
boneNib = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-boneNib.png");
slot = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-slot.png");
slotRoot = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-slotRoot.png");
skinPlaceholder = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-skinPlaceholder.png");
image = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-image.png");
boundingBox = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-boundingBox.png");
mesh = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-mesh.png");
weights = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-weights.png");
skin = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-skinPlaceholder.png");
skinsRoot = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-skinsRoot.png");
animation = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-animation.png");
animationRoot = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-animationRoot.png");
spine = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-spine.png");
_event = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-event.png");
constraintNib = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-constraintNib.png");
warning = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-warning.png");
skeletonUtility = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-skeletonUtility.png");
hingeChain = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-hingeChain.png");
subMeshRenderer = (Texture2D)AssetDatabase.LoadMainAssetAtPath(SpineEditorUtilities.editorGUIPath + "/icon-subMeshRenderer.png");
unityIcon = EditorGUIUtility.FindTexture("SceneAsset Icon");
controllerIcon = EditorGUIUtility.FindTexture("AnimatorController Icon");
}
}
public static string editorPath = "";
public static string editorGUIPath = "";
static HashSet<string> assetsImportedInWrongState;
static Dictionary<int, GameObject> skeletonRendererTable;
static Dictionary<int, SkeletonUtilityBone> skeletonUtilityBoneTable;
static Dictionary<int, BoundingBoxFollower> boundingBoxFollowerTable;
public static float defaultScale = 0.01f;
public static float defaultMix = 0.2f;
public static string defaultShader = "Spine/Skeleton";
public static bool initialized;
const string DEFAULT_MIX_KEY = "SPINE_DEFAULT_MIX";
static SpineEditorUtilities () {
Initialize();
}
static void Initialize () {
defaultMix = EditorPrefs.GetFloat(DEFAULT_MIX_KEY, 0.2f);
DirectoryInfo rootDir = new DirectoryInfo(Application.dataPath);
FileInfo[] files = rootDir.GetFiles("SpineEditorUtilities.cs", SearchOption.AllDirectories);
editorPath = Path.GetDirectoryName(files[0].FullName.Replace("\\", "/").Replace(Application.dataPath, "Assets"));
editorGUIPath = editorPath + "/GUI";
Icons.Initialize();
assetsImportedInWrongState = new HashSet<string>();
skeletonRendererTable = new Dictionary<int, GameObject>();
skeletonUtilityBoneTable = new Dictionary<int, SkeletonUtilityBone>();
boundingBoxFollowerTable = new Dictionary<int, BoundingBoxFollower>();
EditorApplication.hierarchyWindowChanged += HierarchyWindowChanged;
EditorApplication.hierarchyWindowItemOnGUI += HierarchyWindowItemOnGUI;
HierarchyWindowChanged();
initialized = true;
}
public static void ConfirmInitialization () {
if (!initialized || Icons.skeleton == null)
Initialize();
}
static void HierarchyWindowChanged () {
skeletonRendererTable.Clear();
skeletonUtilityBoneTable.Clear();
boundingBoxFollowerTable.Clear();
SkeletonRenderer[] arr = Object.FindObjectsOfType<SkeletonRenderer>();
foreach (SkeletonRenderer r in arr)
skeletonRendererTable.Add(r.gameObject.GetInstanceID(), r.gameObject);
SkeletonUtilityBone[] boneArr = Object.FindObjectsOfType<SkeletonUtilityBone>();
foreach (SkeletonUtilityBone b in boneArr)
skeletonUtilityBoneTable.Add(b.gameObject.GetInstanceID(), b);
BoundingBoxFollower[] bbfArr = Object.FindObjectsOfType<BoundingBoxFollower>();
foreach (BoundingBoxFollower bbf in bbfArr)
boundingBoxFollowerTable.Add(bbf.gameObject.GetInstanceID(), bbf);
}
static void HierarchyWindowItemOnGUI (int instanceId, Rect selectionRect) {
if (skeletonRendererTable.ContainsKey(instanceId)) {
Rect r = new Rect(selectionRect);
r.x = r.width - 15;
r.width = 15;
GUI.Label(r, Icons.spine);
} else if (skeletonUtilityBoneTable.ContainsKey(instanceId)) {
Rect r = new Rect(selectionRect);
r.x -= 26;
if (skeletonUtilityBoneTable[instanceId] != null) {
if (skeletonUtilityBoneTable[instanceId].transform.childCount == 0)
r.x += 13;
r.y += 2;
r.width = 13;
r.height = 13;
if (skeletonUtilityBoneTable[instanceId].mode == SkeletonUtilityBone.Mode.Follow) {
GUI.DrawTexture(r, Icons.bone);
} else {
GUI.DrawTexture(r, Icons.poseBones);
}
}
} else if (boundingBoxFollowerTable.ContainsKey(instanceId)) {
Rect r = new Rect(selectionRect);
r.x -= 26;
if (boundingBoxFollowerTable[instanceId] != null) {
if (boundingBoxFollowerTable[instanceId].transform.childCount == 0)
r.x += 13;
r.y += 2;
r.width = 13;
r.height = 13;
GUI.DrawTexture(r, Icons.boundingBox);
}
}
}
static void OnPostprocessAllAssets (string[] imported, string[] deleted, string[] moved, string[] movedFromAssetPaths) {
if (imported.Length == 0)
return;
// In case user used "Assets -> Reimport All", during the import process,
// asset database is not initialized until some point. During that period,
// all attempts to load any assets using API (i.e. AssetDatabase.LoadAssetAtPath)
// will return null, and as result, assets won't be loaded even if they actually exists,
// which may lead to numerous importing errors.
// This situation also happens if Library folder is deleted from the project, which is a pretty
// common case, since when using version control systems, the Library folder must be excluded.
//
// So to avoid this, in case asset database is not available, we delay loading the assets
// until next time.
//
// Unity *always* reimports some internal assets after the process is done, so this method
// is always called once again in a state when asset database is available.
//
// Checking whether AssetDatabase is initialized is done by attempting to load
// a known "marker" asset that should always be available. Failing to load this asset
// means that AssetDatabase is not initialized.
assetsImportedInWrongState.UnionWith(imported);
if (AssetDatabaseAvailabilityDetector.IsAssetDatabaseAvailable()) {
string[] combinedAssets = assetsImportedInWrongState.ToArray();
assetsImportedInWrongState.Clear();
ImportSpineContent(combinedAssets);
}
}
public static void ImportSpineContent (string[] imported, bool reimport = false) {
List<string> atlasPaths = new List<string>();
List<string> imagePaths = new List<string>();
List<string> skeletonPaths = new List<string>();
foreach (string str in imported) {
string extension = Path.GetExtension(str).ToLower();
switch (extension) {
case ".txt":
if (str.EndsWith(".atlas.txt")) {
atlasPaths.Add(str);
}
break;
case ".png":
case ".jpg":
imagePaths.Add(str);
break;
case ".json":
if (IsValidSpineData((TextAsset)AssetDatabase.LoadAssetAtPath(str, typeof(TextAsset))))
skeletonPaths.Add(str);
break;
case ".bytes":
if (str.ToLower().EndsWith(".skel.bytes")) {
if (IsValidSpineData((TextAsset)AssetDatabase.LoadAssetAtPath(str, typeof(TextAsset))))
skeletonPaths.Add(str);
}
break;
}
}
List<AtlasAsset> atlases = new List<AtlasAsset>();
//import atlases first
foreach (string ap in atlasPaths) {
if (!reimport && CheckForValidAtlas(ap))
continue;
TextAsset atlasText = (TextAsset)AssetDatabase.LoadAssetAtPath(ap, typeof(TextAsset));
AtlasAsset atlas = IngestSpineAtlas(atlasText);
atlases.Add(atlas);
}
//import skeletons and match them with atlases
bool abortSkeletonImport = false;
foreach (string sp in skeletonPaths) {
if (!reimport && CheckForValidSkeletonData(sp)) {
ResetExistingSkeletonData(sp);
continue;
}
string dir = Path.GetDirectoryName(sp);
var localAtlases = FindAtlasesAtPath(dir);
var requiredPaths = GetRequiredAtlasRegions(sp);
var atlasMatch = GetMatchingAtlas(requiredPaths, localAtlases);
if (atlasMatch != null) {
IngestSpineProject(AssetDatabase.LoadAssetAtPath(sp, typeof(TextAsset)) as TextAsset, atlasMatch);
} else {
bool resolved = false;
while (!resolved) {
int result = EditorUtility.DisplayDialogComplex("Skeleton JSON Import Error!", "Could not find matching AtlasAsset for " + Path.GetFileNameWithoutExtension(sp), "Select", "Skip", "Abort");
switch (result) {
case -1:
Debug.Log("Select Atlas");
AtlasAsset selectedAtlas = GetAtlasDialog(Path.GetDirectoryName(sp));
if (selectedAtlas != null) {
localAtlases.Clear();
localAtlases.Add(selectedAtlas);
atlasMatch = GetMatchingAtlas(requiredPaths, localAtlases);
if (atlasMatch != null) {
resolved = true;
IngestSpineProject(AssetDatabase.LoadAssetAtPath(sp, typeof(TextAsset)) as TextAsset, atlasMatch);
}
}
break;
case 0:
var atlasList = MultiAtlasDialog(requiredPaths, Path.GetDirectoryName(sp), Path.GetFileNameWithoutExtension(sp));
if (atlasList != null)
IngestSpineProject(AssetDatabase.LoadAssetAtPath(sp, typeof(TextAsset)) as TextAsset, atlasList.ToArray());
resolved = true;
break;
case 1:
Debug.Log("Skipped importing: " + Path.GetFileName(sp));
resolved = true;
break;
case 2:
//abort
abortSkeletonImport = true;
resolved = true;
break;
}
}
}
if (abortSkeletonImport)
break;
}
//TODO: any post processing of images
}
static bool CheckForValidSkeletonData (string skeletonJSONPath) {
string dir = Path.GetDirectoryName(skeletonJSONPath);
TextAsset textAsset = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonJSONPath, typeof(TextAsset));
DirectoryInfo dirInfo = new DirectoryInfo(dir);
FileInfo[] files = dirInfo.GetFiles("*.asset");
foreach (var f in files) {
string localPath = dir + "/" + f.Name;
var obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object));
if (obj is SkeletonDataAsset) {
var skeletonDataAsset = (SkeletonDataAsset)obj;
if (skeletonDataAsset.skeletonJSON == textAsset)
return true;
}
}
return false;
}
static void ResetExistingSkeletonData (string skeletonJSONPath) {
string dir = Path.GetDirectoryName(skeletonJSONPath);
TextAsset textAsset = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonJSONPath, typeof(TextAsset));
DirectoryInfo dirInfo = new DirectoryInfo(dir);
FileInfo[] files = dirInfo.GetFiles("*.asset");
foreach (var f in files) {
string localPath = dir + "/" + f.Name;
var obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object));
if (obj is SkeletonDataAsset) {
var skeletonDataAsset = (SkeletonDataAsset)obj;
if (skeletonDataAsset.skeletonJSON == textAsset) {
if (Selection.activeObject == skeletonDataAsset)
Selection.activeObject = null;
skeletonDataAsset.Reset();
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(skeletonDataAsset));
string lastHash = EditorPrefs.GetString(guid + "_hash");
// For some weird reason sometimes Unity loses the internal Object pointer,
// and as a result, all comparisons with null returns true.
// But the C# wrapper is still alive, so we can "restore" the object
// by reloading it from its Instance ID.
AtlasAsset[] skeletonDataAtlasAssets = skeletonDataAsset.atlasAssets;
if (skeletonDataAtlasAssets != null) {
for (int i = 0; i < skeletonDataAtlasAssets.Length; i++) {
if (!ReferenceEquals(null, skeletonDataAtlasAssets[i]) &&
skeletonDataAtlasAssets[i].Equals(null) &&
skeletonDataAtlasAssets[i].GetInstanceID() != 0
) {
skeletonDataAtlasAssets[i] = EditorUtility.InstanceIDToObject(skeletonDataAtlasAssets[i].GetInstanceID()) as AtlasAsset;
}
}
}
SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(true);
string currentHash = skeletonData != null ? skeletonData.Hash : null;
if (currentHash == null || lastHash != currentHash) {
//do any upkeep on synchronized assets
UpdateMecanimClips(skeletonDataAsset);
}
if (currentHash != null) {
EditorPrefs.SetString(guid + "_hash", currentHash);
}
}
}
}
}
static void UpdateMecanimClips (SkeletonDataAsset skeletonDataAsset) {
if (skeletonDataAsset.controller == null)
return;
SkeletonBaker.GenerateMecanimAnimationClips(skeletonDataAsset);
}
static bool CheckForValidAtlas (string atlasPath) {
return false;
//////////////DEPRECATED - always check for new atlas data now
/*
string dir = Path.GetDirectoryName(atlasPath);
TextAsset textAsset = (TextAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(TextAsset));
DirectoryInfo dirInfo = new DirectoryInfo(dir);
FileInfo[] files = dirInfo.GetFiles("*.asset");
foreach (var f in files) {
string localPath = dir + "/" + f.Name;
var obj = AssetDatabase.LoadAssetAtPath(localPath, typeof(Object));
if (obj is AtlasAsset) {
var atlasAsset = (AtlasAsset)obj;
if (atlasAsset.atlasFile == textAsset) {
Atlas atlas = atlasAsset.GetAtlas();
FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic);
List<AtlasRegion> regions = (List<AtlasRegion>)field.GetValue(atlas);
string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset);
string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath);
string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name);
for (int i = 0; i < regions.Count; i++) {
AtlasRegion region = regions[i];
string bakedPrefabPath = Path.Combine(bakedDirPath, SpineEditorUtilities.GetPathSafeRegionName(region) + ".prefab").Replace("\\", "/");
GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject));
if (prefab != null) {
Debug.Log("Updating: " + region.name);
BakeRegion(atlasAsset, region);
}
}
return true;
}
}
}
return false;
*/
}
static List<AtlasAsset> MultiAtlasDialog (List<string> requiredPaths, string initialDirectory, string header = "") {
List<AtlasAsset> atlasAssets = new List<AtlasAsset>();
bool resolved = false;
string lastAtlasPath = initialDirectory;
while (!resolved) {
StringBuilder sb = new StringBuilder();
sb.AppendLine(header);
sb.AppendLine("Atlases:");
if (atlasAssets.Count == 0) {
sb.AppendLine("\t--none--");
}
for (int i = 0; i < atlasAssets.Count; i++) {
sb.AppendLine("\t" + atlasAssets[i].name);
}
sb.AppendLine();
sb.AppendLine("Missing Regions:");
List<string> missingRegions = new List<string>(requiredPaths);
foreach (var atlasAsset in atlasAssets) {
var atlas = atlasAsset.GetAtlas();
for (int i = 0; i < missingRegions.Count; i++) {
if (atlas.FindRegion(missingRegions[i]) != null) {
missingRegions.RemoveAt(i);
i--;
}
}
}
if (missingRegions.Count == 0) {
break;
}
for (int i = 0; i < missingRegions.Count; i++) {
sb.AppendLine("\t" + missingRegions[i]);
}
int result = EditorUtility.DisplayDialogComplex("Atlas Selection", sb.ToString(), "Select", "Finish", "Abort");
switch (result) {
case 0:
AtlasAsset selectedAtlasAsset = GetAtlasDialog(lastAtlasPath);
if (selectedAtlasAsset != null) {
var atlas = selectedAtlasAsset.GetAtlas();
bool hasValidRegion = false;
foreach (string str in missingRegions) {
if (atlas.FindRegion(str) != null) {
hasValidRegion = true;
break;
}
}
atlasAssets.Add(selectedAtlasAsset);
}
break;
case 1:
resolved = true;
break;
case 2:
atlasAssets = null;
resolved = true;
break;
}
}
return atlasAssets;
}
static AtlasAsset GetAtlasDialog (string dirPath) {
string path = EditorUtility.OpenFilePanel("Select AtlasAsset...", dirPath, "asset");
if (path == "")
return null;
int subLen = Application.dataPath.Length - 6;
string assetRelativePath = path.Substring(subLen, path.Length - subLen).Replace("\\", "/");
Object obj = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(AtlasAsset));
if (obj == null || obj.GetType() != typeof(AtlasAsset))
return null;
return (AtlasAsset)obj;
}
static void AddRequiredAtlasRegionsFromBinary (string skeletonDataPath, List<string> requiredPaths) {
SkeletonBinary binary = new SkeletonBinary(new AtlasRequirementLoader(requiredPaths));
TextAsset data = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonDataPath, typeof(TextAsset));
MemoryStream input = new MemoryStream(data.bytes);
binary.ReadSkeletonData(input);
binary = null;
}
public static List<string> GetRequiredAtlasRegions (string skeletonDataPath) {
List<string> requiredPaths = new List<string>();
if (skeletonDataPath.Contains(".skel")) {
AddRequiredAtlasRegionsFromBinary(skeletonDataPath, requiredPaths);
return requiredPaths;
}
TextAsset spineJson = (TextAsset)AssetDatabase.LoadAssetAtPath(skeletonDataPath, typeof(TextAsset));
StringReader reader = new StringReader(spineJson.text);
var root = Json.Deserialize(reader) as Dictionary<string, object>;
foreach (KeyValuePair<string, object> entry in (Dictionary<string, object>)root["skins"]) {
foreach (KeyValuePair<string, object> slotEntry in (Dictionary<string, object>)entry.Value) {
foreach (KeyValuePair<string, object> attachmentEntry in ((Dictionary<string, object>)slotEntry.Value)) {
var data = ((Dictionary<string, object>)attachmentEntry.Value);
if (data.ContainsKey("type")) {
if ((string)data["type"] == "boundingbox") {
continue;
}
}
if (data.ContainsKey("path"))
requiredPaths.Add((string)data["path"]);
else if (data.ContainsKey("name"))
requiredPaths.Add((string)data["name"]);
else
requiredPaths.Add(attachmentEntry.Key);
//requiredPaths.Add((string)sdf["path"]);
}
}
}
return requiredPaths;
}
static AtlasAsset GetMatchingAtlas (List<string> requiredPaths, List<AtlasAsset> atlasAssets) {
AtlasAsset atlasAssetMatch = null;
foreach (AtlasAsset a in atlasAssets) {
Atlas atlas = a.GetAtlas();
bool failed = false;
foreach (string regionPath in requiredPaths) {
if (atlas.FindRegion(regionPath) == null) {
failed = true;
break;
}
}
if (!failed) {
atlasAssetMatch = a;
break;
}
}
return atlasAssetMatch;
}
static List<AtlasAsset> FindAtlasesAtPath (string path) {
List<AtlasAsset> arr = new List<AtlasAsset>();
DirectoryInfo dir = new DirectoryInfo(path);
FileInfo[] assetInfoArr = dir.GetFiles("*.asset");
int subLen = Application.dataPath.Length - 6;
foreach (var f in assetInfoArr) {
string assetRelativePath = f.FullName.Substring(subLen, f.FullName.Length - subLen).Replace("\\", "/");
Object obj = AssetDatabase.LoadAssetAtPath(assetRelativePath, typeof(AtlasAsset));
if (obj != null) {
arr.Add(obj as AtlasAsset);
}
}
return arr;
}
public static bool IsValidSpineData (TextAsset asset) {
if (asset.name.Contains(".skel")) return true;
object obj = null;
try {
obj = Json.Deserialize(new StringReader(asset.text));
} catch (System.Exception) {
}
if (obj == null) {
Debug.LogError("Is not valid JSON");
return false;
}
Dictionary<string, object> root = (Dictionary<string, object>)obj;
if (!root.ContainsKey("skeleton"))
return false;
Dictionary<string, object> skeletonInfo = (Dictionary<string, object>)root["skeleton"];
string spineVersion = (string)skeletonInfo["spine"];
//TODO: reject old versions
return true;
}
static AtlasAsset IngestSpineAtlas (TextAsset atlasText) {
if (atlasText == null) {
Debug.LogWarning("Atlas source cannot be null!");
return null;
}
string primaryName = Path.GetFileNameWithoutExtension(atlasText.name).Replace(".atlas", "");
string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(atlasText));
string atlasPath = assetPath + "/" + primaryName + "_Atlas.asset";
AtlasAsset atlasAsset = (AtlasAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAsset));
List<Material> vestigialMaterials = new List<Material>();
if (atlasAsset == null)
atlasAsset = AtlasAsset.CreateInstance<AtlasAsset>();
else {
foreach (Material m in atlasAsset.materials)
vestigialMaterials.Add(m);
}
atlasAsset.atlasFile = atlasText;
//strip CR
string atlasStr = atlasText.text;
atlasStr = atlasStr.Replace("\r", "");
string[] atlasLines = atlasStr.Split('\n');
List<string> pageFiles = new List<string>();
for (int i = 0; i < atlasLines.Length - 1; i++) {
if (atlasLines[i].Trim().Length == 0)
pageFiles.Add(atlasLines[i + 1].Trim());
}
atlasAsset.materials = new Material[pageFiles.Count];
for (int i = 0; i < pageFiles.Count; i++) {
string texturePath = assetPath + "/" + pageFiles[i];
Texture2D texture = (Texture2D)AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D));
TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(texturePath);
texImporter.textureType = TextureImporterType.Advanced;
texImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;
texImporter.mipmapEnabled = false;
texImporter.alphaIsTransparency = false;
texImporter.maxTextureSize = 2048;
EditorUtility.SetDirty(texImporter);
AssetDatabase.ImportAsset(texturePath);
AssetDatabase.SaveAssets();
string pageName = Path.GetFileNameWithoutExtension(pageFiles[i]);
//because this looks silly
if (pageName == primaryName && pageFiles.Count == 1)
pageName = "Material";
string materialPath = assetPath + "/" + primaryName + "_" + pageName + ".mat";
Material mat = (Material)AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material));
if (mat == null) {
mat = new Material(Shader.Find(defaultShader));
AssetDatabase.CreateAsset(mat, materialPath);
} else {
vestigialMaterials.Remove(mat);
}
mat.mainTexture = texture;
EditorUtility.SetDirty(mat);
AssetDatabase.SaveAssets();
atlasAsset.materials[i] = mat;
}
for (int i = 0; i < vestigialMaterials.Count; i++)
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(vestigialMaterials[i]));
if (AssetDatabase.GetAssetPath(atlasAsset) == "")
AssetDatabase.CreateAsset(atlasAsset, atlasPath);
else
atlasAsset.Reset();
EditorUtility.SetDirty(atlasAsset);
AssetDatabase.SaveAssets();
//iterate regions and bake marked
Atlas atlas = atlasAsset.GetAtlas();
FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic);
List<AtlasRegion> regions = (List<AtlasRegion>)field.GetValue(atlas);
string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset);
string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath);
string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name);
bool hasBakedRegions = false;
for (int i = 0; i < regions.Count; i++) {
AtlasRegion region = regions[i];
string bakedPrefabPath = Path.Combine(bakedDirPath, SpineEditorUtilities.GetPathSafeRegionName(region) + ".prefab").Replace("\\", "/");
GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject));
if (prefab != null) {
BakeRegion(atlasAsset, region, false);
hasBakedRegions = true;
}
}
if (hasBakedRegions) {
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
return (AtlasAsset)AssetDatabase.LoadAssetAtPath(atlasPath, typeof(AtlasAsset));
}
public static GameObject BakeRegion (AtlasAsset atlasAsset, AtlasRegion region, bool autoSave = true) {
Atlas atlas = atlasAsset.GetAtlas();
string atlasAssetPath = AssetDatabase.GetAssetPath(atlasAsset);
string atlasAssetDirPath = Path.GetDirectoryName(atlasAssetPath);
string bakedDirPath = Path.Combine(atlasAssetDirPath, atlasAsset.name);
string bakedPrefabPath = Path.Combine(bakedDirPath, GetPathSafeRegionName(region) + ".prefab").Replace("\\", "/");
GameObject prefab = (GameObject)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(GameObject));
GameObject root;
Mesh mesh;
bool isNewPrefab = false;
if (!Directory.Exists(bakedDirPath))
Directory.CreateDirectory(bakedDirPath);
if (prefab == null) {
root = new GameObject("temp", typeof(MeshFilter), typeof(MeshRenderer));
prefab = (GameObject)PrefabUtility.CreatePrefab(bakedPrefabPath, root);
isNewPrefab = true;
Object.DestroyImmediate(root);
}
mesh = (Mesh)AssetDatabase.LoadAssetAtPath(bakedPrefabPath, typeof(Mesh));
Material mat = null;
mesh = atlasAsset.GenerateMesh(region.name, mesh, out mat);
if (isNewPrefab) {
AssetDatabase.AddObjectToAsset(mesh, prefab);
prefab.GetComponent<MeshFilter>().sharedMesh = mesh;
}
EditorUtility.SetDirty(mesh);
EditorUtility.SetDirty(prefab);
if (autoSave) {
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
prefab.GetComponent<MeshRenderer>().sharedMaterial = mat;
return prefab;
}
public static string GetPathSafeRegionName (AtlasRegion region) {
return region.name.Replace("/", "_");
}
static SkeletonDataAsset IngestSpineProject (TextAsset spineJson, params AtlasAsset[] atlasAssets) {
string primaryName = Path.GetFileNameWithoutExtension(spineJson.name);
string assetPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(spineJson));
string filePath = assetPath + "/" + primaryName + "_SkeletonData.asset";
if (spineJson != null && atlasAssets != null) {
SkeletonDataAsset skelDataAsset = (SkeletonDataAsset)AssetDatabase.LoadAssetAtPath(filePath, typeof(SkeletonDataAsset));
if (skelDataAsset == null) {
skelDataAsset = SkeletonDataAsset.CreateInstance<SkeletonDataAsset>();
skelDataAsset.atlasAssets = atlasAssets;
skelDataAsset.skeletonJSON = spineJson;
skelDataAsset.fromAnimation = new string[0];
skelDataAsset.toAnimation = new string[0];
skelDataAsset.duration = new float[0];
skelDataAsset.defaultMix = defaultMix;
skelDataAsset.scale = defaultScale;
AssetDatabase.CreateAsset(skelDataAsset, filePath);
AssetDatabase.SaveAssets();
} else {
skelDataAsset.atlasAssets = atlasAssets;
skelDataAsset.Reset();
skelDataAsset.GetSkeletonData(true);
}
return skelDataAsset;
} else {
EditorUtility.DisplayDialog("Error!", "Must specify both Spine JSON and AtlasAsset array", "OK");
return null;
}
}
[MenuItem("Assets/Spine/Instantiate (SkeletonAnimation)")]
static void InstantiateSkeletonAnimation () {
Object[] arr = Selection.objects;
foreach (Object o in arr) {
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(o));
string skinName = EditorPrefs.GetString(guid + "_lastSkin", "");
InstantiateSkeletonAnimation((SkeletonDataAsset)o, skinName);
SceneView.RepaintAll();
}
}
[MenuItem("Assets/Spine/Instantiate (SkeletonAnimation)", true)]
static bool ValidateInstantiateSkeletonAnimation () {
Object[] arr = Selection.objects;
if (arr.Length == 0)
return false;
foreach (Object o in arr) {
if (o.GetType() != typeof(SkeletonDataAsset))
return false;
}
return true;
}
public static SkeletonAnimation InstantiateSkeletonAnimation (SkeletonDataAsset skeletonDataAsset, string skinName) {
return InstantiateSkeletonAnimation(skeletonDataAsset, skeletonDataAsset.GetSkeletonData(true).FindSkin(skinName));
}
public static SkeletonAnimation InstantiateSkeletonAnimation (SkeletonDataAsset skeletonDataAsset, Skin skin = null) {
GameObject go = new GameObject(skeletonDataAsset.name.Replace("_SkeletonData", ""), typeof(MeshFilter), typeof(MeshRenderer), typeof(SkeletonAnimation));
SkeletonAnimation anim = go.GetComponent<SkeletonAnimation>();
anim.skeletonDataAsset = skeletonDataAsset;
bool requiresNormals = false;
foreach (AtlasAsset atlasAsset in anim.skeletonDataAsset.atlasAssets) {
foreach (Material m in atlasAsset.materials) {
if (m.shader.name.Contains("Lit")) {
requiresNormals = true;
break;
}
}
}
anim.calculateNormals = requiresNormals;
SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
if (data == null) {
for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) {
string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]);
skeletonDataAsset.atlasAssets[i] = (AtlasAsset)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAsset));
}
data = skeletonDataAsset.GetSkeletonData(true);
}
if (skin == null)
skin = data.DefaultSkin;
if (skin == null)
skin = data.Skins.Items[0];
anim.Reset();
anim.skeleton.SetSkin(skin);
anim.initialSkinName = skin.Name;
anim.skeleton.Update(1);
anim.state.Update(1);
anim.state.Apply(anim.skeleton);
anim.skeleton.UpdateWorldTransform();
return anim;
}
[MenuItem("Assets/Spine/Instantiate (Mecanim)")]
static void InstantiateSkeletonAnimator () {
Object[] arr = Selection.objects;
foreach (Object o in arr) {
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(o));
string skinName = EditorPrefs.GetString(guid + "_lastSkin", "");
InstantiateSkeletonAnimator((SkeletonDataAsset)o, skinName);
SceneView.RepaintAll();
}
}
[MenuItem("Assets/Spine/Instantiate (SkeletonAnimation)", true)]
static bool ValidateInstantiateSkeletonAnimator () {
Object[] arr = Selection.objects;
if (arr.Length == 0)
return false;
foreach (Object o in arr) {
if (o.GetType() != typeof(SkeletonDataAsset))
return false;
}
return true;
}
public static SkeletonAnimator InstantiateSkeletonAnimator (SkeletonDataAsset skeletonDataAsset, string skinName) {
return InstantiateSkeletonAnimator(skeletonDataAsset, skeletonDataAsset.GetSkeletonData(true).FindSkin(skinName));
}
public static SkeletonAnimator InstantiateSkeletonAnimator (SkeletonDataAsset skeletonDataAsset, Skin skin = null) {
GameObject go = new GameObject(skeletonDataAsset.name.Replace("_SkeletonData", ""), typeof(MeshFilter), typeof(MeshRenderer), typeof(Animator), typeof(SkeletonAnimator));
if (skeletonDataAsset.controller == null) {
SkeletonBaker.GenerateMecanimAnimationClips(skeletonDataAsset);
}
go.GetComponent<Animator>().runtimeAnimatorController = skeletonDataAsset.controller;
SkeletonAnimator anim = go.GetComponent<SkeletonAnimator>();
anim.skeletonDataAsset = skeletonDataAsset;
bool requiresNormals = false;
foreach (AtlasAsset atlasAsset in anim.skeletonDataAsset.atlasAssets) {
foreach (Material m in atlasAsset.materials) {
if (m.shader.name.Contains("Lit")) {
requiresNormals = true;
break;
}
}
}
anim.calculateNormals = requiresNormals;
SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
if (data == null) {
for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) {
string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]);
skeletonDataAsset.atlasAssets[i] = (AtlasAsset)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAsset));
}
data = skeletonDataAsset.GetSkeletonData(true);
}
if (skin == null)
skin = data.DefaultSkin;
if (skin == null)
skin = data.Skins.Items[0];
anim.Reset();
anim.skeleton.SetSkin(skin);
anim.initialSkinName = skin.Name;
anim.skeleton.Update(1);
anim.skeleton.UpdateWorldTransform();
anim.LateUpdate();
return anim;
}
static bool preferencesLoaded = false;
[PreferenceItem("Spine")]
static void PreferencesGUI () {
if (!preferencesLoaded) {
preferencesLoaded = true;
defaultMix = EditorPrefs.GetFloat(DEFAULT_MIX_KEY, 0.2f);
}
EditorGUILayout.LabelField("Auto-Import Settings", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
defaultMix = EditorGUILayout.FloatField("Default Mix", defaultMix);
if (EditorGUI.EndChangeCheck())
EditorPrefs.SetFloat(DEFAULT_MIX_KEY, defaultMix);
GUILayout.Space(20);
EditorGUILayout.LabelField("3rd Party Settings", EditorStyles.boldLabel);
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("TK2D");
if (GUILayout.Button("Enable", GUILayout.Width(64)))
EnableTK2D();
if (GUILayout.Button("Disable", GUILayout.Width(64)))
DisableTK2D();
GUILayout.EndHorizontal();
}
//TK2D Support
const string SPINE_TK2D_DEFINE = "SPINE_TK2D";
static void EnableTK2D () {
bool added = false;
foreach (BuildTargetGroup group in System.Enum.GetValues(typeof(BuildTargetGroup))) {
string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(group);
if (!defines.Contains(SPINE_TK2D_DEFINE)) {
added = true;
if (defines.EndsWith(";"))
defines = defines + SPINE_TK2D_DEFINE;
else
defines = defines + ";" + SPINE_TK2D_DEFINE;
PlayerSettings.SetScriptingDefineSymbolsForGroup(group, defines);
}
}
if (added) {
Debug.LogWarning("Setting Scripting Define Symbol " + SPINE_TK2D_DEFINE);
} else {
Debug.LogWarning("Already Set Scripting Define Symbol " + SPINE_TK2D_DEFINE);
}
}
static void DisableTK2D () {
bool removed = false;
foreach (BuildTargetGroup group in System.Enum.GetValues(typeof(BuildTargetGroup))) {
string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(group);
if (defines.Contains(SPINE_TK2D_DEFINE)) {
removed = true;
if (defines.Contains(SPINE_TK2D_DEFINE + ";"))
defines = defines.Replace(SPINE_TK2D_DEFINE + ";", "");
else
defines = defines.Replace(SPINE_TK2D_DEFINE, "");
PlayerSettings.SetScriptingDefineSymbolsForGroup(group, defines);
}
}
if (removed) {
Debug.LogWarning("Removing Scripting Define Symbol " + SPINE_TK2D_DEFINE);
} else {
Debug.LogWarning("Already Removed Scripting Define Symbol " + SPINE_TK2D_DEFINE);
}
}
public class AtlasRequirementLoader : AttachmentLoader {
List<string> requirementList;
public AtlasRequirementLoader (List<string> requirementList) {
this.requirementList = requirementList;
}
public RegionAttachment NewRegionAttachment (Skin skin, string name, string path) {
requirementList.Add(path);
return new RegionAttachment(name);
}
public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) {
requirementList.Add(path);
return new MeshAttachment(name);
}
public SkinnedMeshAttachment NewSkinnedMeshAttachment (Skin skin, string name, string path) {
requirementList.Add(path);
return new SkinnedMeshAttachment(name);
}
public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name) {
return new BoundingBoxAttachment(name);
}
}
}
| |
//
// 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.
//
#if !SILVERLIGHT
namespace NLog.Targets
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Security;
using Internal.Fakeables;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Writes log message to the Event Log.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/EventLog-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/EventLog/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/EventLog/Simple/Example.cs" />
/// </example>
[Target("EventLog")]
public class EventLogTarget : TargetWithLayout, IInstallable
{
private EventLog eventLogInstance;
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget"/> class.
/// </summary>
public EventLogTarget()
: this(AppDomainWrapper.CurrentDomain)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget"/> class.
/// </summary>
public EventLogTarget(IAppDomain appDomain)
{
this.Source = appDomain.FriendlyName;
this.Log = "Application";
this.MachineName = ".";
}
/// <summary>
/// Gets or sets the name of the machine on which Event Log service is running.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
[DefaultValue(".")]
public string MachineName { get; set; }
/// <summary>
/// Gets or sets the layout that renders event ID.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
public Layout EventId { get; set; }
/// <summary>
/// Gets or sets the layout that renders event Category.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
public Layout Category { get; set; }
/// <summary>
/// Optional entrytype. When not set, or when not convertable to <see cref="LogLevel"/> then determined by <see cref="NLog.LogLevel"/>
/// </summary>
public Layout EntryType { get; set; }
/// <summary>
/// Gets or sets the value to be used as the event Source.
/// </summary>
/// <remarks>
/// By default this is the friendly name of the current AppDomain.
/// </remarks>
/// <docgen category='Event Log Options' order='10' />
public Layout Source { get; set; }
/// <summary>
/// Gets or sets the name of the Event Log to write to. This can be System, Application or
/// any user-defined name.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
[DefaultValue("Application")]
public string Log { get; set; }
/// <summary>
/// Performs installation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Install(InstallationContext installationContext)
{
var fixedSource = GetFixedSource();
//always throw error to keep backwardscomp behavior.
CreateEventSourceIfNeeded(fixedSource, true);
}
/// <summary>
/// Performs uninstallation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Uninstall(InstallationContext installationContext)
{
var fixedSource = GetFixedSource();
if (string.IsNullOrEmpty(fixedSource))
{
InternalLogger.Debug("Skipping removing of event source because it contains layout renderers");
}
else
{
EventLog.DeleteEventSource(fixedSource, this.MachineName);
}
}
/// <summary>
/// Determines whether the item is installed.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <returns>
/// Value indicating whether the item is installed or null if it is not possible to determine.
/// </returns>
public bool? IsInstalled(InstallationContext installationContext)
{
var fixedSource = GetFixedSource();
if (!string.IsNullOrEmpty(fixedSource))
{
return EventLog.SourceExists(fixedSource, this.MachineName);
}
InternalLogger.Debug("Unclear if event source exists because it contains layout renderers");
return null; //unclear!
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
var fixedSource = GetFixedSource();
if (string.IsNullOrEmpty(fixedSource))
{
InternalLogger.Debug("Skipping creation of event source because it contains layout renderers");
}
else
{
var currentSourceName = EventLog.LogNameFromSourceName(fixedSource, this.MachineName);
if (!currentSourceName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
{
this.CreateEventSourceIfNeeded(fixedSource, false);
}
}
}
/// <summary>
/// Writes the specified logging event to the event log.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
string message = this.Layout.Render(logEvent);
if (message.Length > 16384)
{
// limitation of EventLog API
message = message.Substring(0, 16384);
}
var entryType = GetEntryType(logEvent);
int eventId = 0;
if (this.EventId != null)
{
eventId = Convert.ToInt32(this.EventId.Render(logEvent), CultureInfo.InvariantCulture);
}
short category = 0;
if (this.Category != null)
{
category = Convert.ToInt16(this.Category.Render(logEvent), CultureInfo.InvariantCulture);
}
var eventLog = GetEventLog(logEvent);
eventLog.WriteEntry(message, entryType, eventId, category);
}
/// <summary>
/// Get the entry type for logging the message.
/// </summary>
/// <param name="logEvent">The logging event - for rendering the <see cref="EntryType"/></param>
/// <returns></returns>
private EventLogEntryType GetEntryType(LogEventInfo logEvent)
{
if (this.EntryType != null)
{
//try parse, if fail, determine auto
var value = this.EntryType.Render(logEvent);
EventLogEntryType eventLogEntryType;
if (EnumHelpers.TryParse(value, true, out eventLogEntryType))
{
return eventLogEntryType;
}
}
// determine auto
if (logEvent.Level >= LogLevel.Error)
{
return EventLogEntryType.Error;
}
if (logEvent.Level >= LogLevel.Warn)
{
return EventLogEntryType.Warning;
}
return EventLogEntryType.Information;
}
/// <summary>
/// Get the source, if and only if the source is fixed.
/// </summary>
/// <returns><c>null</c> when not <see cref="SimpleLayout.IsFixedText"/></returns>
/// <remarks>Internal for unit tests</remarks>
internal string GetFixedSource()
{
if (this.Source == null)
{
return null;
}
var simpleLayout = Source as SimpleLayout;
if (simpleLayout != null && simpleLayout.IsFixedText)
{
return simpleLayout.FixedText;
}
return null;
}
/// <summary>
/// Get the eventlog to write to.
/// </summary>
/// <param name="logEvent">Event if the source needs to be rendered.</param>
/// <returns></returns>
private EventLog GetEventLog(LogEventInfo logEvent)
{
return eventLogInstance ?? (eventLogInstance = new EventLog(this.Log, this.MachineName, this.Source.Render(logEvent)));
}
/// <summary>
/// (re-)create a event source, if it isn't there. Works only with fixed sourcenames.
/// </summary>
/// <param name="fixedSource">sourcenaam. If source is not fixed (see <see cref="SimpleLayout.IsFixedText"/>, then pass <c>null</c> or emptystring.</param>
/// <param name="alwaysThrowError">always throw an Exception when there is an error</param>
private void CreateEventSourceIfNeeded(string fixedSource, bool alwaysThrowError)
{
if (string.IsNullOrEmpty(fixedSource))
{
InternalLogger.Debug("Skipping creation of event source because it contains layout renderers");
//we can only create event sources if the source is fixed (no layout)
return;
}
// if we throw anywhere, we remain non-operational
try
{
if (EventLog.SourceExists(fixedSource, this.MachineName))
{
string currentLogName = EventLog.LogNameFromSourceName(fixedSource, this.MachineName);
if (!currentLogName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
{
// re-create the association between Log and Source
EventLog.DeleteEventSource(fixedSource, this.MachineName);
var eventSourceCreationData = new EventSourceCreationData(fixedSource, this.Log)
{
MachineName = this.MachineName
};
EventLog.CreateEventSource(eventSourceCreationData);
}
}
else
{
var eventSourceCreationData = new EventSourceCreationData(fixedSource, this.Log)
{
MachineName = this.MachineName
};
EventLog.CreateEventSource(eventSourceCreationData);
}
}
catch (Exception exception)
{
InternalLogger.Error("Error when connecting to EventLog: {0}", exception);
if (alwaysThrowError || exception.MustBeRethrown())
{
throw;
}
throw;
}
}
}
}
#endif
| |
//
// File : ApiDefinition.cs
//
// Author: Simon CORSIN <simoncorsin@gmail.com>
//
// Copyright (c) 2012 Ever SAS
//
// Using or modifying this source code is strictly reserved to Ever SAS.
using System;
using System.Drawing;
using MonoTouch.ObjCRuntime;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.AVFoundation;
using MonoTouch.CoreGraphics;
using MonoTouch.CoreMedia;
using MonoTouch.CoreImage;
using MonoTouch.GLKit;
namespace SCorsin {
[BaseType(typeof(NSObject))]
interface SCPhotoConfiguration {
[Export("enabled")]
bool Enabled { get; set; }
[Export("options")]
NSDictionary Options { get; set; }
}
[BaseType(typeof(NSObject))]
interface SCMediaTypeConfiguration {
[Export("enabled")]
bool Enabled { get; set; }
[Export("shouldIgnore")]
bool ShouldIgnore { get; set; }
[Export("options")]
NSDictionary Options { get; set; }
[Export("bitrate")]
ulong Bitrate { get; set; }
[Export("preset")]
NSString Preset { get; set; }
}
[BaseType(typeof(SCMediaTypeConfiguration))]
interface SCVideoConfiguration {
[Export("size")]
SizeF Size { get; set; }
[Export("affineTransform")]
CGAffineTransform AffineTransform { get; set; }
[Export("codec")]
NSString Codec { get; set; }
[Export("scalingMode")]
NSString ScalingMode { get; set; }
[Export("maxFrameRate")]
int MaxFrameRate { get; set; }
[Export("timeScale")]
float TimeScale { get; set; }
[Export("sizeAsSquare")]
bool SizeAsSquare { get; set; }
[Export("shouldKeepOnlyKeyFrames")]
bool ShouldKeepOnlyKeyFrames { get; set; }
[Export("keepInputAffineTransform")]
bool KeepInputAffineTransform { get; set; }
[Export("filterGroup")]
SCFilterGroup FilterGroup { get; set; }
[Export("composition")]
AVVideoComposition Composition { get; set; }
[Export("watermarkImage")]
UIImage WatermarkImage { get; set; }
[Export("watermarkFrame")]
RectangleF WatermarkFrame { get; set; }
[Export("watermarkAnchorLocation")]
int WatermarkAnchorLocation { get; set; }
}
[BaseType(typeof(SCMediaTypeConfiguration))]
interface SCAudioConfiguration {
[Export("sampleRate")]
int SampleRate { get; set; }
[Export("channelsCount")]
int ChannelsCount { get; set; }
[Export("format")]
int Format { get; set; }
[Export("audioMix")]
AVAudioMix AudioMix { get; set; }
}
public delegate void EndRecordSegmentDelegate(int segmentIndex, NSError errore);
public delegate void GenericErrorDelegate(NSUrl outputUrl, NSError error);
[BaseType(typeof(NSObject))]
interface SCRecordSession {
[Export("initWithDictionaryRepresentation:")]
IntPtr Constructor(NSDictionary dictionaryRepresentation);
[Export("identifier")]
string Identifier { get; }
[Export("date")]
NSDate Date { get; }
[Export("outputUrl")]
NSUrl OutputUrl { get; }
[Export("fileType"), NullAllowed]
NSString FileType { get; set; }
[Export("fileExtension"), NullAllowed]
NSString FileExtension { get; set; }
[Export("recordSegments")]
NSUrl[] RecordSegments { get; }
[Export("currentRecordDuration")]
CMTime CurrentRecordDuration { get; }
[Export("segmentsDuration")]
CMTime SegmentsDuration { get; }
[Export("currentSegmentDuration")]
CMTime CurrentSegmentDuration { get; }
[Export("recordSegmentBegan")]
bool RecordSegmentBegan { get; }
[Export("beginRecordSegment:")]
void BeginRecordSegment(out NSError error);
[Export("endRecordSegment:")]
void EndRecordSegment([NullAllowed] EndRecordSegmentDelegate completionHandler);
[Export("removeSegmentAtIndex:deleteFile:")]
void RemoveSegmentAtIndex(int segmentIndex, bool deleteFile);
[Export("addSegment:")]
void AddSegment(NSUrl fileUrl);
[Export("insertSegment:atIndex:")]
void InsertSegment(NSUrl fileUrl, int segmentIndex);
[Export("removeAllSegments")]
void RemoveAllSegments();
[Export("mergeRecordSegmentsUsingPreset:completionHandler:")]
void MergeRecordSegments(NSString exportSessionPreset, [NullAllowed] GenericErrorDelegate completionHandler);
[Export("cancelSession:")]
void CancelSession([NullAllowed] Action completionHandler);
[Export("removeLastSegment")]
void RemoveLastSegment();
[Export("deinitialize")]
void Deinitialize();
[Export("assetRepresentingRecordSegments")]
AVAsset AssetRepresentingRecordSegments { get; }
[Export("dictionaryRepresentation")]
NSDictionary DictionaryRepresentation { get; }
[Export("recorder")]
SCRecorder Recorder { get; }
}
[Model, BaseType(typeof(NSObject)), Protocol]
interface SCRecorderDelegate {
[Abstract, Export("recorder:didReconfigureVideoInput:"), EventArgs("RecorderDidReconfigureVideoInputDelegate")]
void DidReconfigureVideoInput(SCRecorder recorder, NSError videoInputError);
[Abstract, Export("recorder:didReconfigureAudioInput:"), EventArgs("RecorderDidReconfigureAudioInputDelegate")]
void DidReconfigureAudioInput(SCRecorder recorder, NSError audioInputError);
[Export("recorder:didChangeFlashMode:error:"), Abstract, EventArgs("RecorderDidChangeFlashModeDelegate")]
void DidChangeFlashMode(SCRecorder recorder, int flashMode, NSError error);
[Export("recorder:didChangeSessionPreset:error:"), Abstract, EventArgs("RecorderDidChangeSessionPresetDelegate")]
void DidChangeSessionPreset(SCRecorder recorder, string sessionPreset, NSError error);
[Export("recorderWillStartFocus:"), Abstract, EventArgs("RecorderWillStartFocusDelegate")]
void WillStartFocus(SCRecorder recorder);
[Export("recorderDidStartFocus:"), Abstract, EventArgs("RecorderDidStartFocusDelegate")]
void DidStartFocus(SCRecorder recorder);
[Export("recorderDidEndFocus:"), Abstract, EventArgs("RecorderDidEndFocusDelegate")]
void DidEndFocus(SCRecorder recorder);
[Export("recorder:didInitializeAudioInRecordSession:error:"), Abstract, EventArgs("RecorderDidInitializeAudioInRecordSessionDelegate")]
void DidInitializeAudioInRecordSession(SCRecorder recorder, SCRecordSession recordSession, NSError error);
[Export("recorder:didInitializeVideoInRecordSession:error:"), Abstract, EventArgs("RecorderDidInitializeVideoInRecordSessionDelegate")]
void DidInitializeVideoInRecordSession(SCRecorder recorder, SCRecordSession recordSession, NSError error);
[Export("recorder:didBeginRecordSegment:error:"), Abstract, EventArgs("RecorderDidBeginRecordSegmentDelegate")]
void DidBeginRecordSegment(SCRecorder recorder, SCRecordSession recordSession, NSError error);
[Export("recorder:didEndRecordSegment:segmentIndex:error:"), Abstract, EventArgs("RecorderDidEndRecordSegmentDelegate")]
void DidEndRecordSegment(SCRecorder recorder, SCRecordSession recordSession, int segmentIndex, NSError error);
[Export("recorder:didAppendVideoSampleBuffer:"), Abstract, EventArgs("RecorderDidAppendVideoSampleBufferDelegate")]
void DidAppendVideoSampleBuffer(SCRecorder recorder, SCRecordSession recordSession);
[Export("recorder:didAppendAudioSampleBuffer:"), Abstract, EventArgs("RecorderDidAppendAudioSampleBufferDelegate")]
void DidAppendAudioSampleBuffer(SCRecorder recorder, SCRecordSession recordSession);
[Export("recorder:didSkipAudioSampleBuffer:"), Abstract, EventArgs("RecorderDidSkip")]
void DidSkipAudioSampleBuffer(SCRecorder recorder, SCRecordSession recordSession);
[Export("recorder:didSkipVideoSampleBuffer:"), Abstract, EventArgs("RecorderDidSkip")]
void DidSkipVideoSampleBuffer(SCRecorder recorder, SCRecordSession recordSession);
[Export("recorder:didCompleteRecordSession:"), Abstract, EventArgs("RecorderDidCompleteRecordSessionDelegate")]
void DidCompleteRecordSession(SCRecorder recorder, SCRecordSession recordSession);
}
public delegate void OpenSessionDelegate(NSError sessionError, NSError audioError, NSError videoError, NSError photoError);
public delegate void CapturePhotoDelegate(NSError error, UIImage image);
[BaseType(typeof(NSObject), Delegates = new string [] { "Delegate" }, Events = new Type [] { typeof(SCRecorderDelegate) })]
interface SCRecorder {
[Export("videoConfiguration")]
SCVideoConfiguration VideoConfiguration { get; }
[Export("audioConfiguration")]
SCAudioConfiguration AudioConfiguration { get; }
[Export("photoConfiguration")]
SCPhotoConfiguration PhotoConfiguration { get; }
[Export("delegate")]
NSObject WeakDelegate { get; set; }
[Wrap("WeakDelegate")]
SCRecorderDelegate Delegate { get; set; }
[Export("videoEnabledAndReady")]
bool VideoEnabledAndReady { get; }
[Export("audioEnabledAndReady")]
bool AudioEnabledAndReady { get; }
[Export("fastRecordMethodEnabled")]
bool FastRecordMethodEnabled { get; set; }
[Export("isRecording")]
bool IsRecording { get; }
[Export("deviceHasFlash")]
bool DeviceHasFlash { get; }
[Export("flashMode")]
int FlashMode { get; set; }
[Export("device")]
AVCaptureDevicePosition Device { get; set; }
[Export("focusMode")]
AVCaptureFocusMode FocusMode { get; }
[Export("photoOutputSettings"), NullAllowed]
NSDictionary PhotoOutputSettings { get; set; }
[Export("sessionPreset")]
NSString SessionPreset { get; set; }
[Export("captureSession")]
AVCaptureSession CaptureSession { get; }
[Export("isCaptureSessionOpened")]
bool IsCaptureSessionOpened { get; }
[Export("previewLayer")]
AVCaptureVideoPreviewLayer PreviewLayer { get; }
[Export("previewView"), NullAllowed]
UIView PreviewView { get; set; }
[Export("recordSession"), NullAllowed]
SCRecordSession RecordSession { get; set; }
[Export("videoOrientation")]
AVCaptureVideoOrientation VideoOrientation { get; set; }
[Export("autoSetVideoOrientation")]
bool AutoSetVideoOrientation { get; set; }
[Export("initializeRecordSessionLazily")]
bool InitializeRecordSessionLazily { get; set; }
[Export("frameRate")]
int FrameRate { get; set; }
[Export("focusSupported")]
bool FocusSupported { get; }
[Export("openSession:")]
void OpenSession([NullAllowed] OpenSessionDelegate completionHandler);
[Export("previewViewFrameChanged")]
void PreviewViewFrameChanged();
[Export("closeSession")]
void CloseSession();
[Export("startRunningSession")]
void StartRunningSession();
[Export("endRunningSession")]
void EndRunningSession();
[Export("beginSessionConfiguration")]
void BeginSessionConfiguration();
[Export("commitSessionConfiguration")]
void CommitSessionConfiguration();
[Export("switchCaptureDevices")]
void SwitchCaptureDevices();
[Export("convertToPointOfInterestFromViewCoordinates:")]
PointF ConvertToPointOfInterestFromViewCoordinates(PointF viewCoordinates);
[Export("autoFocusAtPoint:")]
void AutoFocusAtPoint(PointF point);
[Export("continuousFocusAtPoint:")]
void ContinuousFocusAtPoint(PointF point);
[Export("setActiveFormatWithFrameRate:width:andHeight:error:")]
bool SetActiveFormatWithFrameRate(int frameRate, int width, int height, out NSError error);
[Export("focusCenter")]
void FocusCenter();
[Export("record")]
void Record();
[Export("pause")]
void Pause();
[Export("pause:")]
void Pause(Action completionHandler);
[Export("capturePhoto:")]
void CapturePhoto([NullAllowed] CapturePhotoDelegate completionHandler);
[Export("snapshotOfLastVideoBuffer")]
UIImage SnapshotOfLastVideoBuffer();
[Export("snapshotOfLastAppendedVideoBuffer")]
UIImage SnapshotOfLastAppendedVideoBuffer();
[Export("CIImageRenderer"), NullAllowed]
NSObject CIImageRenderer { get; set; }
[Export("ratioRecorded")]
float RatioRecorder { get; }
[Export("maxRecordDuration")]
CMTime MaxRecordDuration { get; set; }
[Export("keepMirroringOnWrite")]
bool KeepMirroringOnWrite { get; set; }
}
delegate void CompletionHandler(NSError error);
[BaseType(typeof(NSObject))]
interface SCAudioTools {
[Static]
[Export("overrideCategoryMixWithOthers")]
void OverrideCategoryMixWithOthers();
[Static]
[Export("mixAudio:startTime:withVideo:affineTransform:toUrl:outputFileType:withMaxDuration:withCompletionBlock:")]
void MixAudioWithVideo(AVAsset audioAsset, CMTime audioStartTime, NSUrl inputUrl, CGAffineTransform affineTransform, NSUrl outputUrl, NSString outputFileType, CMTime maxDuration, CompletionHandler completionHandler);
}
[BaseType(typeof(NSObject))]
interface SCFilter {
[Export("initWithCIFilter:")]
IntPtr Constructor(CIFilter filter);
[Export("coreImageFilter")]
CIFilter CoreImageFilter { get; }
}
[BaseType(typeof(NSObject))]
interface SCFilterGroup {
[Export("initWithFilter:")]
IntPtr Constructor(SCFilter filter);
[Export("addFilter:")]
void AddFilter(SCFilter filter);
[Export("removeFilter:")]
void RemoveFilter(SCFilter filter);
[Export("imageByProcessingImage:")]
CIImage ImageByProcessingImage(CIImage image);
[Export("filters")]
SCFilter[] Filters { get; }
[Export("name")]
string Name { get; set; }
[Export("filterGroupWithData:"), Static]
SCFilterGroup FromData(NSData data);
[Export("filterGroupWithData:error:"), Static]
SCFilterGroup FromData(NSData data, out NSError error);
[Export("filterGroupWithContentsOfUrl:"), Static]
SCFilterGroup FromUrl(NSUrl url);
}
[BaseType(typeof(NSObject))]
[Model, Protocol]
interface SCPlayerDelegate {
[Abstract]
[Export("player:didPlay:loopsCount:"), EventArgs("PlayerDidPlay")]
void DidPlay(SCPlayer player, double secondsElapsed, int loopCount);
[Abstract]
[Export("player:didChangeItem:"), EventArgs("PlayerChangedItem")]
void DidChangeItem(SCPlayer player, [NullAllowed] AVPlayerItem item);
[Abstract]
[Export("player:itemReadyToPlay:"), EventArgs("PlayerChangedItem")]
void ItemReadyToPlay(SCPlayer player, [NullAllowed] AVPlayerItem item);
}
[BaseType(typeof(AVPlayer), Delegates = new string [] { "Delegate" }, Events = new Type [] { typeof(SCPlayerDelegate) })]
interface SCPlayer {
[Export("delegate")]
NSObject WeakDelegate { get; set; }
[Wrap("WeakDelegate")]
SCPlayerDelegate Delegate { get; set; }
[Export("setItemByStringPath:")]
void SetItem([NullAllowed] string stringPath);
[Export("setItemByUrl:")]
void SetItem([NullAllowed] NSUrl url);
[Export("setItemByAsset:")]
void SetItem([NullAllowed] AVAsset asset);
[Export("setItem:")]
void SetItem([NullAllowed] AVPlayerItem item);
[Export("setSmoothLoopItemByStringPath:smoothLoopCount:")]
void SetSmoothLoopItem(string stringPath, uint loopCount);
[Export("setSmoothLoopItemByUrl:smoothLoopCount:")]
void SetSmoothLoopItem(NSUrl assetUrl, uint loopCount);
[Export("setSmoothLoopItemByAsset:smoothLoopCount:")]
void SetSmoothLoopItem(AVAsset asset, uint loopCount);
[Export("playableDuration")]
CMTime PlayableDuration { get; }
[Export("isPlaying")]
bool IsPlaying { get; }
[Export("loopEnabled")]
bool LoopEnabled { get; set; }
[Export("beginSendingPlayMessages")]
void BeginSendingPlayMessages();
[Export("endSendingPlayMessages")]
void EndSendingPlayMessages();
[Export("isSendingPlayMessages")]
bool IsSendingPlayMessages { get; }
[Export("autoRotate")]
bool AutoRotate { get; set; }
[Export("CIImageRenderer"), NullAllowed]
NSObject CIImageRenderer { get; set; }
}
[BaseType(typeof(UIView))]
interface SCVideoPlayerView : SCPlayerDelegate {
[Export("player"), NullAllowed]
SCPlayer Player { get; set; }
[Export("playerLayer")]
AVPlayerLayer PlayerLayer { get; }
[Export("SCImageViewEnabled")]
bool SCImageViewEnabled { get; set; }
[Export("SCImageView")]
SCImageView SCImageView { get; }
}
[BaseType(typeof(UIView))]
interface SCRecorderToolsView {
[Export("recorder")]
SCRecorder Recorder { get; set; }
[Export("outsideFocusTargetImage")]
UIImage OutsideFocusTargetImage { get; set; }
[Export("insideFocusTargetImage")]
UIImage InsideFocusTargetImage { get; set; }
[Export("focusTargetSize")]
SizeF FocusTargetSize { get; set; }
[Export("showFocusAnimation")]
void ShowFocusAnimation();
[Export("hideFocusAnimation")]
void HideFocusAnimation();
[Export("minZoomFactor")]
float MinZoomFactor { get; set; }
[Export("maxZoomFactor")]
float MaxZoomFactor { get; set; }
[Export("tapToFocusEnabled")]
bool TapToFocusEnabled { get; set; }
[Export("doubleTapToResetFocusEnabled")]
bool DoubleTapToResetFocusEnabled { get; set; }
[Export("pinchToZoomEnabled")]
bool PinchToZoomEnabled { get; set; }
[Export("showsFocusAnimationAutomatically")]
bool ShowsFocusAnimationAutomatically { get; set; }
}
[BaseType(typeof(NSObject))]
interface SCAssetExportSession {
[Export("inputAsset")]
AVAsset InputAsset { get; set; }
[Export("outputUrl")]
NSUrl OutputUrl { get; set; }
[Export("outputFileType")]
NSString OutputFileType { get; set; }
[Export("videoConfiguration")]
SCVideoConfiguration VideoConfiguration { get;}
[Export("audioConfiguration")]
SCAudioConfiguration AudioConfiguration { get; }
[Export("error")]
NSError Error { get; }
[Export("initWithAsset:")]
IntPtr Constructor(AVAsset inputAsset);
[Export("exportAsynchronouslyWithCompletionHandler:")]
void ExportAsynchronously(Action completionHandler);
[Export("useGPUForRenderingFilters")]
bool UseGPUForRenderingFilters { get; set; }
}
[BaseType(typeof(UIView))]
interface SCFilterSelectorView {
[Export("filterGroups"), NullAllowed]
SCFilterGroup[] FilterGroups { get; set; }
[Export("CIImage"), NullAllowed]
CIImage CIImage { get; set; }
[Export("selectedFilterGroup")]
SCFilterGroup SelectedFilterGroup { get; }
[Export("preferredCIImageTransform")]
CGAffineTransform PreferredCIImageTransform { get; set; }
[Export("currentlyDisplayedImageWithScale:orientation:")]
UIImage CurrentlyDisplayedImage(float scale, UIImageOrientation orientation);
}
[BaseType(typeof(SCFilterSelectorView))]
interface SCSwipeableFilterView {
[Export("selectFilterScrollView")]
UIScrollView SelectFilterScrollView { get; }
[Export("refreshAutomaticallyWhenScrolling")]
bool RefreshAutomaticallyWhenScrolling { get; set; }
}
[BaseType(typeof(GLKView))]
interface SCImageView {
[Export("CIImage"), NullAllowed]
CIImage CIImage { get; set; }
[Export("filterGroup"), NullAllowed]
SCFilterGroup FilterGroup { get; set; }
}
}
| |
// Type: UnityEngine.Vector2
// Assembly: UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// Assembly location: C:\Program Files (x86)\Unity\Editor\Data\Managed\UnityEngine.dll
using System;
using System.Runtime.CompilerServices;
namespace UnityEngine
{
public struct Vector2d
{
public const double kEpsilon = 1E-05d;
public double x;
public double y;
public double this[int index]
{
get
{
switch (index)
{
case 0:
return this.x;
case 1:
return this.y;
default:
throw new IndexOutOfRangeException("Invalid Vector2d index!");
}
}
set
{
switch (index)
{
case 0:
this.x = value;
break;
case 1:
this.y = value;
break;
default:
throw new IndexOutOfRangeException("Invalid Vector2d index!");
}
}
}
public Vector2d normalized
{
get
{
Vector2d vector2d = new Vector2d(this.x, this.y);
vector2d.Normalize();
return vector2d;
}
}
public double magnitude
{
get
{
return Mathd.Sqrt(this.x * this.x + this.y * this.y);
}
}
public double sqrMagnitude
{
get
{
return this.x * this.x + this.y * this.y;
}
}
public static Vector2d zero
{
get
{
return new Vector2d(0.0d, 0.0d);
}
}
public static Vector2d one
{
get
{
return new Vector2d(1d, 1d);
}
}
public static Vector2d up
{
get
{
return new Vector2d(0.0d, 1d);
}
}
public static Vector2d right
{
get
{
return new Vector2d(1d, 0.0d);
}
}
public Vector2d(double x, double y)
{
this.x = x;
this.y = y;
}
public static implicit operator Vector2d(Vector3d v)
{
return new Vector2d(v.x, v.y);
}
public static implicit operator Vector3d(Vector2d v)
{
return new Vector3d(v.x, v.y, 0.0d);
}
public static Vector2d operator +(Vector2d a, Vector2d b)
{
return new Vector2d(a.x + b.x, a.y + b.y);
}
public static Vector2d operator -(Vector2d a, Vector2d b)
{
return new Vector2d(a.x - b.x, a.y - b.y);
}
public static Vector2d operator -(Vector2d a)
{
return new Vector2d(-a.x, -a.y);
}
public static Vector2d operator *(Vector2d a, double d)
{
return new Vector2d(a.x * d, a.y * d);
}
public static Vector2d operator *(float d, Vector2d a)
{
return new Vector2d(a.x * d, a.y * d);
}
public static Vector2d operator /(Vector2d a, double d)
{
return new Vector2d(a.x / d, a.y / d);
}
public static bool operator ==(Vector2d lhs, Vector2d rhs)
{
return Vector2d.SqrMagnitude(lhs - rhs) < 0.0 / 1.0;
}
public static bool operator !=(Vector2d lhs, Vector2d rhs)
{
return (double)Vector2d.SqrMagnitude(lhs - rhs) >= 0.0 / 1.0;
}
public void Set(double new_x, double new_y)
{
this.x = new_x;
this.y = new_y;
}
public static Vector2d Lerp(Vector2d from, Vector2d to, double t)
{
t = Mathd.Clamp01(t);
return new Vector2d(from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t);
}
public static Vector2d MoveTowards(Vector2d current, Vector2d target, double maxDistanceDelta)
{
Vector2d vector2 = target - current;
double magnitude = vector2.magnitude;
if (magnitude <= maxDistanceDelta || magnitude == 0.0d)
return target;
else
return current + vector2 / magnitude * maxDistanceDelta;
}
public static Vector2d Scale(Vector2d a, Vector2d b)
{
return new Vector2d(a.x * b.x, a.y * b.y);
}
public void Scale(Vector2d scale)
{
this.x *= scale.x;
this.y *= scale.y;
}
public void Normalize()
{
double magnitude = this.magnitude;
if (magnitude > 9.99999974737875E-06)
this = this / magnitude;
else
this = Vector2d.zero;
}
public override string ToString()
{
return this.x + " - " + this.y;
//string fmt = "({0:D1}, {1:D1})";
//object[] objArray = new object[2];
//int index1 = 0;
//// ISSUE: variable of a boxed type
//__Boxed<double> local1 = (ValueType)this.x;
//objArray[index1] = (object)local1;
//int index2 = 1;
//// ISSUE: variable of a boxed type
//__Boxed<double> local2 = (ValueType)this.y;
//objArray[index2] = (object)local2;
return "not implemented";
}
public string ToString(string format)
{
/* TODO:
string fmt = "({0}, {1})";
object[] objArray = new object[2];
int index1 = 0;
string str1 = this.x.ToString(format);
objArray[index1] = (object) str1;
int index2 = 1;
string str2 = this.y.ToString(format);
objArray[index2] = (object) str2;
*/
return "not implemented";
}
public override int GetHashCode()
{
return this.x.GetHashCode() ^ this.y.GetHashCode() << 2;
}
public override bool Equals(object other)
{
if (!(other is Vector2d))
return false;
Vector2d vector2d = (Vector2d)other;
if (this.x.Equals(vector2d.x))
return this.y.Equals(vector2d.y);
else
return false;
}
public static double Dot(Vector2d lhs, Vector2d rhs)
{
return lhs.x * rhs.x + lhs.y * rhs.y;
}
public static double Angle(Vector2d from, Vector2d to)
{
return Mathd.Acos(Mathd.Clamp(Vector2d.Dot(from.normalized, to.normalized), -1d, 1d)) * 57.29578d;
}
public static double Distance(Vector2d a, Vector2d b)
{
return (a - b).magnitude;
}
public static Vector2d ClampMagnitude(Vector2d vector, double maxLength)
{
if (vector.sqrMagnitude > maxLength * maxLength)
return vector.normalized * maxLength;
else
return vector;
}
public static double SqrMagnitude(Vector2d a)
{
return (a.x * a.x + a.y * a.y);
}
public double SqrMagnitude()
{
return (this.x * this.x + this.y * this.y);
}
public static Vector2d Min(Vector2d lhs, Vector2d rhs)
{
return new Vector2d(Mathd.Min(lhs.x, rhs.x), Mathd.Min(lhs.y, rhs.y));
}
public static Vector2d Max(Vector2d lhs, Vector2d rhs)
{
return new Vector2d(Mathd.Max(lhs.x, rhs.x), Mathd.Max(lhs.y, rhs.y));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Protocol;
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// An Azure Batch task to add.
/// </summary>
public partial class TaskAddParameter
{
/// <summary>
/// Initializes a new instance of the TaskAddParameter class.
/// </summary>
public TaskAddParameter()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the TaskAddParameter class.
/// </summary>
/// <param name="id">A string that uniquely identifies the task within
/// the job.</param>
/// <param name="commandLine">The command line of the task.</param>
/// <param name="displayName">A display name for the task.</param>
/// <param name="exitConditions">How the Batch service should respond
/// when the task completes.</param>
/// <param name="resourceFiles">A list of files that the Batch service
/// will download to the compute node before running the command
/// line.</param>
/// <param name="outputFiles">A list of files that the Batch service
/// will upload from the compute node after running the command
/// line.</param>
/// <param name="environmentSettings">A list of environment variable
/// settings for the task.</param>
/// <param name="affinityInfo">A locality hint that can be used by the
/// Batch service to select a compute node on which to start the new
/// task.</param>
/// <param name="constraints">The execution constraints that apply to
/// this task.</param>
/// <param name="userIdentity">The user identity under which the task
/// runs.</param>
/// <param name="multiInstanceSettings">An object that indicates that
/// the task is a multi-instance task, and contains information about
/// how to run the multi-instance task.</param>
/// <param name="dependsOn">The tasks that this task depends
/// on.</param>
/// <param name="applicationPackageReferences">A list of application
/// packages that the Batch service will deploy to the compute node
/// before running the command line.</param>
/// <param name="authenticationTokenSettings">The settings for an
/// authentication token that the task can use to perform Batch service
/// operations.</param>
public TaskAddParameter(string id, string commandLine, string displayName = default(string), ExitConditions exitConditions = default(ExitConditions), IList<ResourceFile> resourceFiles = default(IList<ResourceFile>), IList<OutputFile> outputFiles = default(IList<OutputFile>), IList<EnvironmentSetting> environmentSettings = default(IList<EnvironmentSetting>), AffinityInformation affinityInfo = default(AffinityInformation), TaskConstraints constraints = default(TaskConstraints), UserIdentity userIdentity = default(UserIdentity), MultiInstanceSettings multiInstanceSettings = default(MultiInstanceSettings), TaskDependencies dependsOn = default(TaskDependencies), IList<ApplicationPackageReference> applicationPackageReferences = default(IList<ApplicationPackageReference>), AuthenticationTokenSettings authenticationTokenSettings = default(AuthenticationTokenSettings))
{
Id = id;
DisplayName = displayName;
CommandLine = commandLine;
ExitConditions = exitConditions;
ResourceFiles = resourceFiles;
OutputFiles = outputFiles;
EnvironmentSettings = environmentSettings;
AffinityInfo = affinityInfo;
Constraints = constraints;
UserIdentity = userIdentity;
MultiInstanceSettings = multiInstanceSettings;
DependsOn = dependsOn;
ApplicationPackageReferences = applicationPackageReferences;
AuthenticationTokenSettings = authenticationTokenSettings;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a string that uniquely identifies the task within the
/// job.
/// </summary>
/// <remarks>
/// The ID can contain any combination of alphanumeric characters
/// including hyphens and underscores, and cannot contain more than 64
/// characters. The ID is case-preserving and case-insensitive (that
/// is, you may not have two IDs within a job that differ only by
/// case).
/// </remarks>
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// Gets or sets a display name for the task.
/// </summary>
/// <remarks>
/// The display name need not be unique and can contain any Unicode
/// characters up to a maximum length of 1024.
/// </remarks>
[JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// For multi-instance tasks, the command line is executed as the
/// primary task, after the primary task and all subtasks have finished
/// executing the coordination command line. The command line does not
/// run under a shell, and therefore cannot take advantage of shell
/// features such as environment variable expansion. If you want to
/// take advantage of such features, you should invoke the shell in the
/// command line, for example using "cmd /c MyCommand" in Windows or
/// "/bin/sh -c MyCommand" in Linux.
/// </remarks>
[JsonProperty(PropertyName = "commandLine")]
public string CommandLine { get; set; }
/// <summary>
/// Gets or sets how the Batch service should respond when the task
/// completes.
/// </summary>
[JsonProperty(PropertyName = "exitConditions")]
public ExitConditions ExitConditions { get; set; }
/// <summary>
/// Gets or sets a list of files that the Batch service will download
/// to the compute node before running the command line.
/// </summary>
/// <remarks>
/// For multi-instance tasks, the resource files will only be
/// downloaded to the compute node on which the primary task is
/// executed.
/// </remarks>
[JsonProperty(PropertyName = "resourceFiles")]
public IList<ResourceFile> ResourceFiles { get; set; }
/// <summary>
/// Gets or sets a list of files that the Batch service will upload
/// from the compute node after running the command line.
/// </summary>
/// <remarks>
/// For multi-instance tasks, the files will only be uploaded from the
/// compute node on which the primary task is executed.
/// </remarks>
[JsonProperty(PropertyName = "outputFiles")]
public IList<OutputFile> OutputFiles { get; set; }
/// <summary>
/// Gets or sets a list of environment variable settings for the task.
/// </summary>
[JsonProperty(PropertyName = "environmentSettings")]
public IList<EnvironmentSetting> EnvironmentSettings { get; set; }
/// <summary>
/// Gets or sets a locality hint that can be used by the Batch service
/// to select a compute node on which to start the new task.
/// </summary>
[JsonProperty(PropertyName = "affinityInfo")]
public AffinityInformation AffinityInfo { get; set; }
/// <summary>
/// Gets or sets the execution constraints that apply to this task.
/// </summary>
/// <remarks>
/// If you do not specify constraints, the maxTaskRetryCount is the
/// maxTaskRetryCount specified for the job, and the maxWallClockTime
/// and retentionTime are infinite.
/// </remarks>
[JsonProperty(PropertyName = "constraints")]
public TaskConstraints Constraints { get; set; }
/// <summary>
/// Gets or sets the user identity under which the task runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to
/// the task.
/// </remarks>
[JsonProperty(PropertyName = "userIdentity")]
public UserIdentity UserIdentity { get; set; }
/// <summary>
/// Gets or sets an object that indicates that the task is a
/// multi-instance task, and contains information about how to run the
/// multi-instance task.
/// </summary>
[JsonProperty(PropertyName = "multiInstanceSettings")]
public MultiInstanceSettings MultiInstanceSettings { get; set; }
/// <summary>
/// Gets or sets the tasks that this task depends on.
/// </summary>
/// <remarks>
/// This task will not be scheduled until all tasks that it depends on
/// have completed successfully. If any of those tasks fail and exhaust
/// their retry counts, this task will never be scheduled. If the job
/// does not have usesTaskDependencies set to true, and this element is
/// present, the request fails with error code
/// TaskDependenciesNotSpecifiedOnJob.
/// </remarks>
[JsonProperty(PropertyName = "dependsOn")]
public TaskDependencies DependsOn { get; set; }
/// <summary>
/// Gets or sets a list of application packages that the Batch service
/// will deploy to the compute node before running the command line.
/// </summary>
/// <remarks>
/// Application packages are downloaded and deployed to a shared
/// directory, not the task working directory. Therefore, if a
/// referenced package is already on the compute node, and is up to
/// date, then it is not re-downloaded; the existing copy on the
/// compute node is used. If a referenced application package cannot be
/// installed, for example because the package has been deleted or
/// because download failed, the task fails.
/// </remarks>
[JsonProperty(PropertyName = "applicationPackageReferences")]
public IList<ApplicationPackageReference> ApplicationPackageReferences { get; set; }
/// <summary>
/// Gets or sets the settings for an authentication token that the task
/// can use to perform Batch service operations.
/// </summary>
/// <remarks>
/// If this property is set, the Batch service provides the task with
/// an authentication token which can be used to authenticate Batch
/// service operations without requiring an account access key. The
/// token is provided via the AZ_BATCH_AUTHENTICATION_TOKEN environment
/// variable. The operations that the task can carry out using the
/// token depend on the settings. For example, a task can request job
/// permissions in order to add other tasks to the job, or check the
/// status of the job or of other tasks under the job.
/// </remarks>
[JsonProperty(PropertyName = "authenticationTokenSettings")]
public AuthenticationTokenSettings AuthenticationTokenSettings { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Id == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Id");
}
if (CommandLine == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "CommandLine");
}
if (ResourceFiles != null)
{
foreach (var element in ResourceFiles)
{
if (element != null)
{
element.Validate();
}
}
}
if (OutputFiles != null)
{
foreach (var element1 in OutputFiles)
{
if (element1 != null)
{
element1.Validate();
}
}
}
if (EnvironmentSettings != null)
{
foreach (var element2 in EnvironmentSettings)
{
if (element2 != null)
{
element2.Validate();
}
}
}
if (AffinityInfo != null)
{
AffinityInfo.Validate();
}
if (MultiInstanceSettings != null)
{
MultiInstanceSettings.Validate();
}
if (ApplicationPackageReferences != null)
{
foreach (var element3 in ApplicationPackageReferences)
{
if (element3 != null)
{
element3.Validate();
}
}
}
}
}
}
| |
using System.Linq;
using NUnit.Framework;
using Assert = ModestTree.Assert;
namespace Zenject.Tests.Bindings
{
[TestFixture]
public class TestFromResolve : ZenjectUnitTestFixture
{
[Test]
public void TestTransient()
{
var foo = new Foo();
Container.BindInstance(foo);
Container.Bind<IFoo>().To<Foo>().FromResolve();
Assert.IsEqual(Container.Resolve<IFoo>(), Container.Resolve<Foo>());
Assert.IsEqual(Container.Resolve<IFoo>(), foo);
}
[Test]
public void TestIdentifier()
{
var foo = new Foo();
Container.Bind<Foo>().WithId("foo").FromInstance(foo);
Container.Bind<IFoo>().To<Foo>().FromResolve("foo");
Assert.IsEqual(Container.Resolve<IFoo>(), Container.ResolveId<Foo>("foo"));
Assert.IsEqual(Container.Resolve<IFoo>(), foo);
}
[Test]
public void TestCached()
{
Container.Bind<Foo>().AsTransient();
Container.Bind<IFoo>().To<Foo>().FromResolve().AsCached();
Assert.IsNotEqual(Container.Resolve<Foo>(), Container.Resolve<Foo>());
Assert.IsEqual(Container.Resolve<IFoo>(), Container.Resolve<IFoo>());
}
[Test]
public void TestSingle()
{
var foo = new Foo();
Container.Bind<Foo>().FromInstance(foo);
Container.Bind<IFoo>().To<Foo>().FromResolve();
Assert.IsEqual(Container.Resolve<IFoo>(), foo);
Assert.IsEqual(Container.Resolve<IFoo>(), Container.Resolve<IFoo>());
Assert.IsEqual(Container.Resolve<IFoo>(), Container.Resolve<Foo>());
}
[Test]
public void TestNoMatch()
{
Container.Bind<IFoo>().To<Foo>().FromResolve();
Assert.Throws(() => Container.Resolve<IFoo>());
}
[Test]
public void TestSingleFailure()
{
Container.Bind<Foo>().AsCached();
Container.Bind<Foo>().AsCached();
Container.Bind<IFoo>().To<Foo>().FromResolve();
Assert.Throws(() => Container.Resolve<IFoo>());
}
[Test]
public void TestInfiniteLoop()
{
Container.Bind<IFoo>().To<IFoo>().FromResolve().AsSingle();
Assert.Throws(() => Container.Resolve<IFoo>());
}
[Test]
public void TestResolveManyTransient()
{
Container.Bind<Foo>().AsTransient();
Container.Bind<Foo>().FromInstance(new Foo());
Container.Bind<IFoo>().To<Foo>().FromResolveAll();
Assert.IsEqual(Container.ResolveAll<IFoo>().Count, 2);
}
[Test]
public void TestResolveManyTransient2()
{
Container.Bind<Foo>().AsTransient();
Container.Bind<Foo>().FromInstance(new Foo());
Container.Bind(typeof(IFoo), typeof(IBar)).To<Foo>().FromResolveAll();
Assert.IsEqual(Container.ResolveAll<IFoo>().Count, 2);
Assert.IsEqual(Container.ResolveAll<IBar>().Count, 2);
}
[Test]
public void TestResolveManyCached()
{
Container.Bind<Foo>().AsTransient();
Container.Bind<Foo>().AsTransient();
Container.Bind<IFoo>().To<Foo>().FromResolveAll().AsCached();
Assert.IsEqual(Container.ResolveAll<IFoo>().Count, 2);
Assert.That(Enumerable.SequenceEqual(Container.ResolveAll<IFoo>(), Container.ResolveAll<IFoo>()));
}
[Test]
public void TestResolveManyCached2()
{
Container.Bind<Foo>().AsTransient();
Container.Bind<Foo>().AsTransient();
Container.Bind(typeof(IFoo), typeof(IBar)).To<Foo>().FromResolveAll().AsCached();
Assert.IsEqual(Container.ResolveAll<IBar>().Count, 2);
Assert.IsEqual(Container.ResolveAll<IFoo>().Count, 2);
Assert.That(Enumerable.SequenceEqual(Container.ResolveAll<IFoo>().Cast<object>(), Container.ResolveAll<IBar>().Cast<object>()));
}
[Test]
public void TestResolveManyCached3()
{
Container.Bind<Foo>().AsTransient();
Container.Bind<Foo>().AsTransient();
Container.Bind<IFoo>().To<Foo>().FromResolveAll().AsCached();
Container.Bind<IBar>().To<Foo>().FromResolveAll().AsCached();
Assert.IsEqual(Container.ResolveAll<IFoo>().Count, 2);
Assert.IsEqual(Container.ResolveAll<IBar>().Count, 2);
Assert.That(!Enumerable.SequenceEqual(Container.ResolveAll<IFoo>().Cast<object>(), Container.ResolveAll<IBar>().Cast<object>()));
}
[Test]
public void TestResolveSingleLocal()
{
var foo1 = new Foo();
var foo2 = new Foo();
Container.Bind<Foo>().FromInstance(foo1);
var subContainer = Container.CreateSubContainer();
subContainer.Bind<Foo>().FromInstance(foo2);
subContainer.Bind<IFoo>().To<Foo>().FromResolve();
Assert.IsEqual(subContainer.Resolve<IFoo>(), foo2);
}
[Test]
public void TestInjectSource1()
{
var foo1 = new Foo();
var foo2 = new Foo();
Container.Bind<Foo>().FromInstance(foo1);
var subContainer = Container.CreateSubContainer();
subContainer.Bind<Foo>().FromInstance(foo2);
subContainer.Bind<IFoo>().To<Foo>().FromResolve(null, InjectSources.Parent);
Assert.IsEqual(subContainer.Resolve<IFoo>(), foo1);
}
[Test]
public void TestInjectSource2()
{
var foo1 = new Foo();
var foo2 = new Foo();
var foo3 = new Foo();
Container.Bind<Foo>().FromInstance(foo1);
var subContainer = Container.CreateSubContainer();
subContainer.Bind<Foo>().FromInstance(foo2);
subContainer.Bind<Foo>().FromInstance(foo3);
subContainer.Bind<IFoo>().To<Foo>().FromResolveAll(null, InjectSources.Local);
Assert.Throws(() => subContainer.Resolve<IFoo>());
Assert.That(Enumerable.SequenceEqual(subContainer.ResolveAll<IFoo>(), new [] { foo2, foo3, }));
}
interface IBar
{
}
interface IFoo
{
}
class Foo : IFoo, IBar
{
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.